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/WorkQueue.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 "WorkQueue.h"
#include "include/compat.h"
#include "common/errno.h"
#define dout_subsys ceph_subsys_tp
#undef dout_prefix
#define dout_prefix *_dout << name << " "
ThreadPool::ThreadPool(CephContext *cct_, std::string nm, std::string tn, int n, const char *option)
: cct(cct_), name(std::move(nm)), thread_name(std::move(tn)),
lockname(name + "::lock"),
_lock(ceph::make_mutex(lockname)), // this should be safe due to declaration order
_stop(false),
_pause(0),
_draining(0),
_num_threads(n),
processing(0)
{
if (option) {
_thread_num_option = option;
// set up conf_keys
_conf_keys = new const char*[2];
_conf_keys[0] = _thread_num_option.c_str();
_conf_keys[1] = NULL;
} else {
_conf_keys = new const char*[1];
_conf_keys[0] = NULL;
}
}
void ThreadPool::TPHandle::suspend_tp_timeout()
{
cct->get_heartbeat_map()->clear_timeout(hb);
}
void ThreadPool::TPHandle::reset_tp_timeout()
{
cct->get_heartbeat_map()->reset_timeout(
hb, grace, suicide_grace);
}
ThreadPool::~ThreadPool()
{
ceph_assert(_threads.empty());
delete[] _conf_keys;
}
void ThreadPool::handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed)
{
if (changed.count(_thread_num_option)) {
char *buf;
int r = conf.get_val(_thread_num_option.c_str(), &buf, -1);
ceph_assert(r >= 0);
int v = atoi(buf);
free(buf);
if (v >= 0) {
_lock.lock();
_num_threads = v;
start_threads();
_cond.notify_all();
_lock.unlock();
}
}
}
void ThreadPool::worker(WorkThread *wt)
{
std::unique_lock ul(_lock);
ldout(cct,10) << "worker start" << dendl;
std::stringstream ss;
ss << name << " thread " << (void *)pthread_self();
auto hb = cct->get_heartbeat_map()->add_worker(ss.str(), pthread_self());
while (!_stop) {
// manage dynamic thread pool
join_old_threads();
if (_threads.size() > _num_threads) {
ldout(cct,1) << " worker shutting down; too many threads (" << _threads.size() << " > " << _num_threads << ")" << dendl;
_threads.erase(wt);
_old_threads.push_back(wt);
break;
}
if (work_queues.empty()) {
ldout(cct, 10) << "worker no work queues" << dendl;
} else if (!_pause) {
WorkQueue_* wq;
int tries = 2 * work_queues.size();
bool did = false;
while (tries--) {
next_work_queue %= work_queues.size();
wq = work_queues[next_work_queue++];
void *item = wq->_void_dequeue();
if (item) {
processing++;
ldout(cct,12) << "worker wq " << wq->name << " start processing " << item
<< " (" << processing << " active)" << dendl;
ul.unlock();
TPHandle tp_handle(cct, hb, wq->timeout_interval.load(), wq->suicide_interval.load());
tp_handle.reset_tp_timeout();
wq->_void_process(item, tp_handle);
ul.lock();
wq->_void_process_finish(item);
processing--;
ldout(cct,15) << "worker wq " << wq->name << " done processing " << item
<< " (" << processing << " active)" << dendl;
if (_pause || _draining)
_wait_cond.notify_all();
did = true;
break;
}
}
if (did)
continue;
}
ldout(cct,20) << "worker waiting" << dendl;
cct->get_heartbeat_map()->reset_timeout(
hb,
ceph::make_timespan(cct->_conf->threadpool_default_timeout),
ceph::make_timespan(0));
auto wait = std::chrono::seconds(
cct->_conf->threadpool_empty_queue_max_wait);
_cond.wait_for(ul, wait);
}
ldout(cct,1) << "worker finish" << dendl;
cct->get_heartbeat_map()->remove_worker(hb);
}
void ThreadPool::start_threads()
{
ceph_assert(ceph_mutex_is_locked(_lock));
while (_threads.size() < _num_threads) {
WorkThread *wt = new WorkThread(this);
ldout(cct, 10) << "start_threads creating and starting " << wt << dendl;
_threads.insert(wt);
wt->create(thread_name.c_str());
}
}
void ThreadPool::join_old_threads()
{
ceph_assert(ceph_mutex_is_locked(_lock));
while (!_old_threads.empty()) {
ldout(cct, 10) << "join_old_threads joining and deleting " << _old_threads.front() << dendl;
_old_threads.front()->join();
delete _old_threads.front();
_old_threads.pop_front();
}
}
void ThreadPool::start()
{
ldout(cct,10) << "start" << dendl;
if (_thread_num_option.length()) {
ldout(cct, 10) << " registering config observer on " << _thread_num_option << dendl;
cct->_conf.add_observer(this);
}
_lock.lock();
start_threads();
_lock.unlock();
ldout(cct,15) << "started" << dendl;
}
void ThreadPool::stop(bool clear_after)
{
ldout(cct,10) << "stop" << dendl;
if (_thread_num_option.length()) {
ldout(cct, 10) << " unregistering config observer on " << _thread_num_option << dendl;
cct->_conf.remove_observer(this);
}
_lock.lock();
_stop = true;
_cond.notify_all();
join_old_threads();
_lock.unlock();
for (auto p = _threads.begin(); p != _threads.end(); ++p) {
(*p)->join();
delete *p;
}
_threads.clear();
_lock.lock();
for (unsigned i=0; i<work_queues.size(); i++)
work_queues[i]->_clear();
_stop = false;
_lock.unlock();
ldout(cct,15) << "stopped" << dendl;
}
void ThreadPool::pause()
{
std::unique_lock ul(_lock);
ldout(cct,10) << "pause" << dendl;
_pause++;
while (processing) {
_wait_cond.wait(ul);
}
ldout(cct,15) << "paused" << dendl;
}
void ThreadPool::pause_new()
{
ldout(cct,10) << "pause_new" << dendl;
_lock.lock();
_pause++;
_lock.unlock();
}
void ThreadPool::unpause()
{
ldout(cct,10) << "unpause" << dendl;
_lock.lock();
ceph_assert(_pause > 0);
_pause--;
_cond.notify_all();
_lock.unlock();
}
void ThreadPool::drain(WorkQueue_* wq)
{
std::unique_lock ul(_lock);
ldout(cct,10) << "drain" << dendl;
_draining++;
while (processing || (wq != NULL && !wq->_empty())) {
_wait_cond.wait(ul);
}
_draining--;
}
ShardedThreadPool::ShardedThreadPool(CephContext *pcct_, std::string nm, std::string tn,
uint32_t pnum_threads):
cct(pcct_),
name(std::move(nm)),
thread_name(std::move(tn)),
lockname(name + "::lock"),
shardedpool_lock(ceph::make_mutex(lockname)),
num_threads(pnum_threads),
num_paused(0),
num_drained(0),
wq(NULL) {}
void ShardedThreadPool::shardedthreadpool_worker(uint32_t thread_index)
{
ceph_assert(wq != NULL);
ldout(cct,10) << "worker start" << dendl;
std::stringstream ss;
ss << name << " thread " << (void *)pthread_self();
auto hb = cct->get_heartbeat_map()->add_worker(ss.str(), pthread_self());
while (!stop_threads) {
if (pause_threads) {
std::unique_lock ul(shardedpool_lock);
++num_paused;
wait_cond.notify_all();
while (pause_threads) {
cct->get_heartbeat_map()->reset_timeout(
hb,
wq->timeout_interval.load(),
wq->suicide_interval.load());
shardedpool_cond.wait_for(
ul,
std::chrono::seconds(cct->_conf->threadpool_empty_queue_max_wait));
}
--num_paused;
}
if (drain_threads) {
std::unique_lock ul(shardedpool_lock);
if (wq->is_shard_empty(thread_index)) {
++num_drained;
wait_cond.notify_all();
while (drain_threads) {
cct->get_heartbeat_map()->reset_timeout(
hb,
wq->timeout_interval.load(),
wq->suicide_interval.load());
shardedpool_cond.wait_for(
ul,
std::chrono::seconds(cct->_conf->threadpool_empty_queue_max_wait));
}
--num_drained;
}
}
cct->get_heartbeat_map()->reset_timeout(
hb,
wq->timeout_interval.load(),
wq->suicide_interval.load());
wq->_process(thread_index, hb);
}
ldout(cct,10) << "sharded worker finish" << dendl;
cct->get_heartbeat_map()->remove_worker(hb);
}
void ShardedThreadPool::start_threads()
{
ceph_assert(ceph_mutex_is_locked(shardedpool_lock));
int32_t thread_index = 0;
while (threads_shardedpool.size() < num_threads) {
WorkThreadSharded *wt = new WorkThreadSharded(this, thread_index);
ldout(cct, 10) << "start_threads creating and starting " << wt << dendl;
threads_shardedpool.push_back(wt);
wt->create(thread_name.c_str());
thread_index++;
}
}
void ShardedThreadPool::start()
{
ldout(cct,10) << "start" << dendl;
shardedpool_lock.lock();
start_threads();
shardedpool_lock.unlock();
ldout(cct,15) << "started" << dendl;
}
void ShardedThreadPool::stop()
{
ldout(cct,10) << "stop" << dendl;
stop_threads = true;
ceph_assert(wq != NULL);
wq->return_waiting_threads();
for (auto p = threads_shardedpool.begin();
p != threads_shardedpool.end();
++p) {
(*p)->join();
delete *p;
}
threads_shardedpool.clear();
ldout(cct,15) << "stopped" << dendl;
}
void ShardedThreadPool::pause()
{
std::unique_lock ul(shardedpool_lock);
ldout(cct,10) << "pause" << dendl;
pause_threads = true;
ceph_assert(wq != NULL);
wq->return_waiting_threads();
while (num_threads != num_paused){
wait_cond.wait(ul);
}
ldout(cct,10) << "paused" << dendl;
}
void ShardedThreadPool::pause_new()
{
ldout(cct,10) << "pause_new" << dendl;
shardedpool_lock.lock();
pause_threads = true;
ceph_assert(wq != NULL);
wq->return_waiting_threads();
shardedpool_lock.unlock();
ldout(cct,10) << "paused_new" << dendl;
}
void ShardedThreadPool::unpause()
{
ldout(cct,10) << "unpause" << dendl;
shardedpool_lock.lock();
pause_threads = false;
wq->stop_return_waiting_threads();
shardedpool_cond.notify_all();
shardedpool_lock.unlock();
ldout(cct,10) << "unpaused" << dendl;
}
void ShardedThreadPool::drain()
{
std::unique_lock ul(shardedpool_lock);
ldout(cct,10) << "drain" << dendl;
drain_threads = true;
ceph_assert(wq != NULL);
wq->return_waiting_threads();
while (num_threads != num_drained) {
wait_cond.wait(ul);
}
drain_threads = false;
wq->stop_return_waiting_threads();
shardedpool_cond.notify_all();
ldout(cct,10) << "drained" << dendl;
}
| 10,365 | 24.160194 | 126 | cc |
null | ceph-main/src/common/WorkQueue.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_WORKQUEUE_H
#define CEPH_WORKQUEUE_H
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
// for ObjectStore.h
struct ThreadPool {
struct TPHandle {
};
};
#else
#include <atomic>
#include <list>
#include <set>
#include <string>
#include <vector>
#include "common/ceph_mutex.h"
#include "include/unordered_map.h"
#include "common/config_obs.h"
#include "common/HeartbeatMap.h"
#include "common/Thread.h"
#include "include/common_fwd.h"
#include "include/Context.h"
#include "common/HBHandle.h"
/// Pool of threads that share work submitted to multiple work queues.
class ThreadPool : public md_config_obs_t {
protected:
CephContext *cct;
std::string name;
std::string thread_name;
std::string lockname;
ceph::mutex _lock;
ceph::condition_variable _cond;
bool _stop;
int _pause;
int _draining;
ceph::condition_variable _wait_cond;
public:
class TPHandle : public HBHandle {
friend class ThreadPool;
CephContext *cct;
ceph::heartbeat_handle_d *hb;
ceph::timespan grace;
ceph::timespan suicide_grace;
public:
TPHandle(
CephContext *cct,
ceph::heartbeat_handle_d *hb,
ceph::timespan grace,
ceph::timespan suicide_grace)
: cct(cct), hb(hb), grace(grace), suicide_grace(suicide_grace) {}
void reset_tp_timeout() override final;
void suspend_tp_timeout() override final;
};
protected:
/// Basic interface to a work queue used by the worker threads.
struct WorkQueue_ {
std::string name;
std::atomic<ceph::timespan> timeout_interval = ceph::timespan::zero();
std::atomic<ceph::timespan> suicide_interval = ceph::timespan::zero();
WorkQueue_(std::string n, ceph::timespan ti, ceph::timespan sti)
: name(std::move(n)), timeout_interval(ti), suicide_interval(sti)
{ }
virtual ~WorkQueue_() {}
/// Remove all work items from the queue.
virtual void _clear() = 0;
/// Check whether there is anything to do.
virtual bool _empty() = 0;
/// Get the next work item to process.
virtual void *_void_dequeue() = 0;
/** @brief Process the work item.
* This function will be called several times in parallel
* and must therefore be thread-safe. */
virtual void _void_process(void *item, TPHandle &handle) = 0;
/** @brief Synchronously finish processing a work item.
* This function is called after _void_process with the global thread pool lock held,
* so at most one copy will execute simultaneously for a given thread pool.
* It can be used for non-thread-safe finalization. */
virtual void _void_process_finish(void *) = 0;
void set_timeout(time_t ti){
timeout_interval.store(ceph::make_timespan(ti));
}
void set_suicide_timeout(time_t sti){
suicide_interval.store(ceph::make_timespan(sti));
}
};
// track thread pool size changes
unsigned _num_threads;
std::string _thread_num_option;
const char **_conf_keys;
const char **get_tracked_conf_keys() const override {
return _conf_keys;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override;
public:
/** @brief Templated by-value work queue.
* Skeleton implementation of a queue that processes items submitted by value.
* This is useful if the items are single primitive values or very small objects
* (a few bytes). The queue will automatically add itself to the thread pool on
* construction and remove itself on destruction. */
template<typename T, typename U = T>
class WorkQueueVal : public WorkQueue_ {
ceph::mutex _lock = ceph::make_mutex("WorkQueueVal::_lock");
ThreadPool *pool;
std::list<U> to_process;
std::list<U> to_finish;
virtual void _enqueue(T) = 0;
virtual void _enqueue_front(T) = 0;
bool _empty() override = 0;
virtual U _dequeue() = 0;
virtual void _process_finish(U) {}
void *_void_dequeue() override {
{
std::lock_guard l(_lock);
if (_empty())
return 0;
U u = _dequeue();
to_process.push_back(u);
}
return ((void*)1); // Not used
}
void _void_process(void *, TPHandle &handle) override {
_lock.lock();
ceph_assert(!to_process.empty());
U u = to_process.front();
to_process.pop_front();
_lock.unlock();
_process(u, handle);
_lock.lock();
to_finish.push_back(u);
_lock.unlock();
}
void _void_process_finish(void *) override {
_lock.lock();
ceph_assert(!to_finish.empty());
U u = to_finish.front();
to_finish.pop_front();
_lock.unlock();
_process_finish(u);
}
void _clear() override {}
public:
WorkQueueVal(std::string n,
ceph::timespan ti,
ceph::timespan sti,
ThreadPool *p)
: WorkQueue_(std::move(n), ti, sti), pool(p) {
pool->add_work_queue(this);
}
~WorkQueueVal() override {
pool->remove_work_queue(this);
}
void queue(T item) {
std::lock_guard l(pool->_lock);
_enqueue(item);
pool->_cond.notify_one();
}
void queue_front(T item) {
std::lock_guard l(pool->_lock);
_enqueue_front(item);
pool->_cond.notify_one();
}
void drain() {
pool->drain(this);
}
protected:
void lock() {
pool->lock();
}
void unlock() {
pool->unlock();
}
virtual void _process(U u, TPHandle &) = 0;
};
/** @brief Template by-pointer work queue.
* Skeleton implementation of a queue that processes items of a given type submitted as pointers.
* This is useful when the work item are large or include dynamically allocated memory. The queue
* will automatically add itself to the thread pool on construction and remove itself on
* destruction. */
template<class T>
class WorkQueue : public WorkQueue_ {
ThreadPool *pool;
/// Add a work item to the queue.
virtual bool _enqueue(T *) = 0;
/// Dequeue a previously submitted work item.
virtual void _dequeue(T *) = 0;
/// Dequeue a work item and return the original submitted pointer.
virtual T *_dequeue() = 0;
virtual void _process_finish(T *) {}
// implementation of virtual methods from WorkQueue_
void *_void_dequeue() override {
return (void *)_dequeue();
}
void _void_process(void *p, TPHandle &handle) override {
_process(static_cast<T *>(p), handle);
}
void _void_process_finish(void *p) override {
_process_finish(static_cast<T *>(p));
}
protected:
/// Process a work item. Called from the worker threads.
virtual void _process(T *t, TPHandle &) = 0;
public:
WorkQueue(std::string n,
ceph::timespan ti, ceph::timespan sti,
ThreadPool* p)
: WorkQueue_(std::move(n), ti, sti), pool(p) {
pool->add_work_queue(this);
}
~WorkQueue() override {
pool->remove_work_queue(this);
}
bool queue(T *item) {
pool->_lock.lock();
bool r = _enqueue(item);
pool->_cond.notify_one();
pool->_lock.unlock();
return r;
}
void dequeue(T *item) {
pool->_lock.lock();
_dequeue(item);
pool->_lock.unlock();
}
void clear() {
pool->_lock.lock();
_clear();
pool->_lock.unlock();
}
void lock() {
pool->lock();
}
void unlock() {
pool->unlock();
}
/// wake up the thread pool (without lock held)
void wake() {
pool->wake();
}
/// wake up the thread pool (with lock already held)
void _wake() {
pool->_wake();
}
void _wait() {
pool->_wait();
}
void drain() {
pool->drain(this);
}
};
template<typename T>
class PointerWQ : public WorkQueue_ {
public:
~PointerWQ() override {
m_pool->remove_work_queue(this);
ceph_assert(m_processing == 0);
}
void drain() {
{
// if this queue is empty and not processing, don't wait for other
// queues to finish processing
std::lock_guard l(m_pool->_lock);
if (m_processing == 0 && m_items.empty()) {
return;
}
}
m_pool->drain(this);
}
void queue(T *item) {
std::lock_guard l(m_pool->_lock);
m_items.push_back(item);
m_pool->_cond.notify_one();
}
bool empty() {
std::lock_guard l(m_pool->_lock);
return _empty();
}
protected:
PointerWQ(std::string n,
ceph::timespan ti, ceph::timespan sti,
ThreadPool* p)
: WorkQueue_(std::move(n), ti, sti), m_pool(p), m_processing(0) {
}
void register_work_queue() {
m_pool->add_work_queue(this);
}
void _clear() override {
ceph_assert(ceph_mutex_is_locked(m_pool->_lock));
m_items.clear();
}
bool _empty() override {
ceph_assert(ceph_mutex_is_locked(m_pool->_lock));
return m_items.empty();
}
void *_void_dequeue() override {
ceph_assert(ceph_mutex_is_locked(m_pool->_lock));
if (m_items.empty()) {
return NULL;
}
++m_processing;
T *item = m_items.front();
m_items.pop_front();
return item;
}
void _void_process(void *item, ThreadPool::TPHandle &handle) override {
process(reinterpret_cast<T *>(item));
}
void _void_process_finish(void *item) override {
ceph_assert(ceph_mutex_is_locked(m_pool->_lock));
ceph_assert(m_processing > 0);
--m_processing;
}
virtual void process(T *item) = 0;
void process_finish() {
std::lock_guard locker(m_pool->_lock);
_void_process_finish(nullptr);
}
T *front() {
ceph_assert(ceph_mutex_is_locked(m_pool->_lock));
if (m_items.empty()) {
return NULL;
}
return m_items.front();
}
void requeue_front(T *item) {
std::lock_guard pool_locker(m_pool->_lock);
_void_process_finish(nullptr);
m_items.push_front(item);
}
void requeue_back(T *item) {
std::lock_guard pool_locker(m_pool->_lock);
_void_process_finish(nullptr);
m_items.push_back(item);
}
void signal() {
std::lock_guard pool_locker(m_pool->_lock);
m_pool->_cond.notify_one();
}
ceph::mutex &get_pool_lock() {
return m_pool->_lock;
}
private:
ThreadPool *m_pool;
std::list<T *> m_items;
uint32_t m_processing;
};
protected:
std::vector<WorkQueue_*> work_queues;
int next_work_queue = 0;
// threads
struct WorkThread : public Thread {
ThreadPool *pool;
// cppcheck-suppress noExplicitConstructor
WorkThread(ThreadPool *p) : pool(p) {}
void *entry() override {
pool->worker(this);
return 0;
}
};
std::set<WorkThread*> _threads;
std::list<WorkThread*> _old_threads; ///< need to be joined
int processing;
void start_threads();
void join_old_threads();
virtual void worker(WorkThread *wt);
public:
ThreadPool(CephContext *cct_, std::string nm, std::string tn, int n, const char *option = NULL);
~ThreadPool() override;
/// return number of threads currently running
int get_num_threads() {
std::lock_guard l(_lock);
return _num_threads;
}
/// assign a work queue to this thread pool
void add_work_queue(WorkQueue_* wq) {
std::lock_guard l(_lock);
work_queues.push_back(wq);
}
/// remove a work queue from this thread pool
void remove_work_queue(WorkQueue_* wq) {
std::lock_guard l(_lock);
unsigned i = 0;
while (work_queues[i] != wq)
i++;
for (i++; i < work_queues.size(); i++)
work_queues[i-1] = work_queues[i];
ceph_assert(i == work_queues.size());
work_queues.resize(i-1);
}
/// take thread pool lock
void lock() {
_lock.lock();
}
/// release thread pool lock
void unlock() {
_lock.unlock();
}
/// wait for a kick on this thread pool
void wait(ceph::condition_variable &c) {
std::unique_lock l(_lock, std::adopt_lock);
c.wait(l);
}
/// wake up a waiter (with lock already held)
void _wake() {
_cond.notify_all();
}
/// wake up a waiter (without lock held)
void wake() {
std::lock_guard l(_lock);
_cond.notify_all();
}
void _wait() {
std::unique_lock l(_lock, std::adopt_lock);
_cond.wait(l);
}
/// start thread pool thread
void start();
/// stop thread pool thread
void stop(bool clear_after=true);
/// pause thread pool (if it not already paused)
void pause();
/// pause initiation of new work
void pause_new();
/// resume work in thread pool. must match each pause() call 1:1 to resume.
void unpause();
/** @brief Wait until work completes.
* If the parameter is NULL, blocks until all threads are idle.
* If it is not NULL, blocks until the given work queue does not have
* any items left to process. */
void drain(WorkQueue_* wq = 0);
};
class GenContextWQ :
public ThreadPool::WorkQueueVal<GenContext<ThreadPool::TPHandle&>*> {
std::list<GenContext<ThreadPool::TPHandle&>*> _queue;
public:
GenContextWQ(const std::string &name, ceph::timespan ti, ThreadPool *tp)
: ThreadPool::WorkQueueVal<
GenContext<ThreadPool::TPHandle&>*>(name, ti, ti*10, tp) {}
void _enqueue(GenContext<ThreadPool::TPHandle&> *c) override {
_queue.push_back(c);
}
void _enqueue_front(GenContext<ThreadPool::TPHandle&> *c) override {
_queue.push_front(c);
}
bool _empty() override {
return _queue.empty();
}
GenContext<ThreadPool::TPHandle&> *_dequeue() override {
ceph_assert(!_queue.empty());
GenContext<ThreadPool::TPHandle&> *c = _queue.front();
_queue.pop_front();
return c;
}
void _process(GenContext<ThreadPool::TPHandle&> *c,
ThreadPool::TPHandle &tp) override {
c->complete(tp);
}
};
class C_QueueInWQ : public Context {
GenContextWQ *wq;
GenContext<ThreadPool::TPHandle&> *c;
public:
C_QueueInWQ(GenContextWQ *wq, GenContext<ThreadPool::TPHandle &> *c)
: wq(wq), c(c) {}
void finish(int) override {
wq->queue(c);
}
};
/// Work queue that asynchronously completes contexts (executes callbacks).
/// @see Finisher
class ContextWQ : public ThreadPool::PointerWQ<Context> {
public:
ContextWQ(const std::string &name, ceph::timespan ti, ThreadPool *tp)
: ThreadPool::PointerWQ<Context>(name, ti, ceph::timespan::zero(), tp) {
this->register_work_queue();
}
void queue(Context *ctx, int result = 0) {
if (result != 0) {
std::lock_guard locker(m_lock);
m_context_results[ctx] = result;
}
ThreadPool::PointerWQ<Context>::queue(ctx);
}
protected:
void _clear() override {
ThreadPool::PointerWQ<Context>::_clear();
std::lock_guard locker(m_lock);
m_context_results.clear();
}
void process(Context *ctx) override {
int result = 0;
{
std::lock_guard locker(m_lock);
ceph::unordered_map<Context *, int>::iterator it =
m_context_results.find(ctx);
if (it != m_context_results.end()) {
result = it->second;
m_context_results.erase(it);
}
}
ctx->complete(result);
}
private:
ceph::mutex m_lock = ceph::make_mutex("ContextWQ::m_lock");
ceph::unordered_map<Context*, int> m_context_results;
};
class ShardedThreadPool {
CephContext *cct;
std::string name;
std::string thread_name;
std::string lockname;
ceph::mutex shardedpool_lock;
ceph::condition_variable shardedpool_cond;
ceph::condition_variable wait_cond;
uint32_t num_threads;
std::atomic<bool> stop_threads = { false };
std::atomic<bool> pause_threads = { false };
std::atomic<bool> drain_threads = { false };
uint32_t num_paused;
uint32_t num_drained;
public:
class BaseShardedWQ {
public:
std::atomic<ceph::timespan> timeout_interval = ceph::timespan::zero();
std::atomic<ceph::timespan> suicide_interval = ceph::timespan::zero();
BaseShardedWQ(ceph::timespan ti, ceph::timespan sti)
:timeout_interval(ti), suicide_interval(sti) {}
virtual ~BaseShardedWQ() {}
virtual void _process(uint32_t thread_index, ceph::heartbeat_handle_d *hb ) = 0;
virtual void return_waiting_threads() = 0;
virtual void stop_return_waiting_threads() = 0;
virtual bool is_shard_empty(uint32_t thread_index) = 0;
void set_timeout(time_t ti) {
timeout_interval.store(ceph::make_timespan(ti));
}
void set_suicide_timeout(time_t sti) {
suicide_interval.store(ceph::make_timespan(sti));
}
};
template <typename T>
class ShardedWQ: public BaseShardedWQ {
ShardedThreadPool* sharded_pool;
protected:
virtual void _enqueue(T&&) = 0;
virtual void _enqueue_front(T&&) = 0;
public:
ShardedWQ(ceph::timespan ti,
ceph::timespan sti, ShardedThreadPool* tp)
: BaseShardedWQ(ti, sti), sharded_pool(tp) {
tp->set_wq(this);
}
~ShardedWQ() override {}
void queue(T&& item) {
_enqueue(std::move(item));
}
void queue_front(T&& item) {
_enqueue_front(std::move(item));
}
void drain() {
sharded_pool->drain();
}
};
private:
BaseShardedWQ* wq;
// threads
struct WorkThreadSharded : public Thread {
ShardedThreadPool *pool;
uint32_t thread_index;
WorkThreadSharded(ShardedThreadPool *p, uint32_t pthread_index): pool(p),
thread_index(pthread_index) {}
void *entry() override {
pool->shardedthreadpool_worker(thread_index);
return 0;
}
};
std::vector<WorkThreadSharded*> threads_shardedpool;
void start_threads();
void shardedthreadpool_worker(uint32_t thread_index);
void set_wq(BaseShardedWQ* swq) {
wq = swq;
}
public:
ShardedThreadPool(CephContext *cct_, std::string nm, std::string tn, uint32_t pnum_threads);
~ShardedThreadPool(){};
/// start thread pool thread
void start();
/// stop thread pool thread
void stop();
/// pause thread pool (if it not already paused)
void pause();
/// pause initiation of new work
void pause_new();
/// resume work in thread pool. must match each pause() call 1:1 to resume.
void unpause();
/// wait for all work to complete
void drain();
};
#endif
#endif
| 18,509 | 25.90407 | 99 | h |
null | ceph-main/src/common/admin_socket.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 <poll.h>
#include <sys/un.h>
#include "common/admin_socket.h"
#include "common/admin_socket_client.h"
#include "common/dout.h"
#include "common/errno.h"
#include "common/safe_io.h"
#include "common/Thread.h"
#include "common/version.h"
#include "common/ceph_mutex.h"
#ifndef WITH_SEASTAR
#include "common/Cond.h"
#endif
#include "messages/MCommand.h"
#include "messages/MCommandReply.h"
#include "messages/MMonCommand.h"
#include "messages/MMonCommandAck.h"
// re-include our assert to clobber the system one; fix dout:
#include "include/ceph_assert.h"
#include "include/compat.h"
#include "include/sock_compat.h"
#define dout_subsys ceph_subsys_asok
#undef dout_prefix
#define dout_prefix *_dout << "asok(" << (void*)m_cct << ") "
using namespace std::literals;
using std::ostringstream;
using std::string;
using std::stringstream;
using namespace TOPNSPC::common;
using ceph::bufferlist;
using ceph::cref_t;
using ceph::Formatter;
/*
* UNIX domain sockets created by an application persist even after that
* application closes, unless they're explicitly unlinked. This is because the
* directory containing the socket keeps a reference to the socket.
*
* This code makes things a little nicer by unlinking those dead sockets when
* the application exits normally.
*/
template<typename F, typename... Args>
inline int retry_sys_call(F f, Args... args) {
int r;
do {
r = f(args...);
} while (r < 0 && errno == EINTR);
return r;
};
static std::mutex cleanup_lock;
static std::vector<std::string> cleanup_files;
static bool cleanup_atexit = false;
static void remove_cleanup_file(std::string_view file) {
std::unique_lock l(cleanup_lock);
if (auto i = std::find(cleanup_files.cbegin(), cleanup_files.cend(), file);
i != cleanup_files.cend()) {
retry_sys_call(::unlink, i->c_str());
cleanup_files.erase(i);
}
}
void remove_all_cleanup_files() {
std::unique_lock l(cleanup_lock);
for (const auto& s : cleanup_files) {
retry_sys_call(::unlink, s.c_str());
}
cleanup_files.clear();
}
static void add_cleanup_file(std::string file) {
std::unique_lock l(cleanup_lock);
cleanup_files.push_back(std::move(file));
if (!cleanup_atexit) {
atexit(remove_all_cleanup_files);
cleanup_atexit = true;
}
}
AdminSocket::AdminSocket(CephContext *cct)
: m_cct(cct)
{}
AdminSocket::~AdminSocket()
{
shutdown();
}
/*
* This thread listens on the UNIX domain socket for incoming connections.
* It only handles one connection at a time at the moment. All I/O is nonblocking,
* so that we can implement sensible timeouts. [TODO: make all I/O nonblocking]
*
* This thread also listens to m_wakeup_rd_fd. If there is any data sent to this
* pipe, the thread wakes up. If m_shutdown is set, the thread terminates
* itself gracefully, allowing the AdminSocketConfigObs class to join() it.
*/
std::string AdminSocket::create_wakeup_pipe(int *pipe_rd, int *pipe_wr)
{
int pipefd[2];
#ifdef _WIN32
if (win_socketpair(pipefd) < 0) {
#else
if (pipe_cloexec(pipefd, O_NONBLOCK) < 0) {
#endif
int e = ceph_sock_errno();
ostringstream oss;
oss << "AdminSocket::create_wakeup_pipe error: " << cpp_strerror(e);
return oss.str();
}
*pipe_rd = pipefd[0];
*pipe_wr = pipefd[1];
return "";
}
std::string AdminSocket::destroy_wakeup_pipe()
{
// Send a byte to the wakeup pipe that the thread is listening to
char buf[1] = { 0x0 };
int ret = safe_send(m_wakeup_wr_fd, buf, sizeof(buf));
// Close write end
retry_sys_call(::compat_closesocket, m_wakeup_wr_fd);
m_wakeup_wr_fd = -1;
if (ret != 0) {
ostringstream oss;
oss << "AdminSocket::destroy_shutdown_pipe error: failed to write"
"to thread shutdown pipe: error " << ret;
return oss.str();
}
th.join();
// Close read end. Doing this before join() blocks the listenter and prevents
// joining.
retry_sys_call(::compat_closesocket, m_wakeup_rd_fd);
m_wakeup_rd_fd = -1;
return "";
}
std::string AdminSocket::bind_and_listen(const std::string &sock_path, int *fd)
{
ldout(m_cct, 5) << "bind_and_listen " << sock_path << dendl;
struct sockaddr_un address;
if (sock_path.size() > sizeof(address.sun_path) - 1) {
ostringstream oss;
oss << "AdminSocket::bind_and_listen: "
<< "The UNIX domain socket path " << sock_path << " is too long! The "
<< "maximum length on this system is "
<< (sizeof(address.sun_path) - 1);
return oss.str();
}
int sock_fd = socket_cloexec(PF_UNIX, SOCK_STREAM, 0);
if (sock_fd < 0) {
int err = ceph_sock_errno();
ostringstream oss;
oss << "AdminSocket::bind_and_listen: "
<< "failed to create socket: " << cpp_strerror(err);
return oss.str();
}
// FIPS zeroization audit 20191115: this memset is fine.
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path),
"%s", sock_path.c_str());
if (::bind(sock_fd, (struct sockaddr*)&address,
sizeof(struct sockaddr_un)) != 0) {
int err = ceph_sock_errno();
if (err == EADDRINUSE) {
AdminSocketClient client(sock_path);
bool ok;
client.ping(&ok);
if (ok) {
ldout(m_cct, 20) << "socket " << sock_path << " is in use" << dendl;
err = EEXIST;
} else {
ldout(m_cct, 20) << "unlink stale file " << sock_path << dendl;
retry_sys_call(::unlink, sock_path.c_str());
if (::bind(sock_fd, (struct sockaddr*)&address,
sizeof(struct sockaddr_un)) == 0) {
err = 0;
} else {
err = ceph_sock_errno();
}
}
}
if (err != 0) {
ostringstream oss;
oss << "AdminSocket::bind_and_listen: "
<< "failed to bind the UNIX domain socket to '" << sock_path
<< "': " << cpp_strerror(err);
close(sock_fd);
return oss.str();
}
}
if (listen(sock_fd, 5) != 0) {
int err = ceph_sock_errno();
ostringstream oss;
oss << "AdminSocket::bind_and_listen: "
<< "failed to listen to socket: " << cpp_strerror(err);
close(sock_fd);
retry_sys_call(::unlink, sock_path.c_str());
return oss.str();
}
*fd = sock_fd;
return "";
}
void AdminSocket::entry() noexcept
{
ldout(m_cct, 5) << "entry start" << dendl;
while (true) {
struct pollfd fds[2];
// FIPS zeroization audit 20191115: this memset is fine.
memset(fds, 0, sizeof(fds));
fds[0].fd = m_sock_fd;
fds[0].events = POLLIN | POLLRDBAND;
fds[1].fd = m_wakeup_rd_fd;
fds[1].events = POLLIN | POLLRDBAND;
ldout(m_cct,20) << __func__ << " waiting" << dendl;
int ret = poll(fds, 2, -1);
if (ret < 0) {
int err = ceph_sock_errno();
if (err == EINTR) {
continue;
}
lderr(m_cct) << "AdminSocket: poll(2) error: '"
<< cpp_strerror(err) << dendl;
return;
}
ldout(m_cct,20) << __func__ << " awake" << dendl;
if (fds[0].revents & POLLIN) {
// Send out some data
do_accept();
}
if (fds[1].revents & POLLIN) {
// read off one byte
char buf;
auto s = safe_recv(m_wakeup_rd_fd, &buf, 1);
if (s == -1) {
int e = ceph_sock_errno();
ldout(m_cct, 5) << "AdminSocket: (ignoring) read(2) error: '"
<< cpp_strerror(e) << dendl;
}
do_tell_queue();
}
if (m_shutdown) {
// Parent wants us to shut down
return;
}
}
ldout(m_cct, 5) << "entry exit" << dendl;
}
void AdminSocket::chown(uid_t uid, gid_t gid)
{
if (m_sock_fd >= 0) {
int r = ::chown(m_path.c_str(), uid, gid);
if (r < 0) {
r = -errno;
lderr(m_cct) << "AdminSocket: failed to chown socket: "
<< cpp_strerror(r) << dendl;
}
}
}
void AdminSocket::chmod(mode_t mode)
{
if (m_sock_fd >= 0) {
int r = ::chmod(m_path.c_str(), mode);
if (r < 0) {
r = -errno;
lderr(m_cct) << "AdminSocket: failed to chmod socket: "
<< cpp_strerror(r) << dendl;
}
}
}
void AdminSocket::do_accept()
{
struct sockaddr_un address;
socklen_t address_length = sizeof(address);
ldout(m_cct, 30) << "AdminSocket: calling accept" << dendl;
int connection_fd = accept_cloexec(m_sock_fd, (struct sockaddr*) &address,
&address_length);
if (connection_fd < 0) {
int err = ceph_sock_errno();
lderr(m_cct) << "AdminSocket: do_accept error: '"
<< cpp_strerror(err) << dendl;
return;
}
ldout(m_cct, 30) << "AdminSocket: finished accept" << dendl;
char cmd[1024];
unsigned pos = 0;
string c;
while (1) {
int ret = safe_recv(connection_fd, &cmd[pos], 1);
if (ret <= 0) {
if (ret < 0) {
lderr(m_cct) << "AdminSocket: error reading request code: "
<< cpp_strerror(ret) << dendl;
}
retry_sys_call(::compat_closesocket, connection_fd);
return;
}
if (cmd[0] == '\0') {
// old protocol: __be32
if (pos == 3 && cmd[0] == '\0') {
switch (cmd[3]) {
case 0:
c = "0";
break;
case 1:
c = "perfcounters_dump";
break;
case 2:
c = "perfcounters_schema";
break;
default:
c = "foo";
break;
}
//wrap command with new protocol
c = "{\"prefix\": \"" + c + "\"}";
break;
}
} else {
// new protocol: null or \n terminated string
if (cmd[pos] == '\n' || cmd[pos] == '\0') {
cmd[pos] = '\0';
c = cmd;
break;
}
}
if (++pos >= sizeof(cmd)) {
lderr(m_cct) << "AdminSocket: error reading request too long" << dendl;
retry_sys_call(::compat_closesocket, connection_fd);
return;
}
}
std::vector<std::string> cmdvec = { c };
bufferlist empty, out;
ostringstream err;
int rval = execute_command(cmdvec, empty /* inbl */, err, &out);
// Unfortunately, the asok wire protocol does not let us pass an error code,
// and many asok command implementations return helpful error strings. So,
// let's prepend an error string to the output if there is an error code.
if (rval < 0) {
ostringstream ss;
ss << "ERROR: " << cpp_strerror(rval) << "\n";
ss << err.str() << "\n";
bufferlist o;
o.append(ss.str());
o.claim_append(out);
out.claim_append(o);
}
uint32_t len = htonl(out.length());
int ret = safe_send(connection_fd, &len, sizeof(len));
if (ret < 0) {
lderr(m_cct) << "AdminSocket: error writing response length "
<< cpp_strerror(ret) << dendl;
} else {
int r = out.send_fd(connection_fd);
if (r < 0) {
lderr(m_cct) << "AdminSocket: error writing response payload "
<< cpp_strerror(ret) << dendl;
}
}
retry_sys_call(::compat_closesocket, connection_fd);
}
void AdminSocket::do_tell_queue()
{
ldout(m_cct,10) << __func__ << dendl;
std::list<cref_t<MCommand>> q;
std::list<cref_t<MMonCommand>> lq;
{
std::lock_guard l(tell_lock);
q.swap(tell_queue);
lq.swap(tell_legacy_queue);
}
for (auto& m : q) {
bufferlist outbl;
execute_command(
m->cmd,
m->get_data(),
[m](int r, const std::string& err, bufferlist& outbl) {
auto reply = new MCommandReply(r, err);
reply->set_tid(m->get_tid());
reply->set_data(outbl);
#ifdef WITH_SEASTAR
// TODO: crimson: handle asok commmand from alien thread
#else
m->get_connection()->send_message(reply);
#endif
});
}
for (auto& m : lq) {
bufferlist outbl;
execute_command(
m->cmd,
m->get_data(),
[m](int r, const std::string& err, bufferlist& outbl) {
auto reply = new MMonCommandAck(m->cmd, r, err, 0);
reply->set_tid(m->get_tid());
reply->set_data(outbl);
#ifdef WITH_SEASTAR
// TODO: crimson: handle asok commmand from alien thread
#else
m->get_connection()->send_message(reply);
#endif
});
}
}
int AdminSocket::execute_command(
const std::vector<std::string>& cmd,
const bufferlist& inbl,
std::ostream& errss,
bufferlist *outbl)
{
#ifdef WITH_SEASTAR
// TODO: crimson: blocking execute_command() in alien thread
return -ENOSYS;
#else
bool done = false;
int rval = 0;
ceph::mutex mylock = ceph::make_mutex("admin_socket::excute_command::mylock");
ceph::condition_variable mycond;
C_SafeCond fin(mylock, mycond, &done, &rval);
execute_command(
cmd,
inbl,
[&errss, outbl, &fin](int r, const std::string& err, bufferlist& out) {
errss << err;
*outbl = std::move(out);
fin.finish(r);
});
{
std::unique_lock l{mylock};
mycond.wait(l, [&done] { return done;});
}
return rval;
#endif
}
void AdminSocket::execute_command(
const std::vector<std::string>& cmdvec,
const bufferlist& inbl,
std::function<void(int,const std::string&,bufferlist&)> on_finish)
{
cmdmap_t cmdmap;
string format;
stringstream errss;
bufferlist empty;
ldout(m_cct,10) << __func__ << " cmdvec='" << cmdvec << "'" << dendl;
if (!cmdmap_from_json(cmdvec, &cmdmap, errss)) {
ldout(m_cct, 0) << "AdminSocket: " << errss.str() << dendl;
return on_finish(-EINVAL, "invalid json", empty);
}
string prefix;
try {
cmd_getval(cmdmap, "format", format);
cmd_getval(cmdmap, "prefix", prefix);
} catch (const bad_cmd_get& e) {
return on_finish(-EINVAL, "invalid json, missing format and/or prefix",
empty);
}
auto f = Formatter::create(format, "json-pretty", "json-pretty");
auto [retval, hook] = find_matched_hook(prefix, cmdmap);
switch (retval) {
case ENOENT:
lderr(m_cct) << "AdminSocket: request '" << cmdvec
<< "' not defined" << dendl;
delete f;
return on_finish(-EINVAL, "unknown command prefix "s + prefix, empty);
case EINVAL:
delete f;
return on_finish(-EINVAL, "invalid command json", empty);
default:
assert(retval == 0);
}
hook->call_async(
prefix, cmdmap, f, inbl,
[f, on_finish](int r, const std::string& err, bufferlist& out) {
// handle either existing output in bufferlist *or* via formatter
if (r >= 0 && out.length() == 0) {
f->flush(out);
}
delete f;
on_finish(r, err, out);
});
std::unique_lock l(lock);
in_hook = false;
in_hook_cond.notify_all();
}
std::pair<int, AdminSocketHook*>
AdminSocket::find_matched_hook(std::string& prefix,
const cmdmap_t& cmdmap)
{
std::unique_lock l(lock);
// Drop lock after done with the lookup to avoid cycles in cases where the
// hook takes the same lock that was held during calls to
// register/unregister, and set in_hook to allow unregister to wait for us
// before removing this hook.
auto [hooks_begin, hooks_end] = hooks.equal_range(prefix);
if (hooks_begin == hooks_end) {
return {ENOENT, nullptr};
}
// make sure one of the registered commands with this prefix validates.
stringstream errss;
for (auto hook = hooks_begin; hook != hooks_end; ++hook) {
if (validate_cmd(hook->second.desc, cmdmap, errss)) {
in_hook = true;
return {0, hook->second.hook};
}
}
return {EINVAL, nullptr};
}
void AdminSocket::queue_tell_command(cref_t<MCommand> m)
{
ldout(m_cct,10) << __func__ << " " << *m << dendl;
std::lock_guard l(tell_lock);
tell_queue.push_back(std::move(m));
wakeup();
}
void AdminSocket::queue_tell_command(cref_t<MMonCommand> m)
{
ldout(m_cct,10) << __func__ << " " << *m << dendl;
std::lock_guard l(tell_lock);
tell_legacy_queue.push_back(std::move(m));
wakeup();
}
int AdminSocket::register_command(std::string_view cmddesc,
AdminSocketHook *hook,
std::string_view help)
{
int ret;
std::unique_lock l(lock);
string prefix = cmddesc_get_prefix(cmddesc);
auto i = hooks.find(prefix);
if (i != hooks.cend() &&
i->second.desc == cmddesc) {
ldout(m_cct, 5) << "register_command " << prefix
<< " cmddesc " << cmddesc << " hook " << hook
<< " EEXIST" << dendl;
ret = -EEXIST;
} else {
ldout(m_cct, 5) << "register_command " << prefix << " hook " << hook
<< dendl;
hooks.emplace_hint(i,
std::piecewise_construct,
std::forward_as_tuple(prefix),
std::forward_as_tuple(hook, cmddesc, help));
ret = 0;
}
return ret;
}
void AdminSocket::unregister_commands(const AdminSocketHook *hook)
{
std::unique_lock l(lock);
auto i = hooks.begin();
while (i != hooks.end()) {
if (i->second.hook == hook) {
ldout(m_cct, 5) << __func__ << " " << i->first << dendl;
// If we are currently processing a command, wait for it to
// complete in case it referenced the hook that we are
// unregistering.
in_hook_cond.wait(l, [this]() { return !in_hook; });
hooks.erase(i++);
} else {
i++;
}
}
}
class VersionHook : public AdminSocketHook {
public:
int call(std::string_view command, const cmdmap_t& cmdmap,
const bufferlist&,
Formatter *f,
std::ostream& errss,
bufferlist& out) override {
if (command == "0"sv) {
out.append(CEPH_ADMIN_SOCK_VERSION);
} else {
f->open_object_section("version");
if (command == "version") {
f->dump_string("version", ceph_version_to_str());
f->dump_string("release", ceph_release_to_str());
f->dump_string("release_type", ceph_release_type());
} else if (command == "git_version") {
f->dump_string("git_version", git_version_to_str());
}
ostringstream ss;
f->close_section();
}
return 0;
}
};
class HelpHook : public AdminSocketHook {
AdminSocket *m_as;
public:
explicit HelpHook(AdminSocket *as) : m_as(as) {}
int call(std::string_view command, const cmdmap_t& cmdmap,
const bufferlist&,
Formatter *f,
std::ostream& errss,
bufferlist& out) override {
f->open_object_section("help");
for (const auto& [command, info] : m_as->hooks) {
if (info.help.length())
f->dump_string(command.c_str(), info.help);
}
f->close_section();
return 0;
}
};
class GetdescsHook : public AdminSocketHook {
AdminSocket *m_as;
public:
explicit GetdescsHook(AdminSocket *as) : m_as(as) {}
int call(std::string_view command, const cmdmap_t& cmdmap,
const bufferlist&,
Formatter *f,
std::ostream& errss,
bufferlist& out) override {
int cmdnum = 0;
f->open_object_section("command_descriptions");
for (const auto& [command, info] : m_as->hooks) {
// GCC 8 actually has [[maybe_unused]] on a structured binding
// do what you'd expect. GCC 7 does not.
(void)command;
ostringstream secname;
secname << "cmd" << std::setfill('0') << std::setw(3) << cmdnum;
dump_cmd_and_help_to_json(f,
CEPH_FEATURES_ALL,
secname.str().c_str(),
info.desc,
info.help);
cmdnum++;
}
f->close_section(); // command_descriptions
return 0;
}
};
bool AdminSocket::init(const std::string& path)
{
ldout(m_cct, 5) << "init " << path << dendl;
#ifdef _WIN32
OSVERSIONINFOEXW ver = {0};
ver.dwOSVersionInfoSize = sizeof(ver);
get_windows_version(&ver);
if (std::tie(ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber) <
std::make_tuple(10, 0, 17063)) {
ldout(m_cct, 5) << "Unix sockets require Windows 10.0.17063 or later. "
<< "The admin socket will not be available." << dendl;
return false;
}
#endif
/* Set up things for the new thread */
std::string err;
int pipe_rd = -1, pipe_wr = -1;
err = create_wakeup_pipe(&pipe_rd, &pipe_wr);
if (!err.empty()) {
lderr(m_cct) << "AdminSocketConfigObs::init: error: " << err << dendl;
return false;
}
int sock_fd;
err = bind_and_listen(path, &sock_fd);
if (!err.empty()) {
lderr(m_cct) << "AdminSocketConfigObs::init: failed: " << err << dendl;
close(pipe_rd);
close(pipe_wr);
return false;
}
/* Create new thread */
m_sock_fd = sock_fd;
m_wakeup_rd_fd = pipe_rd;
m_wakeup_wr_fd = pipe_wr;
m_path = path;
version_hook = std::make_unique<VersionHook>();
register_command("0", version_hook.get(), "");
register_command("version", version_hook.get(), "get ceph version");
register_command("git_version", version_hook.get(),
"get git sha1");
help_hook = std::make_unique<HelpHook>(this);
register_command("help", help_hook.get(),
"list available commands");
getdescs_hook = std::make_unique<GetdescsHook>(this);
register_command("get_command_descriptions",
getdescs_hook.get(), "list available commands");
th = make_named_thread("admin_socket", &AdminSocket::entry, this);
add_cleanup_file(m_path.c_str());
return true;
}
void AdminSocket::shutdown()
{
// Under normal operation this is unlikely to occur. However for some unit
// tests, some object members are not initialized and so cannot be deleted
// without fault.
if (m_wakeup_wr_fd < 0)
return;
ldout(m_cct, 5) << "shutdown" << dendl;
m_shutdown = true;
auto err = destroy_wakeup_pipe();
if (!err.empty()) {
lderr(m_cct) << "AdminSocket::shutdown: error: " << err << dendl;
}
retry_sys_call(::compat_closesocket, m_sock_fd);
unregister_commands(version_hook.get());
version_hook.reset();
unregister_commands(help_hook.get());
help_hook.reset();
unregister_commands(getdescs_hook.get());
getdescs_hook.reset();
remove_cleanup_file(m_path);
m_path.clear();
}
void AdminSocket::wakeup()
{
// Send a byte to the wakeup pipe that the thread is listening to
char buf[1] = { 0x0 };
int r = safe_send(m_wakeup_wr_fd, buf, sizeof(buf));
(void)r;
}
| 21,714 | 26.452592 | 82 | cc |
null | ceph-main/src/common/admin_socket.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_ADMIN_SOCKET_H
#define CEPH_COMMON_ADMIN_SOCKET_H
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
#include "crimson/admin/admin_socket.h"
#else
#include <condition_variable>
#include <mutex>
#include <string>
#include <string_view>
#include <thread>
#include "include/buffer.h"
#include "include/common_fwd.h"
#include "common/ref.h"
#include "common/cmdparse.h"
class MCommand;
class MMonCommand;
inline constexpr auto CEPH_ADMIN_SOCK_VERSION = std::string_view("2");
class AdminSocketHook {
public:
/**
* @brief
* Handler for admin socket commands, synchronous version
*
* Executes action associated with admin command and returns byte-stream output @c out.
* There is no restriction on output. Each handler defines output semantics.
* Typically output is textual representation of some ceph's internals.
* Handler should use provided formatter @c f if structuralized output is being produced.
*
* @param command[in] String matching constant part of cmddesc in @ref AdminSocket::register_command
* @param cmdmap[in] Parameters extracted from argument part of cmddesc in @ref AdminSocket::register_command
* @param f[in] Formatter created according to requestor preference, used by `ceph --format`
* @param errss[out] Error stream, should contain details in case of execution failure
* @param out[out] Produced output
*
* @retval 0 Success, errss is ignored and does not contribute to output
* @retval <0 Error code, errss is prepended to @c out
*
* @note If @c out is empty, then admin socket will try to flush @c f to out.
*/
virtual int call(
std::string_view command,
const cmdmap_t& cmdmap,
const ceph::buffer::list& inbl,
ceph::Formatter *f,
std::ostream& errss,
ceph::buffer::list& out) = 0;
/**
* @brief
* Handler for admin socket commands, asynchronous version
*
* Executes action associated with admin command and prepares byte-stream response.
* When processing is done @c on_finish must be called.
* There is no restriction on output. Each handler defines own output semantics.
* Typically output is textual representation of some ceph's internals.
* Input @c inbl can be passed, see ceph --in-file.
* Handler should use provided formatter @c f if structuralized output is being produced.
* on_finish handler has following parameters:
* - result code of handler (same as @ref AdminSocketHook::call)
* - error message, text
* - output
*
* @param[in] command String matching constant part of cmddesc in @ref AdminSocket::register_command
* @param[in] cmdmap Parameters extracted from argument part of cmddesc in @ref AdminSocket::register_command
* @param[in] f Formatter created according to requestor preference, used by `ceph --format`
* @param[in] inbl Input content for handler
* @param[in] on_finish Function to call when processing is done
*
* @note If @c out is empty, then admin socket will try to flush @c f to out.
*/
virtual void call_async(
std::string_view command,
const cmdmap_t& cmdmap,
ceph::Formatter *f,
const ceph::buffer::list& inbl,
std::function<void(int,const std::string&,ceph::buffer::list&)> on_finish) {
// by default, call the synchronous handler and then finish
ceph::buffer::list out;
std::ostringstream errss;
int r = call(command, cmdmap, inbl, f, errss, out);
on_finish(r, errss.str(), out);
}
virtual ~AdminSocketHook() {}
};
class AdminSocket
{
public:
AdminSocket(CephContext *cct);
~AdminSocket();
AdminSocket(const AdminSocket&) = delete;
AdminSocket& operator =(const AdminSocket&) = delete;
AdminSocket(AdminSocket&&) = delete;
AdminSocket& operator =(AdminSocket&&) = delete;
/**
* register an admin socket command
*
* The command is registered under a command string. Incoming
* commands are split by space and matched against the longest
* registered command. For example, if 'foo' and 'foo bar' are
* registered, and an incoming command is 'foo bar baz', it is
* matched with 'foo bar', while 'foo fud' will match 'foo'.
*
* The entire incoming command string is passed to the registered
* hook.
*
* @param command command string
* @param cmddesc command syntax descriptor
* @param hook implementation
* @param help help text. if empty, command will not be included in 'help' output.
*
* @return 0 for success, -EEXIST if command already registered.
*/
int register_command(std::string_view cmddesc,
AdminSocketHook *hook,
std::string_view help);
/*
* unregister all commands belong to hook.
*/
void unregister_commands(const AdminSocketHook *hook);
bool init(const std::string& path);
void chown(uid_t uid, gid_t gid);
void chmod(mode_t mode);
/// execute (async)
void execute_command(
const std::vector<std::string>& cmd,
const ceph::buffer::list& inbl,
std::function<void(int,const std::string&,ceph::buffer::list&)> on_fin);
/// execute (blocking)
int execute_command(
const std::vector<std::string>& cmd,
const ceph::buffer::list& inbl,
std::ostream& errss,
ceph::buffer::list *outbl);
void queue_tell_command(ceph::cref_t<MCommand> m);
void queue_tell_command(ceph::cref_t<MMonCommand> m); // for compat
private:
void shutdown();
void wakeup();
std::string create_wakeup_pipe(int *pipe_rd, int *pipe_wr);
std::string destroy_wakeup_pipe();
std::string bind_and_listen(const std::string &sock_path, int *fd);
std::thread th;
void entry() noexcept;
void do_accept();
void do_tell_queue();
CephContext *m_cct;
std::string m_path;
int m_sock_fd = -1;
int m_wakeup_rd_fd = -1;
int m_wakeup_wr_fd = -1;
bool m_shutdown = false;
bool in_hook = false;
std::condition_variable in_hook_cond;
std::mutex lock; // protects `hooks`
std::unique_ptr<AdminSocketHook> version_hook;
std::unique_ptr<AdminSocketHook> help_hook;
std::unique_ptr<AdminSocketHook> getdescs_hook;
std::mutex tell_lock;
std::list<ceph::cref_t<MCommand>> tell_queue;
std::list<ceph::cref_t<MMonCommand>> tell_legacy_queue;
struct hook_info {
AdminSocketHook* hook;
std::string desc;
std::string help;
hook_info(AdminSocketHook* hook, std::string_view desc,
std::string_view help)
: hook(hook), desc(desc), help(help) {}
};
/// find the first hook which matches the given prefix and cmdmap
std::pair<int, AdminSocketHook*> find_matched_hook(
std::string& prefix,
const cmdmap_t& cmdmap);
std::multimap<std::string, hook_info, std::less<>> hooks;
friend class AdminSocketTest;
friend class HelpHook;
friend class GetdescsHook;
};
#endif
#endif
| 7,193 | 31.405405 | 112 | h |
null | ceph-main/src/common/admin_socket_client.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 <arpa/inet.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "common/admin_socket.h"
#include "common/errno.h"
#include "common/safe_io.h"
#include "common/admin_socket_client.h"
#include "include/compat.h"
#include "include/sock_compat.h"
using std::ostringstream;
const char* get_rand_socket_path()
{
static char *g_socket_path = NULL;
if (g_socket_path == NULL) {
char buf[512];
const char *tdir = getenv("TMPDIR");
#ifdef _WIN32
if (tdir == NULL) {
tdir = getenv("TEMP");
}
#endif /* _WIN32 */
if (tdir == NULL) {
tdir = "/tmp";
}
snprintf(buf, sizeof(((struct sockaddr_un*)0)->sun_path),
"%s/perfcounters_test_socket.%ld.%ld",
tdir, (long int)getpid(), time(NULL));
g_socket_path = (char*)strdup(buf);
}
return g_socket_path;
}
static std::string asok_connect(const std::string &path, int *fd)
{
int socket_fd = socket_cloexec(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0) {
int err = ceph_sock_errno();
ostringstream oss;
oss << "socket(PF_UNIX, SOCK_STREAM, 0) failed: " << cpp_strerror(err);
return oss.str();
}
struct sockaddr_un address;
// FIPS zeroization audit 20191115: this memset is fine.
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path), "%s", path.c_str());
if (::connect(socket_fd, (struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0) {
int err = ceph_sock_errno();
ostringstream oss;
oss << "connect(" << socket_fd << ") failed: " << cpp_strerror(err);
compat_closesocket(socket_fd);
return oss.str();
}
struct timeval timer;
timer.tv_sec = 10;
timer.tv_usec = 0;
if (::setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, (SOCKOPT_VAL_TYPE)&timer, sizeof(timer))) {
int err = ceph_sock_errno();
ostringstream oss;
oss << "setsockopt(" << socket_fd << ", SO_RCVTIMEO) failed: "
<< cpp_strerror(err);
compat_closesocket(socket_fd);
return oss.str();
}
timer.tv_sec = 10;
timer.tv_usec = 0;
if (::setsockopt(socket_fd, SOL_SOCKET, SO_SNDTIMEO, (SOCKOPT_VAL_TYPE)&timer, sizeof(timer))) {
int err = ceph_sock_errno();
ostringstream oss;
oss << "setsockopt(" << socket_fd << ", SO_SNDTIMEO) failed: "
<< cpp_strerror(err);
compat_closesocket(socket_fd);
return oss.str();
}
*fd = socket_fd;
return "";
}
static std::string asok_request(int socket_fd, std::string request)
{
ssize_t res = safe_send(socket_fd, request.c_str(), request.length() + 1);
if (res < 0) {
int err = res;
ostringstream oss;
oss << "safe_write(" << socket_fd << ") failed to write request code: "
<< cpp_strerror(err);
return oss.str();
}
return "";
}
AdminSocketClient::
AdminSocketClient(const std::string &path)
: m_path(path)
{
}
std::string AdminSocketClient::ping(bool *ok)
{
std::string version;
std::string result = do_request("{\"prefix\":\"0\"}", &version);
*ok = result == "" && version.length() == 1;
return result;
}
std::string AdminSocketClient::do_request(std::string request, std::string *result)
{
int socket_fd = 0, res;
std::string buffer;
uint32_t message_size_raw, message_size;
std::string err = asok_connect(m_path, &socket_fd);
if (!err.empty()) {
goto out;
}
err = asok_request(socket_fd, request);
if (!err.empty()) {
goto done;
}
res = safe_recv_exact(socket_fd, &message_size_raw,
sizeof(message_size_raw));
if (res < 0) {
int e = res;
ostringstream oss;
oss << "safe_recv(" << socket_fd << ") failed to read message size: "
<< cpp_strerror(e);
err = oss.str();
goto done;
}
message_size = ntohl(message_size_raw);
buffer.resize(message_size, 0);
res = safe_recv_exact(socket_fd, &buffer[0], message_size);
if (res < 0) {
int e = res;
ostringstream oss;
oss << "safe_recv(" << socket_fd << ") failed: " << cpp_strerror(e);
err = oss.str();
goto done;
}
//printf("MESSAGE FROM SERVER: %s\n", buffer.c_str());
std::swap(*result, buffer);
done:
compat_closesocket(socket_fd);
out:
return err;
}
| 4,598 | 25.583815 | 98 | cc |
null | ceph-main/src/common/admin_socket_client.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_ADMIN_SOCKET_CLIENT_H
#define CEPH_COMMON_ADMIN_SOCKET_CLIENT_H
#include <string>
/* This is a simple client that talks to an AdminSocket using blocking I/O.
* We put a 5-second timeout on send and recv operations.
*/
class AdminSocketClient
{
public:
AdminSocketClient(const std::string &path);
std::string do_request(std::string request, std::string *result);
std::string ping(bool *ok);
private:
std::string m_path;
};
const char* get_rand_socket_path();
#endif
| 908 | 24.25 | 75 | h |
null | ceph-main/src/common/aix_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 <errno.h>
#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 -51:
return -EL2HLT;
case -52:
return -EPERM; //TODO EBADE
case -53:
return -EPERM; //TODO EBADR
case -54:
return -EPERM; //TODO EXFULL
case -55:
return -EPERM; //TODO ENOANO
case -56:
return -EPERM; //TODO EBADRQC
case -57:
return -EPERM; //TODO EBADSLT
case -59:
return -EPERM; //TODO 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 -EPERM; //TODO ENOTUNIQ
case -77:
return -EPERM; //TODO EBADFD
case -78:
return -EPERM; //TODO EREMCHG
case -79:
return -EPERM; //TODO ELIBACC
case -80:
return -EPERM; //TODO ELIBBAD
case -81:
return -EPERM; //TODO ELIBSCN
case -82:
return -EPERM; //TODO ELIBMAX
case -83:
return -EPERM; // TODO ELIBEXEC
case -84:
return -EILSEQ;
case -85:
return -ERESTART;
case -86:
return -EPERM; //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,361 | 22.112069 | 70 | cc |
null | ceph-main/src/common/allocate_unique.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 Red Hat
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <memory>
namespace ceph {
/// An allocator-aware 'Deleter' for std::unique_ptr<T, Deleter>. The
/// allocator's traits must have a value_type of T.
template <typename Alloc>
class deallocator {
using allocator_type = Alloc;
using allocator_traits = std::allocator_traits<allocator_type>;
using pointer = typename allocator_traits::pointer;
allocator_type alloc;
public:
explicit deallocator(const allocator_type& alloc) noexcept : alloc(alloc) {}
void operator()(pointer p) {
allocator_traits::destroy(alloc, p);
allocator_traits::deallocate(alloc, p, 1);
}
};
/// deallocator alias that rebinds Alloc's value_type to T
template <typename T, typename Alloc>
using deallocator_t = deallocator<typename std::allocator_traits<Alloc>
::template rebind_alloc<T>>;
/// std::unique_ptr alias that rebinds Alloc if necessary, and avoids repetition
/// of the template parameter T.
template <typename T, typename Alloc>
using allocated_unique_ptr = std::unique_ptr<T, deallocator_t<T, Alloc>>;
/// Returns a std::unique_ptr whose memory is managed by the given allocator.
template <typename T, typename Alloc, typename... Args>
static auto allocate_unique(Alloc& alloc, Args&&... args)
-> allocated_unique_ptr<T, Alloc>
{
static_assert(!std::is_array_v<T>, "allocate_unique() does not support T[]");
using allocator_type = typename std::allocator_traits<Alloc>
::template rebind_alloc<T>;
using allocator_traits = std::allocator_traits<allocator_type>;
auto a = allocator_type{alloc};
auto p = allocator_traits::allocate(a, 1);
try {
allocator_traits::construct(a, p, std::forward<Args>(args)...);
return {p, deallocator<allocator_type>{a}};
} catch (...) {
allocator_traits::deallocate(a, p, 1);
throw;
}
}
} // namespace ceph
| 2,217 | 30.685714 | 80 | h |
null | ceph-main/src/common/arch.h | #ifndef CEPH_ARCH_H
#define CEPH_ARCH_H
static const char *get_arch()
{
#if defined(__i386__)
return "i386";
#elif defined(__x86_64__)
return "x86-64";
#else
return "unknown";
#endif
}
#endif
| 202 | 11.6875 | 29 | h |
null | ceph-main/src/common/armor.h | #ifndef CEPH_ARMOR_H
#define CEPH_ARMOR_H
#ifdef __cplusplus
extern "C" {
#endif
int ceph_armor(char *dst, char * const dst_end,
const char * src, const char *end);
int ceph_armor_linebreak(char *dst, char * const dst_end,
const char *src, const char *end,
int line_width);
int ceph_unarmor(char *dst, char * const dst_end,
const char *src, const char * const end);
#ifdef __cplusplus
}
#endif
#endif
| 432 | 19.619048 | 57 | h |
null | ceph-main/src/common/assert.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 "include/compat.h"
#include "common/debug.h"
using std::ostringstream;
namespace ceph {
static CephContext *g_assert_context = NULL;
/* If you register an assert context, ceph_assert() will try to lock the dout
* stream of that context before starting an assert. This is nice because the
* output looks better. Your assert will not be interleaved with other dout
* statements.
*
* However, this is strictly optional and library code currently does not
* register an assert context. The extra complexity of supporting this
* wouldn't really be worth it.
*/
void register_assert_context(CephContext *cct)
{
ceph_assert(!g_assert_context);
g_assert_context = cct;
}
[[gnu::cold]] void __ceph_assert_fail(const char *assertion,
const char *file, int line,
const char *func)
{
g_assert_condition = assertion;
g_assert_file = file;
g_assert_line = line;
g_assert_func = func;
g_assert_thread = (unsigned long long)pthread_self();
ceph_pthread_getname(pthread_self(), g_assert_thread_name,
sizeof(g_assert_thread_name));
ostringstream tss;
tss << ceph_clock_now();
snprintf(g_assert_msg, sizeof(g_assert_msg),
"%s: In function '%s' thread %llx time %s\n"
"%s: %d: FAILED ceph_assert(%s)\n",
file, func, (unsigned long long)pthread_self(), tss.str().c_str(),
file, line, assertion);
dout_emergency(g_assert_msg);
// TODO: get rid of this memory allocation.
ostringstream oss;
oss << ClibBackTrace(1);
dout_emergency(oss.str());
if (g_assert_context) {
lderr(g_assert_context) << g_assert_msg << std::endl;
*_dout << oss.str() << dendl;
// dump recent only if the abort signal handler won't do it for us
if (!g_assert_context->_conf->fatal_signal_handlers) {
g_assert_context->_log->dump_recent();
}
}
abort();
}
[[gnu::cold]] void __ceph_assert_fail(const assert_data &ctx)
{
__ceph_assert_fail(ctx.assertion, ctx.file, ctx.line, ctx.function);
}
class BufAppender {
public:
BufAppender(char* buf, int size) : bufptr(buf), remaining(size) {}
void printf(const char * format, ...) {
va_list args;
va_start(args, format);
this->vprintf(format, args);
va_end(args);
}
void vprintf(const char * format, va_list args) {
int n = vsnprintf(bufptr, remaining, format, args);
if (n >= 0) {
if (n < remaining) {
remaining -= n;
bufptr += n;
} else {
remaining = 0;
}
}
}
private:
char* bufptr;
int remaining;
};
[[gnu::cold]] void __ceph_assertf_fail(const char *assertion,
const char *file, int line,
const char *func, const char* msg,
...)
{
ostringstream tss;
tss << ceph_clock_now();
g_assert_condition = assertion;
g_assert_file = file;
g_assert_line = line;
g_assert_func = func;
g_assert_thread = (unsigned long long)pthread_self();
ceph_pthread_getname(pthread_self(), g_assert_thread_name,
sizeof(g_assert_thread_name));
BufAppender ba(g_assert_msg, sizeof(g_assert_msg));
BackTrace *bt = new ClibBackTrace(1);
ba.printf("%s: In function '%s' thread %llx time %s\n"
"%s: %d: FAILED ceph_assert(%s)\n",
file, func, (unsigned long long)pthread_self(), tss.str().c_str(),
file, line, assertion);
ba.printf("Assertion details: ");
va_list args;
va_start(args, msg);
ba.vprintf(msg, args);
va_end(args);
ba.printf("\n");
dout_emergency(g_assert_msg);
// TODO: get rid of this memory allocation.
ostringstream oss;
oss << *bt;
dout_emergency(oss.str());
if (g_assert_context) {
lderr(g_assert_context) << g_assert_msg << std::endl;
*_dout << oss.str() << dendl;
// dump recent only if the abort signal handler won't do it for us
if (!g_assert_context->_conf->fatal_signal_handlers) {
g_assert_context->_log->dump_recent();
}
}
abort();
}
[[gnu::cold]] void __ceph_abort(const char *file, int line,
const char *func, const std::string& msg)
{
ostringstream tss;
tss << ceph_clock_now();
g_assert_condition = "abort";
g_assert_file = file;
g_assert_line = line;
g_assert_func = func;
g_assert_thread = (unsigned long long)pthread_self();
ceph_pthread_getname(pthread_self(), g_assert_thread_name,
sizeof(g_assert_thread_name));
BackTrace *bt = new ClibBackTrace(1);
snprintf(g_assert_msg, sizeof(g_assert_msg),
"%s: In function '%s' thread %llx time %s\n"
"%s: %d: ceph_abort_msg(\"%s\")\n", file, func,
(unsigned long long)pthread_self(),
tss.str().c_str(), file, line,
msg.c_str());
dout_emergency(g_assert_msg);
// TODO: get rid of this memory allocation.
ostringstream oss;
oss << *bt;
dout_emergency(oss.str());
if (g_assert_context) {
lderr(g_assert_context) << g_assert_msg << std::endl;
*_dout << oss.str() << dendl;
// dump recent only if the abort signal handler won't do it for us
if (!g_assert_context->_conf->fatal_signal_handlers) {
g_assert_context->_log->dump_recent();
}
}
abort();
}
[[gnu::cold]] void __ceph_abortf(const char *file, int line,
const char *func, const char* msg,
...)
{
ostringstream tss;
tss << ceph_clock_now();
g_assert_condition = "abort";
g_assert_file = file;
g_assert_line = line;
g_assert_func = func;
g_assert_thread = (unsigned long long)pthread_self();
ceph_pthread_getname(pthread_self(), g_assert_thread_name,
sizeof(g_assert_thread_name));
BufAppender ba(g_assert_msg, sizeof(g_assert_msg));
BackTrace *bt = new ClibBackTrace(1);
ba.printf("%s: In function '%s' thread %llx time %s\n"
"%s: %d: abort()\n",
file, func, (unsigned long long)pthread_self(), tss.str().c_str(),
file, line);
ba.printf("Abort details: ");
va_list args;
va_start(args, msg);
ba.vprintf(msg, args);
va_end(args);
ba.printf("\n");
dout_emergency(g_assert_msg);
// TODO: get rid of this memory allocation.
ostringstream oss;
oss << *bt;
dout_emergency(oss.str());
if (g_assert_context) {
lderr(g_assert_context) << g_assert_msg << std::endl;
*_dout << oss.str() << dendl;
// dump recent only if the abort signal handler won't do it for us
if (!g_assert_context->_conf->fatal_signal_handlers) {
g_assert_context->_log->dump_recent();
}
}
abort();
}
[[gnu::cold]] void __ceph_assert_warn(const char *assertion,
const char *file,
int line, const char *func)
{
char buf[8096];
snprintf(buf, sizeof(buf),
"WARNING: ceph_assert(%s) at: %s: %d: %s()\n",
assertion, file, line, func);
dout_emergency(buf);
}
}
| 7,321 | 27.27027 | 79 | cc |
null | ceph-main/src/common/autovector.h | // Copyright (c) 2018-Present Red Hat Inc. All rights reserved.
//
// Copyright (c) 2011-2018, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 and Apache 2.0 License
#ifndef CEPH_AUTOVECTOR_H
#define CEPH_AUTOVECTOR_H
#include <algorithm>
#include <cassert>
#include <initializer_list>
#include <iterator>
#include <stdexcept>
#include <vector>
#include "include/ceph_assert.h"
// A vector that leverages pre-allocated stack-based array to achieve better
// performance for array with small amount of items.
//
// The interface resembles that of vector, but with less features since we aim
// to solve the problem that we have in hand, rather than implementing a
// full-fledged generic container.
//
// Currently we don't support:
// * reserve()/shrink_to_fit()
// If used correctly, in most cases, people should not touch the
// underlying vector at all.
// * random insert()/erase(), please only use push_back()/pop_back().
// * No move/swap operations. Each autovector instance has a
// stack-allocated array and if we want support move/swap operations, we
// need to copy the arrays other than just swapping the pointers. In this
// case we'll just explicitly forbid these operations since they may
// lead users to make false assumption by thinking they are inexpensive
// operations.
//
// Naming style of public methods almost follows that of the STL's.
namespace ceph {
template <class T, size_t kSize = 8>
class autovector {
public:
// General STL-style container member types.
typedef T value_type;
typedef typename std::vector<T>::difference_type difference_type;
typedef typename std::vector<T>::size_type size_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
// This class is the base for regular/const iterator
template <class TAutoVector, class TValueType>
class iterator_impl {
public:
// -- iterator traits
typedef iterator_impl<TAutoVector, TValueType> self_type;
typedef TValueType value_type;
typedef TValueType& reference;
typedef TValueType* pointer;
typedef typename TAutoVector::difference_type difference_type;
typedef std::random_access_iterator_tag iterator_category;
iterator_impl(TAutoVector* vect, size_t index)
: vect_(vect), index_(index) {};
iterator_impl(const iterator_impl&) = default;
~iterator_impl() {}
iterator_impl& operator=(const iterator_impl&) = default;
// -- Advancement
// ++iterator
self_type& operator++() {
++index_;
return *this;
}
// iterator++
self_type operator++(int) {
auto old = *this;
++index_;
return old;
}
// --iterator
self_type& operator--() {
--index_;
return *this;
}
// iterator--
self_type operator--(int) {
auto old = *this;
--index_;
return old;
}
self_type operator-(difference_type len) const {
return self_type(vect_, index_ - len);
}
difference_type operator-(const self_type& other) const {
ceph_assert(vect_ == other.vect_);
return index_ - other.index_;
}
self_type operator+(difference_type len) const {
return self_type(vect_, index_ + len);
}
self_type& operator+=(difference_type len) {
index_ += len;
return *this;
}
self_type& operator-=(difference_type len) {
index_ -= len;
return *this;
}
// -- Reference
reference operator*() {
ceph_assert(vect_->size() >= index_);
return (*vect_)[index_];
}
const_reference operator*() const {
ceph_assert(vect_->size() >= index_);
return (*vect_)[index_];
}
pointer operator->() {
ceph_assert(vect_->size() >= index_);
return &(*vect_)[index_];
}
const_pointer operator->() const {
ceph_assert(vect_->size() >= index_);
return &(*vect_)[index_];
}
// -- Logical Operators
bool operator==(const self_type& other) const {
ceph_assert(vect_ == other.vect_);
return index_ == other.index_;
}
bool operator!=(const self_type& other) const { return !(*this == other); }
bool operator>(const self_type& other) const {
ceph_assert(vect_ == other.vect_);
return index_ > other.index_;
}
bool operator<(const self_type& other) const {
ceph_assert(vect_ == other.vect_);
return index_ < other.index_;
}
bool operator>=(const self_type& other) const {
ceph_assert(vect_ == other.vect_);
return index_ >= other.index_;
}
bool operator<=(const self_type& other) const {
ceph_assert(vect_ == other.vect_);
return index_ <= other.index_;
}
private:
TAutoVector* vect_ = nullptr;
size_t index_ = 0;
};
typedef iterator_impl<autovector, value_type> iterator;
typedef iterator_impl<const autovector, const value_type> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
autovector() = default;
autovector(std::initializer_list<T> init_list) {
for (const T& item : init_list) {
push_back(item);
}
}
~autovector() = default;
// -- Immutable operations
// Indicate if all data resides in in-stack data structure.
bool only_in_stack() const {
// If no element was inserted at all, the vector's capacity will be `0`.
return vect_.capacity() == 0;
}
size_type size() const { return num_stack_items_ + vect_.size(); }
// resize does not guarantee anything about the contents of the newly
// available elements
void resize(size_type n) {
if (n > kSize) {
vect_.resize(n - kSize);
num_stack_items_ = kSize;
} else {
vect_.clear();
num_stack_items_ = n;
}
}
bool empty() const { return size() == 0; }
const_reference operator[](size_type n) const {
ceph_assert(n < size());
return n < kSize ? values_[n] : vect_[n - kSize];
}
reference operator[](size_type n) {
ceph_assert(n < size());
return n < kSize ? values_[n] : vect_[n - kSize];
}
const_reference at(size_type n) const {
ceph_assert(n < size());
return (*this)[n];
}
reference at(size_type n) {
ceph_assert(n < size());
return (*this)[n];
}
reference front() {
ceph_assert(!empty());
return *begin();
}
const_reference front() const {
ceph_assert(!empty());
return *begin();
}
reference back() {
ceph_assert(!empty());
return *(end() - 1);
}
const_reference back() const {
ceph_assert(!empty());
return *(end() - 1);
}
// -- Mutable Operations
void push_back(T&& item) {
if (num_stack_items_ < kSize) {
values_[num_stack_items_++] = std::move(item);
} else {
vect_.push_back(item);
}
}
void push_back(const T& item) {
if (num_stack_items_ < kSize) {
values_[num_stack_items_++] = item;
} else {
vect_.push_back(item);
}
}
template <class... Args>
void emplace_back(Args&&... args) {
push_back(value_type(args...));
}
void pop_back() {
ceph_assert(!empty());
if (!vect_.empty()) {
vect_.pop_back();
} else {
--num_stack_items_;
}
}
void clear() {
num_stack_items_ = 0;
vect_.clear();
}
// -- Copy and Assignment
autovector& assign(const autovector& other);
autovector(const autovector& other) { assign(other); }
autovector& operator=(const autovector& other) { return assign(other); }
// -- Iterator Operations
iterator begin() { return iterator(this, 0); }
const_iterator begin() const { return const_iterator(this, 0); }
iterator end() { return iterator(this, this->size()); }
const_iterator end() const { return const_iterator(this, this->size()); }
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
private:
size_type num_stack_items_ = 0; // current number of items
value_type values_[kSize]; // the first `kSize` items
// used only if there are more than `kSize` items.
std::vector<T> vect_;
};
template <class T, size_t kSize>
autovector<T, kSize>& autovector<T, kSize>::assign(const autovector& other) {
// copy the internal vector
vect_.assign(other.vect_.begin(), other.vect_.end());
// copy array
num_stack_items_ = other.num_stack_items_;
std::copy(other.values_, other.values_ + num_stack_items_, values_);
return *this;
}
} // namespace ceph
#endif // CEPH_AUTOVECTOR_H
| 8,854 | 25.275964 | 79 | h |
null | ceph-main/src/common/bit_str.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 SUSE LINUX GmbH
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/bit_str.h"
#include "common/Formatter.h"
#include "include/ceph_assert.h"
static void _dump_bit_str(
uint64_t bits,
std::ostream *out,
ceph::Formatter *f,
std::function<const char*(uint64_t)> func,
bool dump_bit_val)
{
uint64_t b = bits;
int cnt = 0;
bool outted = false;
while (b && cnt < 64) {
uint64_t r = bits & (1ULL << cnt++);
if (r) {
if (out) {
if (outted)
*out << ",";
*out << func(r);
if (dump_bit_val) {
*out << "(" << r << ")";
}
} else {
ceph_assert(f != NULL);
if (dump_bit_val) {
f->dump_stream("bit_flag") << func(r)
<< "(" << r << ")";
} else {
f->dump_stream("bit_flag") << func(r);
}
}
outted = true;
}
b >>= 1;
}
if (!outted && out)
*out << "none";
}
void print_bit_str(
uint64_t bits,
std::ostream &out,
const std::function<const char*(uint64_t)> &func,
bool dump_bit_val)
{
_dump_bit_str(bits, &out, NULL, func, dump_bit_val);
}
void dump_bit_str(
uint64_t bits,
ceph::Formatter *f,
const std::function<const char*(uint64_t)> &func,
bool dump_bit_val)
{
_dump_bit_str(bits, NULL, f, func, dump_bit_val);
}
| 1,710 | 22.438356 | 70 | cc |
null | ceph-main/src/common/bit_str.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 SUSE LINUX GmbH
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_BIT_STR_H
#define CEPH_COMMON_BIT_STR_H
#include <cstdint>
#include <iosfwd>
#include <functional>
namespace ceph {
class Formatter;
}
extern void print_bit_str(
uint64_t bits,
std::ostream &out,
const std::function<const char*(uint64_t)> &func,
bool dump_bit_val = false);
extern void dump_bit_str(
uint64_t bits,
ceph::Formatter *f,
const std::function<const char*(uint64_t)> &func,
bool dump_bit_val = false);
#endif /* CEPH_COMMON_BIT_STR_H */
| 913 | 23.052632 | 70 | h |
null | ceph-main/src/common/bit_vector.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) 2014 Red Hat <[email protected]>
*
* LGPL2.1 (see COPYING-LGPL2.1) or later
*/
#ifndef BIT_VECTOR_HPP
#define BIT_VECTOR_HPP
#include "common/Formatter.h"
#include "include/ceph_assert.h"
#include "include/encoding.h"
#include <memory>
#include <utility>
#include <vector>
namespace ceph {
template <uint8_t _bit_count>
class BitVector
{
private:
static const uint8_t BITS_PER_BYTE = 8;
static const uint32_t ELEMENTS_PER_BLOCK = BITS_PER_BYTE / _bit_count;
static const uint8_t MASK = static_cast<uint8_t>((1 << _bit_count) - 1);
// must be power of 2
BOOST_STATIC_ASSERT((_bit_count != 0) && !(_bit_count & (_bit_count - 1)));
BOOST_STATIC_ASSERT(_bit_count <= BITS_PER_BYTE);
template <typename DataIterator>
class ReferenceImpl {
protected:
DataIterator m_data_iterator;
uint64_t m_shift;
ReferenceImpl(const DataIterator& data_iterator, uint64_t shift)
: m_data_iterator(data_iterator), m_shift(shift) {
}
ReferenceImpl(DataIterator&& data_iterator, uint64_t shift)
: m_data_iterator(std::move(data_iterator)), m_shift(shift) {
}
public:
inline operator uint8_t() const {
return (*m_data_iterator >> m_shift) & MASK;
}
};
public:
class ConstReference : public ReferenceImpl<bufferlist::const_iterator> {
private:
friend class BitVector;
ConstReference(const bufferlist::const_iterator& data_iterator,
uint64_t shift)
: ReferenceImpl<bufferlist::const_iterator>(data_iterator, shift) {
}
ConstReference(bufferlist::const_iterator&& data_iterator, uint64_t shift)
: ReferenceImpl<bufferlist::const_iterator>(std::move(data_iterator),
shift) {
}
};
class Reference : public ReferenceImpl<bufferlist::iterator> {
public:
Reference& operator=(uint8_t v);
private:
friend class BitVector;
Reference(const bufferlist::iterator& data_iterator, uint64_t shift)
: ReferenceImpl<bufferlist::iterator>(data_iterator, shift) {
}
Reference(bufferlist::iterator&& data_iterator, uint64_t shift)
: ReferenceImpl<bufferlist::iterator>(std::move(data_iterator), shift) {
}
};
public:
template <typename BitVectorT, typename DataIterator>
class IteratorImpl {
private:
friend class BitVector;
uint64_t m_offset = 0;
BitVectorT *m_bit_vector;
// cached derived values
uint64_t m_index = 0;
uint64_t m_shift = 0;
DataIterator m_data_iterator;
IteratorImpl(BitVectorT *bit_vector, uint64_t offset)
: m_bit_vector(bit_vector),
m_data_iterator(bit_vector->m_data.begin()) {
*this += offset;
}
public:
inline IteratorImpl& operator++() {
++m_offset;
uint64_t index;
compute_index(m_offset, &index, &m_shift);
ceph_assert(index == m_index || index == m_index + 1);
if (index > m_index) {
m_index = index;
++m_data_iterator;
}
return *this;
}
inline IteratorImpl& operator+=(uint64_t offset) {
m_offset += offset;
compute_index(m_offset, &m_index, &m_shift);
if (m_offset < m_bit_vector->size()) {
m_data_iterator.seek(m_index);
} else {
m_data_iterator = m_bit_vector->m_data.end();
}
return *this;
}
inline IteratorImpl operator++(int) {
IteratorImpl iterator_impl(*this);
++iterator_impl;
return iterator_impl;
}
inline IteratorImpl operator+(uint64_t offset) {
IteratorImpl iterator_impl(*this);
iterator_impl += offset;
return iterator_impl;
}
inline bool operator==(const IteratorImpl& rhs) const {
return (m_offset == rhs.m_offset && m_bit_vector == rhs.m_bit_vector);
}
inline bool operator!=(const IteratorImpl& rhs) const {
return (m_offset != rhs.m_offset || m_bit_vector != rhs.m_bit_vector);
}
inline ConstReference operator*() const {
return ConstReference(m_data_iterator, m_shift);
}
inline Reference operator*() {
return Reference(m_data_iterator, m_shift);
}
};
typedef IteratorImpl<const BitVector,
bufferlist::const_iterator> ConstIterator;
typedef IteratorImpl<BitVector, bufferlist::iterator> Iterator;
static const uint32_t BLOCK_SIZE;
static const uint8_t BIT_COUNT = _bit_count;
BitVector();
inline ConstIterator begin() const {
return ConstIterator(this, 0);
}
inline ConstIterator end() const {
return ConstIterator(this, m_size);
}
inline Iterator begin() {
return Iterator(this, 0);
}
inline Iterator end() {
return Iterator(this, m_size);
}
void set_crc_enabled(bool enabled) {
m_crc_enabled = enabled;
}
void clear();
void resize(uint64_t elements);
uint64_t size() const;
const bufferlist& get_data() const;
Reference operator[](uint64_t offset);
ConstReference operator[](uint64_t offset) const;
void encode_header(bufferlist& bl) const;
void decode_header(bufferlist::const_iterator& it);
uint64_t get_header_length() const;
void encode_data(bufferlist& bl, uint64_t data_byte_offset,
uint64_t byte_length) const;
void decode_data(bufferlist::const_iterator& it, uint64_t data_byte_offset);
void get_data_extents(uint64_t offset, uint64_t length,
uint64_t *data_byte_offset,
uint64_t *object_byte_offset,
uint64_t *byte_length) const;
void encode_footer(bufferlist& bl) const;
void decode_footer(bufferlist::const_iterator& it);
uint64_t get_footer_offset() const;
void decode_header_crc(bufferlist::const_iterator& it);
void get_header_crc_extents(uint64_t *byte_offset,
uint64_t *byte_length) const;
void encode_data_crcs(bufferlist& bl, uint64_t offset,
uint64_t length) const;
void decode_data_crcs(bufferlist::const_iterator& it, uint64_t offset);
void get_data_crcs_extents(uint64_t offset, uint64_t length,
uint64_t *byte_offset,
uint64_t *byte_length) const;
void encode(bufferlist& bl) const;
void decode(bufferlist::const_iterator& it);
void dump(Formatter *f) const;
bool operator==(const BitVector &b) const;
static void generate_test_instances(std::list<BitVector *> &o);
private:
bufferlist m_data;
uint64_t m_size;
bool m_crc_enabled;
mutable __u32 m_header_crc;
// inhibit value-initialization when used in std::vector
struct u32_struct {
u32_struct() {}
__u32 val;
};
mutable std::vector<u32_struct> m_data_crcs;
void resize(uint64_t elements, bool zero);
static void compute_index(uint64_t offset, uint64_t *index, uint64_t *shift);
};
template <uint8_t _b>
const uint32_t BitVector<_b>::BLOCK_SIZE = 4096;
template <uint8_t _b>
BitVector<_b>::BitVector() : m_size(0), m_crc_enabled(true), m_header_crc(0)
{
}
template <uint8_t _b>
void BitVector<_b>::clear() {
m_data.clear();
m_data_crcs.clear();
m_size = 0;
m_header_crc = 0;
}
template <uint8_t _b>
void BitVector<_b>::resize(uint64_t size) {
resize(size, true);
}
template <uint8_t _b>
void BitVector<_b>::resize(uint64_t size, bool zero) {
uint64_t buffer_size = (size + ELEMENTS_PER_BLOCK - 1) / ELEMENTS_PER_BLOCK;
if (buffer_size > m_data.length()) {
if (zero) {
m_data.append_zero(buffer_size - m_data.length());
} else {
m_data.append(buffer::ptr(buffer_size - m_data.length()));
}
} else if (buffer_size < m_data.length()) {
bufferlist bl;
bl.substr_of(m_data, 0, buffer_size);
bl.swap(m_data);
}
m_size = size;
uint64_t block_count = (buffer_size + BLOCK_SIZE - 1) / BLOCK_SIZE;
m_data_crcs.resize(block_count);
}
template <uint8_t _b>
uint64_t BitVector<_b>::size() const {
return m_size;
}
template <uint8_t _b>
const bufferlist& BitVector<_b>::get_data() const {
return m_data;
}
template <uint8_t _b>
void BitVector<_b>::compute_index(uint64_t offset, uint64_t *index, uint64_t *shift) {
*index = offset / ELEMENTS_PER_BLOCK;
*shift = ((ELEMENTS_PER_BLOCK - 1) - (offset % ELEMENTS_PER_BLOCK)) * _b;
}
template <uint8_t _b>
void BitVector<_b>::encode_header(bufferlist& bl) const {
bufferlist header_bl;
ENCODE_START(1, 1, header_bl);
encode(m_size, header_bl);
ENCODE_FINISH(header_bl);
m_header_crc = header_bl.crc32c(0);
encode(header_bl, bl);
}
template <uint8_t _b>
void BitVector<_b>::decode_header(bufferlist::const_iterator& it) {
using ceph::decode;
bufferlist header_bl;
decode(header_bl, it);
auto header_it = header_bl.cbegin();
uint64_t size;
DECODE_START(1, header_it);
decode(size, header_it);
DECODE_FINISH(header_it);
resize(size, false);
m_header_crc = header_bl.crc32c(0);
}
template <uint8_t _b>
uint64_t BitVector<_b>::get_header_length() const {
// 4 byte bl length, 6 byte encoding header, 8 byte size
return 18;
}
template <uint8_t _b>
void BitVector<_b>::encode_data(bufferlist& bl, uint64_t data_byte_offset,
uint64_t byte_length) const {
ceph_assert(data_byte_offset % BLOCK_SIZE == 0);
ceph_assert(data_byte_offset + byte_length == m_data.length() ||
byte_length % BLOCK_SIZE == 0);
uint64_t end_offset = data_byte_offset + byte_length;
while (data_byte_offset < end_offset) {
uint64_t len = std::min<uint64_t>(BLOCK_SIZE,
end_offset - data_byte_offset);
bufferlist bit;
bit.substr_of(m_data, data_byte_offset, len);
m_data_crcs[data_byte_offset / BLOCK_SIZE].val = bit.crc32c(0);
bl.claim_append(bit);
data_byte_offset += BLOCK_SIZE;
}
}
template <uint8_t _b>
void BitVector<_b>::decode_data(bufferlist::const_iterator& it,
uint64_t data_byte_offset) {
ceph_assert(data_byte_offset % BLOCK_SIZE == 0);
if (it.end()) {
return;
}
uint64_t end_offset = data_byte_offset + it.get_remaining();
if (end_offset > m_data.length()) {
throw buffer::end_of_buffer();
}
bufferlist data;
if (data_byte_offset > 0) {
data.substr_of(m_data, 0, data_byte_offset);
}
while (data_byte_offset < end_offset) {
uint64_t len = std::min<uint64_t>(BLOCK_SIZE, end_offset - data_byte_offset);
bufferptr ptr;
it.copy_deep(len, ptr);
bufferlist bit;
bit.append(ptr);
if (m_crc_enabled &&
m_data_crcs[data_byte_offset / BLOCK_SIZE].val != bit.crc32c(0)) {
throw buffer::malformed_input("invalid data block CRC");
}
data.append(bit);
data_byte_offset += bit.length();
}
if (m_data.length() > end_offset) {
bufferlist tail;
tail.substr_of(m_data, end_offset, m_data.length() - end_offset);
data.append(tail);
}
ceph_assert(data.length() == m_data.length());
data.swap(m_data);
}
template <uint8_t _b>
void BitVector<_b>::get_data_extents(uint64_t offset, uint64_t length,
uint64_t *data_byte_offset,
uint64_t *object_byte_offset,
uint64_t *byte_length) const {
// read BLOCK_SIZE-aligned chunks
ceph_assert(length > 0 && offset + length <= m_size);
uint64_t shift;
compute_index(offset, data_byte_offset, &shift);
*data_byte_offset -= (*data_byte_offset % BLOCK_SIZE);
uint64_t end_offset;
compute_index(offset + length - 1, &end_offset, &shift);
end_offset += (BLOCK_SIZE - (end_offset % BLOCK_SIZE));
ceph_assert(*data_byte_offset <= end_offset);
*object_byte_offset = get_header_length() + *data_byte_offset;
*byte_length = end_offset - *data_byte_offset;
if (*data_byte_offset + *byte_length > m_data.length()) {
*byte_length = m_data.length() - *data_byte_offset;
}
}
template <uint8_t _b>
void BitVector<_b>::encode_footer(bufferlist& bl) const {
using ceph::encode;
bufferlist footer_bl;
if (m_crc_enabled) {
encode(m_header_crc, footer_bl);
__u32 size = m_data_crcs.size();
encode(size, footer_bl);
encode_data_crcs(footer_bl, 0, m_size);
}
encode(footer_bl, bl);
}
template <uint8_t _b>
void BitVector<_b>::decode_footer(bufferlist::const_iterator& it) {
using ceph::decode;
bufferlist footer_bl;
decode(footer_bl, it);
m_crc_enabled = (footer_bl.length() > 0);
if (m_crc_enabled) {
auto footer_it = footer_bl.cbegin();
decode_header_crc(footer_it);
__u32 data_src_size;
decode(data_src_size, footer_it);
decode_data_crcs(footer_it, 0);
uint64_t block_count = (m_data.length() + BLOCK_SIZE - 1) / BLOCK_SIZE;
if (m_data_crcs.size() != block_count) {
throw buffer::malformed_input("invalid data block CRCs");
}
}
}
template <uint8_t _b>
uint64_t BitVector<_b>::get_footer_offset() const {
return get_header_length() + m_data.length();
}
template <uint8_t _b>
void BitVector<_b>::decode_header_crc(bufferlist::const_iterator& it) {
if (it.get_remaining() > 0) {
__u32 header_crc;
ceph::decode(header_crc, it);
if (m_header_crc != header_crc) {
throw buffer::malformed_input("incorrect header CRC");
}
}
}
template <uint8_t _b>
void BitVector<_b>::get_header_crc_extents(uint64_t *byte_offset,
uint64_t *byte_length) const {
// footer is prefixed with a bufferlist length
*byte_offset = get_footer_offset() + sizeof(__u32);
*byte_length = sizeof(__u32);
}
template <uint8_t _b>
void BitVector<_b>::encode_data_crcs(bufferlist& bl, uint64_t offset,
uint64_t length) const {
if (length == 0) {
return;
}
uint64_t index;
uint64_t shift;
compute_index(offset, &index, &shift);
uint64_t crc_index = index / BLOCK_SIZE;
compute_index(offset + length - 1, &index, &shift);
uint64_t end_crc_index = index / BLOCK_SIZE;
while (crc_index <= end_crc_index) {
__u32 crc = m_data_crcs[crc_index++].val;
ceph::encode(crc, bl);
}
}
template <uint8_t _b>
void BitVector<_b>::decode_data_crcs(bufferlist::const_iterator& it,
uint64_t offset) {
if (it.end()) {
return;
}
uint64_t index;
uint64_t shift;
compute_index(offset, &index, &shift);
uint64_t crc_index = index / BLOCK_SIZE;
uint64_t remaining = it.get_remaining() / sizeof(__u32);
while (remaining > 0) {
__u32 crc;
ceph::decode(crc, it);
m_data_crcs[crc_index++].val = crc;
--remaining;
}
}
template <uint8_t _b>
void BitVector<_b>::get_data_crcs_extents(uint64_t offset, uint64_t length,
uint64_t *byte_offset,
uint64_t *byte_length) const {
// data CRCs immediately follow the header CRC
get_header_crc_extents(byte_offset, byte_length);
*byte_offset += *byte_length;
// skip past data CRC vector size
*byte_offset += sizeof(__u32);
// CRCs are computed over BLOCK_SIZE chunks
ceph_assert(length > 0 && offset + length <= m_size);
uint64_t index;
uint64_t shift;
compute_index(offset, &index, &shift);
uint64_t start_byte_offset =
*byte_offset + ((index / BLOCK_SIZE) * sizeof(__u32));
compute_index(offset + length, &index, &shift);
uint64_t end_byte_offset =
*byte_offset + (((index / BLOCK_SIZE) + 1) * sizeof(__u32));
ceph_assert(start_byte_offset < end_byte_offset);
*byte_offset = start_byte_offset;
*byte_length = end_byte_offset - start_byte_offset;
}
template <uint8_t _b>
void BitVector<_b>::encode(bufferlist& bl) const {
encode_header(bl);
encode_data(bl, 0, m_data.length());
encode_footer(bl);
}
template <uint8_t _b>
void BitVector<_b>::decode(bufferlist::const_iterator& it) {
decode_header(it);
bufferlist data_bl;
if (m_data.length() > 0) {
it.copy(m_data.length(), data_bl);
}
decode_footer(it);
auto data_it = data_bl.cbegin();
decode_data(data_it, 0);
}
template <uint8_t _b>
void BitVector<_b>::dump(Formatter *f) const {
f->dump_unsigned("size", m_size);
f->open_array_section("bit_table");
for (unsigned i = 0; i < m_data.length(); ++i) {
f->dump_format("byte", "0x%02hhX", m_data[i]);
}
f->close_section();
}
template <uint8_t _b>
bool BitVector<_b>::operator==(const BitVector &b) const {
return (this->m_size == b.m_size && this->m_data == b.m_data);
}
template <uint8_t _b>
typename BitVector<_b>::Reference BitVector<_b>::operator[](uint64_t offset) {
uint64_t index;
uint64_t shift;
compute_index(offset, &index, &shift);
bufferlist::iterator data_iterator(m_data.begin());
data_iterator.seek(index);
return Reference(std::move(data_iterator), shift);
}
template <uint8_t _b>
typename BitVector<_b>::ConstReference BitVector<_b>::operator[](uint64_t offset) const {
uint64_t index;
uint64_t shift;
compute_index(offset, &index, &shift);
bufferlist::const_iterator data_iterator(m_data.begin());
data_iterator.seek(index);
return ConstReference(std::move(data_iterator), shift);
}
template <uint8_t _b>
typename BitVector<_b>::Reference& BitVector<_b>::Reference::operator=(uint8_t v) {
uint8_t mask = MASK << this->m_shift;
char packed_value = (*this->m_data_iterator & ~mask) |
((v << this->m_shift) & mask);
bufferlist::iterator it(this->m_data_iterator);
it.copy_in(1, &packed_value, true);
return *this;
}
template <uint8_t _b>
void BitVector<_b>::generate_test_instances(std::list<BitVector *> &o) {
o.push_back(new BitVector());
BitVector *b = new BitVector();
const uint64_t radix = 1 << b->BIT_COUNT;
const uint64_t size = 1024;
b->resize(size, false);
for (uint64_t i = 0; i < size; ++i) {
(*b)[i] = rand() % radix;
}
o.push_back(b);
}
WRITE_CLASS_ENCODER(ceph::BitVector<2>)
template <uint8_t _b>
inline std::ostream& operator<<(std::ostream& out, const ceph::BitVector<_b> &b)
{
out << "ceph::BitVector<" << _b << ">(size=" << b.size() << ", data="
<< b.get_data() << ")";
return out;
}
}
#endif // BIT_VECTOR_HPP
| 18,156 | 27.020062 | 89 | hpp |
null | ceph-main/src/common/blkdev.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
*
* 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/compat.h"
#ifdef __FreeBSD__
#include <sys/param.h>
#include <geom/geom_disk.h>
#include <sys/disk.h>
#include <fcntl.h>
#endif
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <boost/algorithm/string/replace.hpp>
//#include "common/debug.h"
#include "include/scope_guard.h"
#include "include/uuid.h"
#include "include/stringify.h"
#include "blkdev.h"
#include "numa.h"
#include "json_spirit/json_spirit_reader.h"
int get_device_by_path(const char *path, char* partition, char* device,
size_t max)
{
int fd = ::open(path, O_RDONLY|O_DIRECTORY);
if (fd < 0) {
return -errno;
}
auto close_fd = make_scope_guard([fd] {
::close(fd);
});
BlkDev blkdev(fd);
if (auto ret = blkdev.partition(partition, max); ret) {
return ret;
}
if (auto ret = blkdev.wholedisk(device, max); ret) {
return ret;
}
return 0;
}
#include "common/blkdev.h"
#ifdef __linux__
#include <libudev.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <blkid/blkid.h>
#include <set>
#include "common/SubProcess.h"
#include "common/errno.h"
#define UUID_LEN 36
#endif
using namespace std::literals;
using std::string;
using ceph::bufferlist;
BlkDev::BlkDev(int f)
: fd(f)
{}
BlkDev::BlkDev(const std::string& devname)
: devname(devname)
{}
int BlkDev::get_devid(dev_t *id) const
{
struct stat st;
int r;
if (fd >= 0) {
r = fstat(fd, &st);
} else {
char path[PATH_MAX];
snprintf(path, sizeof(path), "/dev/%s", devname.c_str());
r = stat(path, &st);
}
if (r < 0) {
return -errno;
}
*id = S_ISBLK(st.st_mode) ? st.st_rdev : st.st_dev;
return 0;
}
#ifdef __linux__
const char *BlkDev::sysfsdir() const {
return "/sys";
}
int BlkDev::get_size(int64_t *psize) const
{
#ifdef BLKGETSIZE64
int ret = ::ioctl(fd, BLKGETSIZE64, psize);
#elif defined(BLKGETSIZE)
unsigned long sectors = 0;
int ret = ::ioctl(fd, BLKGETSIZE, §ors);
*psize = sectors * 512ULL;
#else
// cppcheck-suppress preprocessorErrorDirective
# error "Linux configuration error (get_size)"
#endif
if (ret < 0)
ret = -errno;
return ret;
}
/**
* get a block device property as a string
*
* store property in *val, up to maxlen chars
* return 0 on success
* return negative error on error
*/
int64_t BlkDev::get_string_property(const char* prop,
char *val, size_t maxlen) const
{
char filename[PATH_MAX], wd[PATH_MAX];
const char* dev = nullptr;
if (fd >= 0) {
// sysfs isn't fully populated for partitions, so we need to lookup the sysfs
// entry for the underlying whole disk.
if (int r = wholedisk(wd, sizeof(wd)); r < 0)
return r;
dev = wd;
} else {
dev = devname.c_str();
}
if (snprintf(filename, sizeof(filename), "%s/block/%s/%s", sysfsdir(), dev,
prop) >= static_cast<int>(sizeof(filename))) {
return -ERANGE;
}
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
return -errno;
}
int r = 0;
if (fgets(val, maxlen - 1, fp)) {
// truncate at newline
char *p = val;
while (*p && *p != '\n')
++p;
*p = 0;
} else {
r = -EINVAL;
}
fclose(fp);
return r;
}
/**
* get a block device property
*
* return the value (we assume it is positive)
* return negative error on error
*/
int64_t BlkDev::get_int_property(const char* prop) const
{
char buff[256] = {0};
int r = get_string_property(prop, buff, sizeof(buff));
if (r < 0)
return r;
// take only digits
for (char *p = buff; *p; ++p) {
if (!isdigit(*p)) {
*p = 0;
break;
}
}
char *endptr = 0;
r = strtoll(buff, &endptr, 10);
if (endptr != buff + strlen(buff))
r = -EINVAL;
return r;
}
bool BlkDev::support_discard() const
{
return get_int_property("queue/discard_granularity") > 0;
}
int BlkDev::discard(int64_t offset, int64_t len) const
{
uint64_t range[2] = {(uint64_t)offset, (uint64_t)len};
return ioctl(fd, BLKDISCARD, range);
}
int BlkDev::get_optimal_io_size() const
{
return get_int_property("queue/optimal_io_size");
}
bool BlkDev::is_rotational() const
{
return get_int_property("queue/rotational") > 0;
}
int BlkDev::get_numa_node(int *node) const
{
int numa = get_int_property("device/device/numa_node");
if (numa < 0)
return -1;
*node = numa;
return 0;
}
int BlkDev::dev(char *dev, size_t max) const
{
return get_string_property("dev", dev, max);
}
int BlkDev::vendor(char *vendor, size_t max) const
{
return get_string_property("device/device/vendor", vendor, max);
}
int BlkDev::model(char *model, size_t max) const
{
return get_string_property("device/model", model, max);
}
int BlkDev::serial(char *serial, size_t max) const
{
return get_string_property("device/serial", serial, max);
}
int BlkDev::partition(char *partition, size_t max) const
{
dev_t id;
int r = get_devid(&id);
if (r < 0)
return -EINVAL; // hrm.
char *t = blkid_devno_to_devname(id);
if (!t) {
return -EINVAL;
}
strncpy(partition, t, max);
free(t);
return 0;
}
int BlkDev::wholedisk(char *device, size_t max) const
{
dev_t id;
int r = get_devid(&id);
if (r < 0)
return -EINVAL; // hrm.
r = blkid_devno_to_wholedisk(id, device, max, nullptr);
if (r < 0) {
return -EINVAL;
}
return 0;
}
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;
}
void get_dm_parents(const std::string& dev, std::set<std::string> *ls)
{
std::string p = std::string("/sys/block/") + dev + "/slaves";
std::set<std::string> parents;
easy_readdir(p, &parents);
for (auto& d : parents) {
ls->insert(d);
// recurse in case it is dm-on-dm
if (d.find("dm-") == 0) {
get_dm_parents(d, ls);
}
}
}
void get_raw_devices(const std::string& in,
std::set<std::string> *ls)
{
if (in.substr(0, 3) == "dm-") {
std::set<std::string> o;
get_dm_parents(in, &o);
for (auto& d : o) {
get_raw_devices(d, ls);
}
} else {
BlkDev d(in);
std::string wholedisk;
if (d.wholedisk(&wholedisk) == 0) {
ls->insert(wholedisk);
} else {
ls->insert(in);
}
}
}
std::string _decode_model_enc(const std::string& in)
{
auto v = boost::replace_all_copy(in, "\\x20", " ");
if (auto found = v.find_last_not_of(" "); found != v.npos) {
v.erase(found + 1);
}
std::replace(v.begin(), v.end(), ' ', '_');
// remove "__", which seems to come up on by ubuntu box for some reason.
while (true) {
auto p = v.find("__");
if (p == std::string::npos) break;
v.replace(p, 2, "_");
}
return v;
}
// trying to use udev first, and if it doesn't work, we fall back to
// reading /sys/block/$devname/device/(vendor/model/serial).
std::string get_device_id(const std::string& devname,
std::string *err)
{
struct udev_device *dev;
static struct udev *udev;
const char *data;
udev = udev_new();
if (!udev) {
if (err) {
*err = "udev_new failed";
}
return {};
}
dev = udev_device_new_from_subsystem_sysname(udev, "block", devname.c_str());
if (!dev) {
if (err) {
*err = std::string("udev_device_new_from_subsystem_sysname failed on '")
+ devname + "'";
}
udev_unref(udev);
return {};
}
// ****
// NOTE: please keep this implementation in sync with _get_device_id() in
// src/ceph-volume/ceph_volume/util/device.py
// ****
std::string id_vendor, id_model, id_serial, id_serial_short, id_scsi_serial;
data = udev_device_get_property_value(dev, "ID_VENDOR");
if (data) {
id_vendor = data;
}
data = udev_device_get_property_value(dev, "ID_MODEL");
if (data) {
id_model = data;
// sometimes, ID_MODEL is "LVM ..." but ID_MODEL_ENC is correct (but
// encoded with \x20 for space).
if (id_model.substr(0, 7) == "LVM PV ") {
const char *enc = udev_device_get_property_value(dev, "ID_MODEL_ENC");
if (enc) {
id_model = _decode_model_enc(enc);
} else {
// ignore ID_MODEL then
id_model.clear();
}
}
}
data = udev_device_get_property_value(dev, "ID_SERIAL_SHORT");
if (data) {
id_serial_short = data;
}
data = udev_device_get_property_value(dev, "ID_SCSI_SERIAL");
if (data) {
id_scsi_serial = data;
}
data = udev_device_get_property_value(dev, "ID_SERIAL");
if (data) {
id_serial = data;
}
udev_device_unref(dev);
udev_unref(udev);
// ID_SERIAL is usually $vendor_$model_$serial, but not always
// ID_SERIAL_SHORT is mostly always just the serial
// ID_MODEL is sometimes $vendor_$model, but
// ID_VENDOR is sometimes $vendor and ID_MODEL just $model and ID_SCSI_SERIAL the real serial number, with ID_SERIAL and ID_SERIAL_SHORT gibberish (ick)
std::string device_id;
if (id_vendor.size() && id_model.size() && id_scsi_serial.size()) {
device_id = id_vendor + '_' + id_model + '_' + id_scsi_serial;
} else if (id_model.size() && id_serial_short.size()) {
device_id = id_model + '_' + id_serial_short;
} else if (id_serial.size()) {
device_id = id_serial;
if (device_id.substr(0, 4) == "MTFD") {
// Micron NVMes hide the vendor
device_id = "Micron_" + device_id;
}
}
if (device_id.size()) {
std::replace(device_id.begin(), device_id.end(), ' ', '_');
return device_id;
}
// either udev_device_get_property_value() failed, or succeeded but
// returned nothing; trying to read from files. note that the 'vendor'
// file rarely contains the actual vendor; it's usually 'ATA'.
std::string model, serial;
char buf[1024] = {0};
BlkDev blkdev(devname);
if (!blkdev.model(buf, sizeof(buf))) {
model = buf;
}
if (!blkdev.serial(buf, sizeof(buf))) {
serial = buf;
}
if (err) {
if (model.empty() && serial.empty()) {
*err = std::string("fallback method has no model nor serial");
return {};
} else if (model.empty()) {
*err = std::string("fallback method has serial '") + serial
+ "' but no model'";
return {};
} else if (serial.empty()) {
*err = std::string("fallback method has model '") + model
+ "' but no serial'";
return {};
}
}
device_id = model + "_" + serial;
std::replace(device_id.begin(), device_id.end(), ' ', '_');
return device_id;
}
static std::string get_device_vendor(const std::string& devname)
{
struct udev_device *dev;
static struct udev *udev;
const char *data;
udev = udev_new();
if (!udev) {
return {};
}
dev = udev_device_new_from_subsystem_sysname(udev, "block", devname.c_str());
if (!dev) {
udev_unref(udev);
return {};
}
std::string id_vendor, id_model;
data = udev_device_get_property_value(dev, "ID_VENDOR");
if (data) {
id_vendor = data;
}
data = udev_device_get_property_value(dev, "ID_MODEL");
if (data) {
id_model = data;
}
udev_device_unref(dev);
udev_unref(udev);
std::transform(id_vendor.begin(), id_vendor.end(), id_vendor.begin(),
::tolower);
std::transform(id_model.begin(), id_model.end(), id_model.begin(),
::tolower);
if (id_vendor.size()) {
return id_vendor;
}
if (id_model.size()) {
int pos = id_model.find(" ");
if (pos > 0) {
return id_model.substr(0, pos);
} else {
return id_model;
}
}
std::string vendor, model;
char buf[1024] = {0};
BlkDev blkdev(devname);
if (!blkdev.vendor(buf, sizeof(buf))) {
vendor = buf;
}
if (!blkdev.model(buf, sizeof(buf))) {
model = buf;
}
if (vendor.size()) {
return vendor;
}
if (model.size()) {
int pos = model.find(" ");
if (pos > 0) {
return model.substr(0, pos);
} else {
return model;
}
}
return {};
}
static int block_device_run_vendor_nvme(
const string& devname, const string& vendor, int timeout,
std::string *result)
{
string device = "/dev/" + devname;
SubProcessTimed nvmecli(
"sudo", SubProcess::CLOSE, SubProcess::PIPE, SubProcess::CLOSE,
timeout);
nvmecli.add_cmd_args(
"nvme",
vendor.c_str(),
"smart-log-add",
"--json",
device.c_str(),
NULL);
int ret = nvmecli.spawn();
if (ret != 0) {
*result = std::string("error spawning nvme command: ") + nvmecli.err();
return ret;
}
bufferlist output;
ret = output.read_fd(nvmecli.get_stdout(), 100*1024);
if (ret < 0) {
bufferlist err;
err.read_fd(nvmecli.get_stderr(), 100 * 1024);
*result = std::string("failed to execute nvme: ") + err.to_str();
} else {
ret = 0;
*result = output.to_str();
}
if (nvmecli.join() != 0) {
*result = std::string("nvme returned an error: ") + nvmecli.err();
return -EINVAL;
}
return ret;
}
std::string get_device_path(const std::string& devname,
std::string *err)
{
std::set<std::string> links;
int r = easy_readdir("/dev/disk/by-path", &links);
if (r < 0) {
*err = "unable to list contents of /dev/disk/by-path: "s +
cpp_strerror(r);
return {};
}
for (auto& i : links) {
char fn[PATH_MAX];
char target[PATH_MAX+1];
snprintf(fn, sizeof(fn), "/dev/disk/by-path/%s", i.c_str());
int r = readlink(fn, target, sizeof(target));
if (r < 0 || r >= (int)sizeof(target))
continue;
target[r] = 0;
if ((unsigned)r > devname.size() + 1 &&
strncmp(target + r - devname.size(), devname.c_str(), r) == 0 &&
target[r - devname.size() - 1] == '/') {
return fn;
}
}
*err = "no symlink to "s + devname + " in /dev/disk/by-path";
return {};
}
static int block_device_run_smartctl(const string& devname, int timeout,
std::string *result)
{
string device = "/dev/" + devname;
// when using --json, smartctl will report its errors in JSON format to stdout
SubProcessTimed smartctl(
"sudo", SubProcess::CLOSE, SubProcess::PIPE, SubProcess::CLOSE,
timeout);
smartctl.add_cmd_args(
"smartctl",
//"-a", // all SMART info
"-x", // all SMART and non-SMART info
"--json=o",
device.c_str(),
NULL);
int ret = smartctl.spawn();
if (ret != 0) {
*result = std::string("error spawning smartctl: ") + smartctl.err();
return ret;
}
bufferlist output;
ret = output.read_fd(smartctl.get_stdout(), 100*1024);
if (ret < 0) {
*result = std::string("failed read smartctl output: ") + cpp_strerror(-ret);
} else {
ret = 0;
*result = output.to_str();
}
int joinerr = smartctl.join();
// Bit 0: Command line did not parse.
// Bit 1: Device open failed, device did not return an IDENTIFY DEVICE structure, or device is in a low-power mode (see '-n' option above).
// Bit 2: Some SMART or other ATA command to the disk failed, or there was a checksum error in a SMART data structure (see '-b' option above).
// Bit 3: SMART status check returned "DISK FAILING".
// Bit 4: We found prefail Attributes <= threshold.
// Bit 5: SMART status check returned "DISK OK" but we found that some (usage or prefail) Attributes have been <= threshold at some time in the past.
// Bit 6: The device error log contains records of errors.
// Bit 7: The device self-test log contains records of errors. [ATA only] Failed self-tests outdated by a newer successful extended self-test are ignored.
if (joinerr & 3) {
*result = "smartctl returned an error ("s + stringify(joinerr) +
"): stderr:\n"s + smartctl.err() + "\nstdout:\n"s + *result;
return -EINVAL;
}
return ret;
}
static std::string escape_quotes(const std::string& s)
{
std::string r = s;
auto pos = r.find("\"");
while (pos != std::string::npos) {
r.replace(pos, 1, "\"");
pos = r.find("\"", pos + 1);
}
return r;
}
int block_device_get_metrics(const string& devname, int timeout,
json_spirit::mValue *result)
{
std::string s;
// smartctl
if (int r = block_device_run_smartctl(devname, timeout, &s);
r != 0) {
string orig = s;
s = "{\"error\": \"smartctl failed\", \"dev\": \"/dev/";
s += devname;
s += "\", \"smartctl_error_code\": " + stringify(r);
s += ", \"smartctl_output\": \"" + escape_quotes(orig);
s += + "\"}";
} else if (!json_spirit::read(s, *result)) {
string orig = s;
s = "{\"error\": \"smartctl returned invalid JSON\", \"dev\": \"/dev/";
s += devname;
s += "\",\"output\":\"";
s += escape_quotes(orig);
s += "\"}";
}
if (!json_spirit::read(s, *result)) {
return -EINVAL;
}
json_spirit::mObject& base = result->get_obj();
string vendor = get_device_vendor(devname);
if (vendor.size()) {
base["nvme_vendor"] = vendor;
s.clear();
json_spirit::mValue nvme_json;
if (int r = block_device_run_vendor_nvme(devname, vendor, timeout, &s);
r == 0) {
if (json_spirit::read(s, nvme_json) != 0) {
base["nvme_smart_health_information_add_log"] = nvme_json;
} else {
base["nvme_smart_health_information_add_log_error"] = "bad json output: "
+ s;
}
} else {
base["nvme_smart_health_information_add_log_error_code"] = r;
base["nvme_smart_health_information_add_log_error"] = s;
}
} else {
base["nvme_vendor"] = "unknown";
}
return 0;
}
#elif defined(__APPLE__)
#include <sys/disk.h>
const char *BlkDev::sysfsdir() const {
assert(false); // Should never be called on Apple
return "";
}
int BlkDev::dev(char *dev, size_t max) const
{
struct stat sb;
if (fstat(fd, &sb) < 0)
return -errno;
snprintf(dev, max, "%" PRIu64, (uint64_t)sb.st_rdev);
return 0;
}
int BlkDev::get_size(int64_t *psize) const
{
unsigned long blocksize = 0;
int ret = ::ioctl(fd, DKIOCGETBLOCKSIZE, &blocksize);
if (!ret) {
unsigned long nblocks;
ret = ::ioctl(fd, DKIOCGETBLOCKCOUNT, &nblocks);
if (!ret)
*psize = (int64_t)nblocks * blocksize;
}
if (ret < 0)
ret = -errno;
return ret;
}
int64_t BlkDev::get_int_property(const char* prop) const
{
return 0;
}
bool BlkDev::support_discard() const
{
return false;
}
int BlkDev::discard(int64_t offset, int64_t len) const
{
return -EOPNOTSUPP;
}
int BlkDev::get_optimal_io_size() const
{
return 0;
}
bool BlkDev::is_rotational() const
{
return false;
}
int BlkDev::get_numa_node(int *node) const
{
return -1;
}
int BlkDev::model(char *model, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::serial(char *serial, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::partition(char *partition, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::wholedisk(char *device, size_t max) const
{
}
void get_dm_parents(const std::string& dev, std::set<std::string> *ls)
{
}
void get_raw_devices(const std::string& in,
std::set<std::string> *ls)
{
}
std::string get_device_id(const std::string& devname,
std::string *err)
{
// FIXME: implement me
if (err) {
*err = "not implemented";
}
return std::string();
}
std::string get_device_path(const std::string& devname,
std::string *err)
{
// FIXME: implement me
if (err) {
*err = "not implemented";
}
return std::string();
}
#elif defined(__FreeBSD__)
const char *BlkDev::sysfsdir() const {
assert(false); // Should never be called on FreeBSD
return "";
}
int BlkDev::dev(char *dev, size_t max) const
{
struct stat sb;
if (fstat(fd, &sb) < 0)
return -errno;
snprintf(dev, max, "%" PRIu64, (uint64_t)sb.st_rdev);
return 0;
}
int BlkDev::get_size(int64_t *psize) const
{
int ret = ::ioctl(fd, DIOCGMEDIASIZE, psize);
if (ret < 0)
ret = -errno;
return ret;
}
int64_t BlkDev::get_int_property(const char* prop) const
{
return 0;
}
bool BlkDev::support_discard() const
{
#ifdef FREEBSD_WITH_TRIM
// there is no point to claim support of discard, but
// unable to do so.
struct diocgattr_arg arg;
strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
arg.len = sizeof(arg.value.i);
if (ioctl(fd, DIOCGATTR, &arg) == 0) {
return (arg.value.i != 0);
} else {
return false;
}
#endif
return false;
}
int BlkDev::discard(int64_t offset, int64_t len) const
{
return -EOPNOTSUPP;
}
int BlkDev::get_optimal_io_size() const
{
return 0;
}
bool BlkDev::is_rotational() const
{
#if __FreeBSD_version >= 1200049
struct diocgattr_arg arg;
strlcpy(arg.name, "GEOM::rotation_rate", sizeof(arg.name));
arg.len = sizeof(arg.value.u16);
int ioctl_ret = ioctl(fd, DIOCGATTR, &arg);
bool ret;
if (ioctl_ret < 0 || arg.value.u16 == DISK_RR_UNKNOWN)
// DISK_RR_UNKNOWN usually indicates an old drive, which is usually spinny
ret = true;
else if (arg.value.u16 == DISK_RR_NON_ROTATING)
ret = false;
else if (arg.value.u16 >= DISK_RR_MIN && arg.value.u16 <= DISK_RR_MAX)
ret = true;
else
ret = true; // Invalid value. Probably spinny?
return ret;
#else
return true; // When in doubt, it's probably spinny
#endif
}
int BlkDev::get_numa_node(int *node) const
{
int numa = get_int_property("device/device/numa_node");
if (numa < 0)
return -1;
*node = numa;
return 0;
}
int BlkDev::model(char *model, size_t max) const
{
struct diocgattr_arg arg;
strlcpy(arg.name, "GEOM::descr", sizeof(arg.name));
arg.len = sizeof(arg.value.str);
if (ioctl(fd, DIOCGATTR, &arg) < 0) {
return -errno;
}
// The GEOM description is of the form "vendor product" for SCSI disks
// and "ATA device_model" for ATA disks. Some vendors choose to put the
// vendor name in device_model, and some don't. Strip the first bit.
char *p = arg.value.str;
if (p == NULL || *p == '\0') {
*model = '\0';
} else {
(void) strsep(&p, " ");
snprintf(model, max, "%s", p);
}
return 0;
}
int BlkDev::serial(char *serial, size_t max) const
{
char ident[DISK_IDENT_SIZE];
if (ioctl(fd, DIOCGIDENT, ident) < 0)
return -errno;
snprintf(serial, max, "%s", ident);
return 0;
}
void get_dm_parents(const std::string& dev, std::set<std::string> *ls)
{
}
void get_raw_devices(const std::string& in,
std::set<std::string> *ls)
{
}
std::string get_device_id(const std::string& devname,
std::string *err)
{
// FIXME: implement me for freebsd
if (err) {
*err = "not implemented for FreeBSD";
}
return std::string();
}
std::string get_device_path(const std::string& devname,
std::string *err)
{
// FIXME: implement me for freebsd
if (err) {
*err = "not implemented for FreeBSD";
}
return std::string();
}
int block_device_run_smartctl(const char *device, int timeout,
std::string *result)
{
// FIXME: implement me for freebsd
return -EOPNOTSUPP;
}
int block_device_get_metrics(const string& devname, int timeout,
json_spirit::mValue *result)
{
// FIXME: implement me for freebsd
return -EOPNOTSUPP;
}
int block_device_run_nvme(const char *device, const char *vendor, int timeout,
std::string *result)
{
return -EOPNOTSUPP;
}
static int block_device_devname(int fd, char *devname, size_t max)
{
struct fiodgname_arg arg;
arg.buf = devname;
arg.len = max;
if (ioctl(fd, FIODGNAME, &arg) < 0)
return -errno;
return 0;
}
int BlkDev::partition(char *partition, size_t max) const
{
char devname[PATH_MAX];
if (block_device_devname(fd, devname, sizeof(devname)) < 0)
return -errno;
snprintf(partition, max, "/dev/%s", devname);
return 0;
}
int BlkDev::wholedisk(char *wd, size_t max) const
{
char devname[PATH_MAX];
if (block_device_devname(fd, devname, sizeof(devname)) < 0)
return -errno;
size_t first_digit = strcspn(devname, "0123456789");
// first_digit now indexes the first digit or null character of devname
size_t next_nondigit = strspn(&devname[first_digit], "0123456789");
next_nondigit += first_digit;
// next_nondigit now indexes the first alphabetic or null character after the
// unit number
strlcpy(wd, devname, next_nondigit + 1);
return 0;
}
#else
const char *BlkDev::sysfsdir() const {
assert(false); // Should never be called on non-Linux
return "";
}
int BlkDev::dev(char *dev, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::get_size(int64_t *psize) const
{
return -EOPNOTSUPP;
}
bool BlkDev::support_discard() const
{
return false;
}
int BlkDev::discard(int fd, int64_t offset, int64_t len) const
{
return -EOPNOTSUPP;
}
bool BlkDev::is_rotational(const char *devname) const
{
return false;
}
int BlkDev::model(char *model, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::serial(char *serial, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::partition(char *partition, size_t max) const
{
return -EOPNOTSUPP;
}
int BlkDev::wholedisk(char *wd, size_t max) const
{
return -EOPNOTSUPP;
}
void get_dm_parents(const std::string& dev, std::set<std::string> *ls)
{
}
void get_raw_devices(const std::string& in,
std::set<std::string> *ls)
{
}
std::string get_device_id(const std::string& devname,
std::string *err)
{
// not implemented
if (err) {
*err = "not implemented";
}
return std::string();
}
std::string get_device_path(const std::string& devname,
std::string *err)
{
// not implemented
if (err) {
*err = "not implemented";
}
return std::string();
}
int block_device_run_smartctl(const char *device, int timeout,
std::string *result)
{
return -EOPNOTSUPP;
}
int block_device_get_metrics(const string& devname, int timeout,
json_spirit::mValue *result)
{
return -EOPNOTSUPP;
}
int block_device_run_nvme(const char *device, const char *vendor, int timeout,
std::string *result)
{
return -EOPNOTSUPP;
}
#endif
void get_device_metadata(
const std::set<std::string>& devnames,
std::map<std::string,std::string> *pm,
std::map<std::string,std::string> *errs)
{
(*pm)["devices"] = stringify(devnames);
string &devids = (*pm)["device_ids"];
string &devpaths = (*pm)["device_paths"];
for (auto& dev : devnames) {
string err;
string id = get_device_id(dev, &err);
if (id.size()) {
if (!devids.empty()) {
devids += ",";
}
devids += dev + "=" + id;
} else {
(*errs)[dev] = " no unique device id for "s + dev + ": " + err;
}
string path = get_device_path(dev, &err);
if (path.size()) {
if (!devpaths.empty()) {
devpaths += ",";
}
devpaths += dev + "=" + path;
} else {
(*errs)[dev] + " no unique device path for "s + dev + ": " + err;
}
}
}
| 27,142 | 21.751886 | 157 | cc |
null | ceph-main/src/common/blkdev.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef __CEPH_COMMON_BLKDEV_H
#define __CEPH_COMMON_BLKDEV_H
#include <set>
#include <map>
#include <string>
#include "json_spirit/json_spirit_value.h"
extern int get_device_by_path(const char *path, char* partition, char* device, size_t max);
extern std::string _decode_model_enc(const std::string& in); // helper, exported only so we can unit test
// get $vendor_$model_$serial style device id
extern std::string get_device_id(const std::string& devname,
std::string *err=0);
// get /dev/disk/by-path/... style device id that is stable for a disk slot across reboots etc
extern std::string get_device_path(const std::string& devname,
std::string *err=0);
// populate daemon metadata map with device info
extern void get_device_metadata(
const std::set<std::string>& devnames,
std::map<std::string,std::string> *pm,
std::map<std::string,std::string> *errs);
extern void get_dm_parents(const std::string& dev, std::set<std::string> *ls);
extern int block_device_get_metrics(const std::string& devname, int timeout,
json_spirit::mValue *result);
// do everything to translate a device to the raw physical devices that
// back it, including partitions -> wholedisks and dm -> constituent devices.
extern void get_raw_devices(const std::string& in,
std::set<std::string> *ls);
class BlkDev {
public:
BlkDev(int fd);
BlkDev(const std::string& devname);
/* GoogleMock requires a virtual destructor */
virtual ~BlkDev() {}
// from an fd
int discard(int64_t offset, int64_t len) const;
int get_size(int64_t *psize) const;
int get_devid(dev_t *id) const;
int partition(char* partition, size_t max) const;
// from a device (e.g., "sdb")
bool support_discard() const;
int get_optimal_io_size() const;
bool is_rotational() const;
int get_numa_node(int *node) const;
int dev(char *dev, size_t max) const;
int vendor(char *vendor, size_t max) const;
int model(char *model, size_t max) const;
int serial(char *serial, size_t max) const;
/* virtual for testing purposes */
virtual const char *sysfsdir() const;
virtual int wholedisk(char* device, size_t max) const;
int wholedisk(std::string *s) const {
char out[PATH_MAX] = {0};
int r = wholedisk(out, sizeof(out));
if (r < 0) {
return r;
}
*s = out;
return r;
}
protected:
int64_t get_int_property(const char* prop) const;
int64_t get_string_property(const char* prop, char *val,
size_t maxlen) const;
private:
int fd = -1;
std::string devname;
};
#endif
| 2,628 | 29.929412 | 106 | h |
null | ceph-main/src/common/bloom_filter.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "common/bloom_filter.hpp"
#include <bit>
#include <numeric>
using ceph::bufferlist;
using ceph::bufferptr;
using ceph::Formatter;
double bloom_filter::density() const
{
// TODO: use transform_reduce() in GCC-9 and up
unsigned set = std::accumulate(
bit_table_.begin(),
bit_table_.begin() + table_size_,
0u, [](unsigned set, cell_type cell) {
return set + std::popcount(cell);
});
return (double)set / (table_size_ * sizeof(cell_type) * CHAR_BIT);
}
void bloom_filter::encode(bufferlist& bl) const
{
ENCODE_START(2, 2, bl);
encode((uint64_t)salt_count_, bl);
encode((uint64_t)insert_count_, bl);
encode((uint64_t)target_element_count_, bl);
encode((uint64_t)random_seed_, bl);
encode(bit_table_, bl);
ENCODE_FINISH(bl);
}
void bloom_filter::decode(bufferlist::const_iterator& p)
{
DECODE_START(2, p);
uint64_t v;
decode(v, p);
salt_count_ = v;
decode(v, p);
insert_count_ = v;
decode(v, p);
target_element_count_ = v;
decode(v, p);
random_seed_ = v;
salt_.clear();
generate_unique_salt();
decode(bit_table_, p);
table_size_ = bit_table_.size();
DECODE_FINISH(p);
}
void bloom_filter::dump(Formatter *f) const
{
f->dump_unsigned("salt_count", salt_count_);
f->dump_unsigned("table_size", table_size_);
f->dump_unsigned("insert_count", insert_count_);
f->dump_unsigned("target_element_count", target_element_count_);
f->dump_unsigned("random_seed", random_seed_);
f->open_array_section("salt_table");
for (std::vector<bloom_type>::const_iterator i = salt_.begin(); i != salt_.end(); ++i)
f->dump_unsigned("salt", *i);
f->close_section();
f->open_array_section("bit_table");
for (auto byte : bit_table_) {
f->dump_unsigned("byte", (unsigned)byte);
}
f->close_section();
}
void bloom_filter::generate_test_instances(std::list<bloom_filter*>& ls)
{
ls.push_back(new bloom_filter(10, .5, 1));
ls.push_back(new bloom_filter(10, .5, 1));
ls.back()->insert("foo");
ls.back()->insert("bar");
ls.push_back(new bloom_filter(50, .5, 1));
ls.back()->insert("foo");
ls.back()->insert("bar");
ls.back()->insert("baz");
ls.back()->insert("boof");
ls.back()->insert("boogggg");
}
void compressible_bloom_filter::encode(bufferlist& bl) const
{
ENCODE_START(2, 2, bl);
bloom_filter::encode(bl);
uint32_t s = size_list.size();
encode(s, bl);
for (std::vector<size_t>::const_iterator p = size_list.begin();
p != size_list.end(); ++p)
encode((uint64_t)*p, bl);
ENCODE_FINISH(bl);
}
void compressible_bloom_filter::decode(bufferlist::const_iterator& p)
{
DECODE_START(2, p);
bloom_filter::decode(p);
uint32_t s;
decode(s, p);
size_list.resize(s);
for (unsigned i = 0; i < s; i++) {
uint64_t v;
decode(v, p);
size_list[i] = v;
}
DECODE_FINISH(p);
}
void compressible_bloom_filter::dump(Formatter *f) const
{
bloom_filter::dump(f);
f->open_array_section("table_sizes");
for (std::vector<size_t>::const_iterator p = size_list.begin();
p != size_list.end(); ++p)
f->dump_unsigned("size", (uint64_t)*p);
f->close_section();
}
void compressible_bloom_filter::generate_test_instances(std::list<compressible_bloom_filter*>& ls)
{
ls.push_back(new compressible_bloom_filter(10, .5, 1));
ls.push_back(new compressible_bloom_filter(10, .5, 1));
ls.back()->insert("foo");
ls.back()->insert("bar");
ls.push_back(new compressible_bloom_filter(50, .5, 1));
ls.back()->insert("foo");
ls.back()->insert("bar");
ls.back()->insert("baz");
ls.back()->insert("boof");
ls.back()->compress(20);
ls.back()->insert("boogggg");
}
| 3,722 | 24.5 | 98 | cc |
null | ceph-main/src/common/bloom_filter.hpp | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
*******************************************************************
* *
* Open Bloom Filter *
* *
* Author: Arash Partow - 2000 *
* URL: http://www.partow.net/programming/hashfunctions/index.html *
* *
* Copyright notice: *
* Free use of the Open Bloom Filter Library is permitted under *
* the guidelines and in accordance with the most current version *
* of the Boost Software License, Version 1.0 *
* http://www.opensource.org/licenses/bsl1.0.html *
* *
*******************************************************************
*/
#ifndef COMMON_BLOOM_FILTER_HPP
#define COMMON_BLOOM_FILTER_HPP
#include <cmath>
#include "include/encoding.h"
#include "include/mempool.h"
static const unsigned char bit_mask[CHAR_BIT] = {
0x01, //00000001
0x02, //00000010
0x04, //00000100
0x08, //00001000
0x10, //00010000
0x20, //00100000
0x40, //01000000
0x80 //10000000
};
class bloom_filter
{
protected:
using bloom_type = unsigned int;
using cell_type = unsigned char;
using table_type = mempool::bloom_filter::vector<cell_type>;
std::vector<bloom_type> salt_; ///< vector of salts
table_type bit_table_; ///< bit map
std::size_t salt_count_; ///< number of salts
std::size_t table_size_; ///< bit table size in bytes
std::size_t insert_count_; ///< insertion count
std::size_t target_element_count_; ///< target number of unique insertions
std::size_t random_seed_; ///< random seed
public:
bloom_filter()
: salt_count_(0),
table_size_(0),
insert_count_(0),
target_element_count_(0),
random_seed_(0)
{}
bloom_filter(const std::size_t& predicted_inserted_element_count,
const double& false_positive_probability,
const std::size_t& random_seed)
: insert_count_(0),
target_element_count_(predicted_inserted_element_count),
random_seed_((random_seed) ? random_seed : 0xA5A5A5A5)
{
ceph_assert(false_positive_probability > 0.0);
std::tie(salt_count_, table_size_) =
find_optimal_parameters(predicted_inserted_element_count,
false_positive_probability);
init();
}
bloom_filter(const std::size_t& salt_count,
std::size_t table_size,
const std::size_t& random_seed,
std::size_t target_element_count)
: salt_count_(salt_count),
table_size_(table_size),
insert_count_(0),
target_element_count_(target_element_count),
random_seed_((random_seed) ? random_seed : 0xA5A5A5A5)
{
init();
}
void init() {
generate_unique_salt();
bit_table_.resize(table_size_, static_cast<unsigned char>(0x00));
}
bloom_filter(const bloom_filter& filter)
{
this->operator=(filter);
}
bloom_filter& operator = (const bloom_filter& filter)
{
if (this != &filter) {
salt_count_ = filter.salt_count_;
table_size_ = filter.table_size_;
insert_count_ = filter.insert_count_;
target_element_count_ = filter.target_element_count_;
random_seed_ = filter.random_seed_;
bit_table_ = filter.bit_table_;
salt_ = filter.salt_;
}
return *this;
}
virtual ~bloom_filter() = default;
inline bool operator!() const
{
return (0 == table_size_);
}
inline void clear()
{
std::fill(bit_table_.begin(), bit_table_.end(),
static_cast<unsigned char>(0x00));
insert_count_ = 0;
}
/**
* insert a u32 into the set
*
* NOTE: the internal hash is weak enough that consecutive inputs do
* not achieve the desired fpp. Well-mixed values should be used
* here (e.g., put rjhash(x) into the filter instead of just x).
*
* @param val integer value to insert
*/
inline void insert(uint32_t val) {
for (auto salt : salt_) {
auto [bit_index, bit] = compute_indices(hash_ap(val, salt));
bit_table_[bit_index >> 3] |= bit_mask[bit];
}
++insert_count_;
}
inline void insert(const unsigned char* key_begin, const std::size_t& length)
{
for (auto salt : salt_) {
auto [bit_index, bit] = compute_indices(hash_ap(key_begin, length, salt));
bit_table_[bit_index >> 3] |= bit_mask[bit];
}
++insert_count_;
}
inline void insert(const std::string& key)
{
insert(reinterpret_cast<const unsigned char*>(key.c_str()),key.size());
}
inline void insert(const char* data, const std::size_t& length)
{
insert(reinterpret_cast<const unsigned char*>(data),length);
}
template<typename InputIterator>
inline void insert(const InputIterator begin, const InputIterator end)
{
InputIterator itr = begin;
while (end != itr)
{
insert(*(itr++));
}
}
/**
* check if a u32 is contained by set
*
* NOTE: the internal hash is weak enough that consecutive inputs do
* not achieve the desired fpp. Well-mixed values should be used
* here (e.g., put rjhash(x) into the filter instead of just x).
*
* @param val integer value to query
* @returns true if value is (probably) in the set, false if it definitely is not
*/
inline virtual bool contains(uint32_t val) const
{
if (table_size_ == 0) {
return false;
}
for (auto salt : salt_) {
auto [bit_index, bit] = compute_indices(hash_ap(val, salt));
if ((bit_table_[bit_index >> 3] & bit_mask[bit]) != bit_mask[bit]) {
return false;
}
}
return true;
}
inline virtual bool contains(const unsigned char* key_begin, const std::size_t length) const
{
if (table_size_ == 0) {
return false;
}
for (auto salt : salt_) {
auto [bit_index, bit] = compute_indices(hash_ap(key_begin, length, salt));
if ((bit_table_[bit_index >> 3] & bit_mask[bit]) != bit_mask[bit]) {
return false;
}
}
return true;
}
inline bool contains(const std::string& key) const
{
return contains(reinterpret_cast<const unsigned char*>(key.c_str()),key.size());
}
inline bool contains(const char* data, const std::size_t& length) const
{
return contains(reinterpret_cast<const unsigned char*>(data),length);
}
template<typename InputIterator>
inline InputIterator contains_all(const InputIterator begin, const InputIterator end) const
{
InputIterator itr = begin;
while (end != itr)
{
if (!contains(*itr))
{
return itr;
}
++itr;
}
return end;
}
template<typename InputIterator>
inline InputIterator contains_none(const InputIterator begin, const InputIterator end) const
{
InputIterator itr = begin;
while (end != itr)
{
if (contains(*itr))
{
return itr;
}
++itr;
}
return end;
}
inline virtual std::size_t size() const
{
return table_size_ * CHAR_BIT;
}
inline std::size_t element_count() const
{
return insert_count_;
}
inline bool is_full() const
{
return insert_count_ >= target_element_count_;
}
/*
* density of bits set. inconvenient units, but:
* .3 = ~50% target insertions
* .5 = 100% target insertions, "perfectly full"
* .75 = 200% target insertions
* 1.0 = all bits set... infinite insertions
*/
double density() const;
virtual inline double approx_unique_element_count() const {
// this is not a very good estimate; a better solution should have
// some asymptotic behavior as density() approaches 1.0.
return (double)target_element_count_ * 2.0 * density();
}
inline double effective_fpp() const
{
/*
Note:
The effective false positive probability is calculated using the
designated table size and hash function count in conjunction with
the current number of inserted elements - not the user defined
predicated/expected number of inserted elements.
*/
return std::pow(1.0 - std::exp(-1.0 * salt_.size() * insert_count_ / size()), 1.0 * salt_.size());
}
inline const cell_type* table() const
{
return bit_table_.data();
}
protected:
virtual std::pair<size_t /* bit_index */,
size_t /* bit */>
compute_indices(const bloom_type& hash) const
{
size_t bit_index = hash % (table_size_ << 3);
size_t bit = bit_index & 7;
return {bit_index, bit};
}
void generate_unique_salt()
{
/*
Note:
A distinct hash function need not be implementation-wise
distinct. In the current implementation "seeding" a common
hash function with different values seems to be adequate.
*/
const unsigned int predef_salt_count = 128;
static const bloom_type predef_salt[predef_salt_count] = {
0xAAAAAAAA, 0x55555555, 0x33333333, 0xCCCCCCCC,
0x66666666, 0x99999999, 0xB5B5B5B5, 0x4B4B4B4B,
0xAA55AA55, 0x55335533, 0x33CC33CC, 0xCC66CC66,
0x66996699, 0x99B599B5, 0xB54BB54B, 0x4BAA4BAA,
0xAA33AA33, 0x55CC55CC, 0x33663366, 0xCC99CC99,
0x66B566B5, 0x994B994B, 0xB5AAB5AA, 0xAAAAAA33,
0x555555CC, 0x33333366, 0xCCCCCC99, 0x666666B5,
0x9999994B, 0xB5B5B5AA, 0xFFFFFFFF, 0xFFFF0000,
0xB823D5EB, 0xC1191CDF, 0xF623AEB3, 0xDB58499F,
0xC8D42E70, 0xB173F616, 0xA91A5967, 0xDA427D63,
0xB1E8A2EA, 0xF6C0D155, 0x4909FEA3, 0xA68CC6A7,
0xC395E782, 0xA26057EB, 0x0CD5DA28, 0x467C5492,
0xF15E6982, 0x61C6FAD3, 0x9615E352, 0x6E9E355A,
0x689B563E, 0x0C9831A8, 0x6753C18B, 0xA622689B,
0x8CA63C47, 0x42CC2884, 0x8E89919B, 0x6EDBD7D3,
0x15B6796C, 0x1D6FDFE4, 0x63FF9092, 0xE7401432,
0xEFFE9412, 0xAEAEDF79, 0x9F245A31, 0x83C136FC,
0xC3DA4A8C, 0xA5112C8C, 0x5271F491, 0x9A948DAB,
0xCEE59A8D, 0xB5F525AB, 0x59D13217, 0x24E7C331,
0x697C2103, 0x84B0A460, 0x86156DA9, 0xAEF2AC68,
0x23243DA5, 0x3F649643, 0x5FA495A8, 0x67710DF8,
0x9A6C499E, 0xDCFB0227, 0x46A43433, 0x1832B07A,
0xC46AFF3C, 0xB9C8FFF0, 0xC9500467, 0x34431BDF,
0xB652432B, 0xE367F12B, 0x427F4C1B, 0x224C006E,
0x2E7E5A89, 0x96F99AA5, 0x0BEB452A, 0x2FD87C39,
0x74B2E1FB, 0x222EFD24, 0xF357F60C, 0x440FCB1E,
0x8BBE030F, 0x6704DC29, 0x1144D12F, 0x948B1355,
0x6D8FD7E9, 0x1C11A014, 0xADD1592F, 0xFB3C712E,
0xFC77642F, 0xF9C4CE8C, 0x31312FB9, 0x08B0DD79,
0x318FA6E7, 0xC040D23D, 0xC0589AA7, 0x0CA5C075,
0xF874B172, 0x0CF914D5, 0x784D3280, 0x4E8CFEBC,
0xC569F575, 0xCDB2A091, 0x2CC016B4, 0x5C5F4421
};
if (salt_count_ <= predef_salt_count)
{
std::copy(predef_salt,
predef_salt + salt_count_,
std::back_inserter(salt_));
for (unsigned int i = 0; i < salt_.size(); ++i)
{
/*
Note:
This is done to integrate the user defined random seed,
so as to allow for the generation of unique bloom filter
instances.
*/
salt_[i] = salt_[i] * salt_[(i + 3) % salt_.size()] + random_seed_;
}
}
else
{
std::copy(predef_salt,predef_salt + predef_salt_count,
std::back_inserter(salt_));
srand(static_cast<unsigned int>(random_seed_));
while (salt_.size() < salt_count_)
{
bloom_type current_salt = static_cast<bloom_type>(rand()) * static_cast<bloom_type>(rand());
if (0 == current_salt)
continue;
if (salt_.end() == std::find(salt_.begin(), salt_.end(), current_salt))
{
salt_.push_back(current_salt);
}
}
}
}
static std::pair<std::size_t /* salt_count */,
std::size_t /* table_size */>
find_optimal_parameters(std::size_t target_insert_count,
double target_fpp)
{
/*
Note:
The following will attempt to find the number of hash functions
and minimum amount of storage bits required to construct a bloom
filter consistent with the user defined false positive probability
and estimated element insertion count.
*/
double min_m = std::numeric_limits<double>::infinity();
double min_k = 0.0;
double curr_m = 0.0;
double k = 1.0;
while (k < 1000.0)
{
double numerator = (- k * target_insert_count);
double denominator = std::log(1.0 - std::pow(target_fpp, 1.0 / k));
curr_m = numerator / denominator;
if (curr_m < min_m)
{
min_m = curr_m;
min_k = k;
}
k += 1.0;
}
size_t salt_count = static_cast<std::size_t>(min_k);
size_t t = static_cast<std::size_t>(min_m);
t += (((t & 7) != 0) ? (CHAR_BIT - (t & 7)) : 0);
size_t table_size = t >> 3;
return {salt_count, table_size};
}
inline bloom_type hash_ap(uint32_t val, bloom_type hash) const
{
hash ^= (hash << 7) ^ ((val & 0xff000000) >> 24) * (hash >> 3);
hash ^= (~((hash << 11) + (((val & 0xff0000) >> 16) ^ (hash >> 5))));
hash ^= (hash << 7) ^ ((val & 0xff00) >> 8) * (hash >> 3);
hash ^= (~((hash << 11) + (((val & 0xff)) ^ (hash >> 5))));
return hash;
}
inline bloom_type hash_ap(const unsigned char* begin, std::size_t remaining_length, bloom_type hash) const
{
const unsigned char* itr = begin;
while (remaining_length >= 4)
{
hash ^= (hash << 7) ^ (*itr++) * (hash >> 3);
hash ^= (~((hash << 11) + ((*itr++) ^ (hash >> 5))));
hash ^= (hash << 7) ^ (*itr++) * (hash >> 3);
hash ^= (~((hash << 11) + ((*itr++) ^ (hash >> 5))));
remaining_length -= 4;
}
while (remaining_length >= 2)
{
hash ^= (hash << 7) ^ (*itr++) * (hash >> 3);
hash ^= (~((hash << 11) + ((*itr++) ^ (hash >> 5))));
remaining_length -= 2;
}
if (remaining_length)
{
hash ^= (hash << 7) ^ (*itr) * (hash >> 3);
}
return hash;
}
public:
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<bloom_filter*>& ls);
};
WRITE_CLASS_ENCODER(bloom_filter)
class compressible_bloom_filter : public bloom_filter
{
public:
compressible_bloom_filter() : bloom_filter() {}
compressible_bloom_filter(const std::size_t& predicted_element_count,
const double& false_positive_probability,
const std::size_t& random_seed)
: bloom_filter(predicted_element_count, false_positive_probability, random_seed)
{
size_list.push_back(table_size_);
}
compressible_bloom_filter(const std::size_t& salt_count,
std::size_t table_size,
const std::size_t& random_seed,
std::size_t target_count)
: bloom_filter(salt_count, table_size, random_seed, target_count)
{
size_list.push_back(table_size_);
}
inline std::size_t size() const override
{
return size_list.back() * CHAR_BIT;
}
inline bool compress(const double& target_ratio)
{
if (bit_table_.empty())
return false;
if ((0.0 >= target_ratio) || (target_ratio >= 1.0))
{
return false;
}
std::size_t original_table_size = size_list.back();
std::size_t new_table_size = static_cast<std::size_t>(size_list.back() * target_ratio);
if ((!new_table_size) || (new_table_size >= original_table_size))
{
return false;
}
table_type tmp(new_table_size);
std::copy(bit_table_.begin(), bit_table_.begin() + new_table_size, tmp.begin());
auto itr = bit_table_.begin() + new_table_size;
auto end = bit_table_.begin() + original_table_size;
auto itr_tmp = tmp.begin();
auto itr_end = tmp.begin() + new_table_size;
while (end != itr) {
*(itr_tmp++) |= (*itr++);
if (itr_tmp == itr_end) {
itr_tmp = tmp.begin();
}
}
std::swap(bit_table_, tmp);
size_list.push_back(new_table_size);
table_size_ = new_table_size;
return true;
}
inline double approx_unique_element_count() const override {
// this is not a very good estimate; a better solution should have
// some asymptotic behavior as density() approaches 1.0.
//
// the compress() correction is also bad; it tends to under-estimate.
return (double)target_element_count_ * 2.0 * density() * (double)size_list.back() / (double)size_list.front();
}
private:
std::pair<size_t /* bit_index */,
size_t /* bit */>
compute_indices(const bloom_type& hash) const final
{
size_t bit_index = hash;
for (auto size : size_list) {
bit_index %= size << 3;
}
size_t bit = bit_index & 7;
return {bit_index, bit};
}
std::vector<std::size_t> size_list;
public:
void encode(ceph::bufferlist& bl) const;
void decode(ceph::bufferlist::const_iterator& bl);
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<compressible_bloom_filter*>& ls);
};
WRITE_CLASS_ENCODER(compressible_bloom_filter)
#endif
/*
Note 1:
If it can be guaranteed that CHAR_BIT will be of the form 2^n then
the following optimization can be used:
bit_table_[bit_index >> n] |= bit_mask[bit_index & (CHAR_BIT - 1)];
Note 2:
For performance reasons where possible when allocating memory it should
be aligned (aligned_alloc) according to the architecture being used.
*/
| 17,565 | 28.976109 | 114 | hpp |
null | ceph-main/src/common/bounded_key_counter.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
*
* Author: Casey Bodley <[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 BOUNDED_KEY_COUNTER_H
#define BOUNDED_KEY_COUNTER_H
#include <algorithm>
#include <map>
#include <tuple>
#include <vector>
#include "include/ceph_assert.h"
/**
* BoundedKeyCounter
*
* A data structure that counts the number of times a given key is inserted,
* and can return the keys with the highest counters. The number of unique keys
* is bounded by the given constructor argument, meaning that new keys will be
* rejected if they would exceed this bound.
*
* It is optimized for use where insertion is frequent, but sorted listings are
* both infrequent and tend to request a small subset of the available keys.
*/
template <typename Key, typename Count>
class BoundedKeyCounter {
/// map type to associate keys with their counter values
using map_type = std::map<Key, Count>;
using value_type = typename map_type::value_type;
/// view type used for sorting key-value pairs by their counter value
using view_type = std::vector<const value_type*>;
/// maximum number of counters to store at once
const size_t bound;
/// map of counters, with a maximum size given by 'bound'
map_type counters;
/// storage for sorted key-value pairs
view_type sorted;
/// remembers how much of the range is actually sorted
typename view_type::iterator sorted_position;
/// invalidate view of sorted entries
void invalidate_sorted()
{
sorted_position = sorted.begin();
sorted.clear();
}
/// value_type comparison function for sorting in descending order
static bool value_greater(const value_type *lhs, const value_type *rhs)
{
return lhs->second > rhs->second;
}
/// map iterator that adapts value_type to value_type*
struct const_pointer_iterator : public map_type::const_iterator {
const_pointer_iterator(typename map_type::const_iterator i)
: map_type::const_iterator(i) {}
using value_type = typename map_type::const_iterator::value_type*;
using reference = const typename map_type::const_iterator::value_type*;
reference operator*() const {
return &map_type::const_iterator::operator*();
}
};
protected:
/// return the number of sorted entries. marked protected for unit testing
size_t get_num_sorted() const
{
using const_iterator = typename view_type::const_iterator;
return std::distance<const_iterator>(sorted.begin(), sorted_position);
}
public:
BoundedKeyCounter(size_t bound)
: bound(bound)
{
sorted.reserve(bound);
sorted_position = sorted.begin();
}
/// return the number of keys stored
size_t size() const noexcept { return counters.size(); }
/// return the maximum number of keys
size_t capacity() const noexcept { return bound; }
/// increment a counter for the given key and return its value. if the key was
/// not present, insert it. if the map is full, return 0
Count insert(const Key& key, Count n = 1)
{
typename map_type::iterator i;
if (counters.size() < bound) {
// insert new entries at count=0
bool inserted;
std::tie(i, inserted) = counters.emplace(key, 0);
if (inserted) {
sorted.push_back(&*i);
}
} else {
// when full, refuse to insert new entries
i = counters.find(key);
if (i == counters.end()) {
return 0;
}
}
i->second += n; // add to the counter
// update sorted position if necessary. use a binary search for the last
// element in the sorted range that's greater than this counter
sorted_position = std::lower_bound(sorted.begin(), sorted_position,
&*i, &value_greater);
return i->second;
}
/// remove the given key from the map of counters
void erase(const Key& key)
{
auto i = counters.find(key);
if (i == counters.end()) {
return;
}
// removing the sorted entry would require linear search; invalidate instead
invalidate_sorted();
counters.erase(i);
}
/// query the highest N key-value pairs sorted by counter value, passing each
/// in order to the given callback with arguments (Key, Count)
template <typename Callback>
void get_highest(size_t count, Callback&& cb)
{
if (sorted.empty()) {
// initialize the vector with pointers to all key-value pairs
sorted.assign(const_pointer_iterator{counters.cbegin()},
const_pointer_iterator{counters.cend()});
// entire range is unsorted
ceph_assert(sorted_position == sorted.begin());
}
const size_t sorted_count = get_num_sorted();
if (sorted_count < count) {
// move sorted_position to cover the requested number of entries
sorted_position = sorted.begin() + std::min(count, sorted.size());
// sort all entries in descending order up to the given position
std::partial_sort(sorted.begin(), sorted_position, sorted.end(),
&value_greater);
}
// return the requested range via callback
for (const auto& pair : sorted) {
if (count-- == 0) {
return;
}
cb(pair->first, pair->second);
}
}
/// remove all keys and counters and invalidate the sorted range
void clear()
{
invalidate_sorted();
counters.clear();
}
};
#endif // BOUNDED_KEY_COUNTER_H
| 5,718 | 28.786458 | 80 | h |
null | ceph-main/src/common/buffer.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 <atomic>
#include <cstring>
#include <errno.h>
#include <limits.h>
#include <sys/uio.h>
#include "include/ceph_assert.h"
#include "include/types.h"
#include "include/buffer_raw.h"
#include "include/compat.h"
#include "include/mempool.h"
#include "armor.h"
#include "common/environment.h"
#include "common/errno.h"
#include "common/error_code.h"
#include "common/safe_io.h"
#include "common/strtol.h"
#include "common/likely.h"
#include "common/valgrind.h"
#include "common/deleter.h"
#include "common/error_code.h"
#include "include/intarith.h"
#include "include/spinlock.h"
#include "include/scope_guard.h"
using std::cerr;
using std::make_pair;
using std::pair;
using std::string;
using namespace ceph;
#define CEPH_BUFFER_ALLOC_UNIT 4096u
#define CEPH_BUFFER_APPEND_SIZE (CEPH_BUFFER_ALLOC_UNIT - sizeof(raw_combined))
// 256K is the maximum "small" object size in tcmalloc above which allocations come from
// the central heap. For now let's keep this below that threshold.
#define CEPH_BUFFER_ALLOC_UNIT_MAX std::size_t { 256*1024 }
#ifdef BUFFER_DEBUG
static ceph::spinlock debug_lock;
# define bdout { std::lock_guard<ceph::spinlock> lg(debug_lock); std::cout
# define bendl std::endl; }
#else
# define bdout if (0) { std::cout
# define bendl std::endl; }
#endif
static ceph::atomic<unsigned> buffer_cached_crc { 0 };
static ceph::atomic<unsigned> buffer_cached_crc_adjusted { 0 };
static ceph::atomic<unsigned> buffer_missed_crc { 0 };
static bool buffer_track_crc = get_env_bool("CEPH_BUFFER_TRACK");
void buffer::track_cached_crc(bool b) {
buffer_track_crc = b;
}
int buffer::get_cached_crc() {
return buffer_cached_crc;
}
int buffer::get_cached_crc_adjusted() {
return buffer_cached_crc_adjusted;
}
int buffer::get_missed_crc() {
return buffer_missed_crc;
}
/*
* raw_combined is always placed within a single allocation along
* with the data buffer. the data goes at the beginning, and
* raw_combined at the end.
*/
class buffer::raw_combined : public buffer::raw {
public:
raw_combined(char *dataptr, unsigned l, int mempool)
: raw(dataptr, l, mempool) {
}
static ceph::unique_leakable_ptr<buffer::raw>
create(unsigned len,
unsigned align,
int mempool = mempool::mempool_buffer_anon)
{
// posix_memalign() requires a multiple of sizeof(void *)
align = std::max<unsigned>(align, sizeof(void *));
size_t rawlen = round_up_to(sizeof(buffer::raw_combined),
alignof(buffer::raw_combined));
size_t datalen = round_up_to(len, alignof(buffer::raw_combined));
#ifdef DARWIN
char *ptr = (char *) valloc(rawlen + datalen);
#else
char *ptr = 0;
int r = ::posix_memalign((void**)(void*)&ptr, align, rawlen + datalen);
if (r)
throw bad_alloc();
#endif /* DARWIN */
if (!ptr)
throw bad_alloc();
// actual data first, since it has presumably larger alignment restriction
// then put the raw_combined at the end
return ceph::unique_leakable_ptr<buffer::raw>(
new (ptr + datalen) raw_combined(ptr, len, mempool));
}
static void operator delete(void *ptr) {
raw_combined *raw = (raw_combined *)ptr;
aligned_free((void *)raw->data);
}
};
class buffer::raw_malloc : public buffer::raw {
public:
MEMPOOL_CLASS_HELPERS();
explicit raw_malloc(unsigned l) : raw(l) {
if (len) {
data = (char *)malloc(len);
if (!data)
throw bad_alloc();
} else {
data = 0;
}
bdout << "raw_malloc " << this << " alloc " << (void *)data << " " << l << bendl;
}
raw_malloc(unsigned l, char *b) : raw(b, l) {
bdout << "raw_malloc " << this << " alloc " << (void *)data << " " << l << bendl;
}
~raw_malloc() override {
free(data);
bdout << "raw_malloc " << this << " free " << (void *)data << " " << bendl;
}
};
#ifndef __CYGWIN__
class buffer::raw_posix_aligned : public buffer::raw {
public:
MEMPOOL_CLASS_HELPERS();
raw_posix_aligned(unsigned l, unsigned align) : raw(l) {
// posix_memalign() requires a multiple of sizeof(void *)
align = std::max<unsigned>(align, sizeof(void *));
#ifdef DARWIN
data = (char *) valloc(len);
#else
int r = ::posix_memalign((void**)(void*)&data, align, len);
if (r)
throw bad_alloc();
#endif /* DARWIN */
if (!data)
throw bad_alloc();
bdout << "raw_posix_aligned " << this << " alloc " << (void *)data
<< " l=" << l << ", align=" << align << bendl;
}
~raw_posix_aligned() override {
aligned_free(data);
bdout << "raw_posix_aligned " << this << " free " << (void *)data << bendl;
}
};
#endif
#ifdef __CYGWIN__
class buffer::raw_hack_aligned : public buffer::raw {
char *realdata;
public:
raw_hack_aligned(unsigned l, unsigned align) : raw(l) {
realdata = new char[len+align-1];
unsigned off = ((uintptr_t)realdata) & (align-1);
if (off)
data = realdata + align - off;
else
data = realdata;
//cout << "hack aligned " << (unsigned)data
//<< " in raw " << (unsigned)realdata
//<< " off " << off << std::endl;
ceph_assert(((uintptr_t)data & (align-1)) == 0);
}
~raw_hack_aligned() {
delete[] realdata;
}
};
#endif
/*
* primitive buffer types
*/
class buffer::raw_claimed_char : public buffer::raw {
public:
MEMPOOL_CLASS_HELPERS();
explicit raw_claimed_char(unsigned l, char *b) : raw(b, l) {
bdout << "raw_claimed_char " << this << " alloc " << (void *)data
<< " " << l << bendl;
}
~raw_claimed_char() override {
bdout << "raw_claimed_char " << this << " free " << (void *)data
<< bendl;
}
};
class buffer::raw_static : public buffer::raw {
public:
MEMPOOL_CLASS_HELPERS();
raw_static(const char *d, unsigned l) : raw((char*)d, l) { }
~raw_static() override {}
};
class buffer::raw_claim_buffer : public buffer::raw {
deleter del;
public:
raw_claim_buffer(const char *b, unsigned l, deleter d)
: raw((char*)b, l), del(std::move(d)) { }
~raw_claim_buffer() override {}
};
ceph::unique_leakable_ptr<buffer::raw> buffer::copy(const char *c, unsigned len) {
auto r = buffer::create_aligned(len, sizeof(size_t));
memcpy(r->get_data(), c, len);
return r;
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create(unsigned len) {
return buffer::create_aligned(len, sizeof(size_t));
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create(unsigned len, char c) {
auto ret = buffer::create_aligned(len, sizeof(size_t));
memset(ret->get_data(), c, len);
return ret;
}
ceph::unique_leakable_ptr<buffer::raw>
buffer::create_in_mempool(unsigned len, int mempool) {
return buffer::create_aligned_in_mempool(len, sizeof(size_t), mempool);
}
ceph::unique_leakable_ptr<buffer::raw>
buffer::claim_char(unsigned len, char *buf) {
return ceph::unique_leakable_ptr<buffer::raw>(
new raw_claimed_char(len, buf));
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create_malloc(unsigned len) {
return ceph::unique_leakable_ptr<buffer::raw>(new raw_malloc(len));
}
ceph::unique_leakable_ptr<buffer::raw>
buffer::claim_malloc(unsigned len, char *buf) {
return ceph::unique_leakable_ptr<buffer::raw>(new raw_malloc(len, buf));
}
ceph::unique_leakable_ptr<buffer::raw>
buffer::create_static(unsigned len, char *buf) {
return ceph::unique_leakable_ptr<buffer::raw>(new raw_static(buf, len));
}
ceph::unique_leakable_ptr<buffer::raw>
buffer::claim_buffer(unsigned len, char *buf, deleter del) {
return ceph::unique_leakable_ptr<buffer::raw>(
new raw_claim_buffer(buf, len, std::move(del)));
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create_aligned_in_mempool(
unsigned len, unsigned align, int mempool)
{
// If alignment is a page multiple, use a separate buffer::raw to
// avoid fragmenting the heap.
//
// Somewhat unexpectedly, I see consistently better performance
// from raw_combined than from raw even when the allocation size is
// a page multiple (but alignment is not).
//
// I also see better performance from a separate buffer::raw once the
// size passes 8KB.
if ((align & ~CEPH_PAGE_MASK) == 0 ||
len >= CEPH_PAGE_SIZE * 2) {
#ifndef __CYGWIN__
return ceph::unique_leakable_ptr<buffer::raw>(new raw_posix_aligned(len, align));
#else
return ceph::unique_leakable_ptr<buffer::raw>(new raw_hack_aligned(len, align));
#endif
}
return raw_combined::create(len, align, mempool);
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create_aligned(
unsigned len, unsigned align) {
return create_aligned_in_mempool(len, align,
mempool::mempool_buffer_anon);
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create_page_aligned(unsigned len) {
return create_aligned(len, CEPH_PAGE_SIZE);
}
ceph::unique_leakable_ptr<buffer::raw> buffer::create_small_page_aligned(unsigned len) {
if (len < CEPH_PAGE_SIZE) {
return create_aligned(len, CEPH_BUFFER_ALLOC_UNIT);
} else {
return create_aligned(len, CEPH_PAGE_SIZE);
}
}
buffer::ptr::ptr(ceph::unique_leakable_ptr<raw> r)
: _raw(r.release()),
_off(0),
_len(_raw->get_len())
{
_raw->nref.store(1, std::memory_order_release);
bdout << "ptr " << this << " get " << _raw << bendl;
}
buffer::ptr::ptr(unsigned l) : _off(0), _len(l)
{
_raw = buffer::create(l).release();
_raw->nref.store(1, std::memory_order_release);
bdout << "ptr " << this << " get " << _raw << bendl;
}
buffer::ptr::ptr(const char *d, unsigned l) : _off(0), _len(l) // ditto.
{
_raw = buffer::copy(d, l).release();
_raw->nref.store(1, std::memory_order_release);
bdout << "ptr " << this << " get " << _raw << bendl;
}
buffer::ptr::ptr(const ptr& p) : _raw(p._raw), _off(p._off), _len(p._len)
{
if (_raw) {
_raw->nref++;
bdout << "ptr " << this << " get " << _raw << bendl;
}
}
buffer::ptr::ptr(ptr&& p) noexcept : _raw(p._raw), _off(p._off), _len(p._len)
{
p._raw = nullptr;
p._off = p._len = 0;
}
buffer::ptr::ptr(const ptr& p, unsigned o, unsigned l)
: _raw(p._raw), _off(p._off + o), _len(l)
{
ceph_assert(o+l <= p._len);
ceph_assert(_raw);
_raw->nref++;
bdout << "ptr " << this << " get " << _raw << bendl;
}
buffer::ptr::ptr(const ptr& p, ceph::unique_leakable_ptr<raw> r)
: _raw(r.release()),
_off(p._off),
_len(p._len)
{
_raw->nref.store(1, std::memory_order_release);
bdout << "ptr " << this << " get " << _raw << bendl;
}
buffer::ptr& buffer::ptr::operator= (const ptr& p)
{
if (p._raw) {
p._raw->nref++;
bdout << "ptr " << this << " get " << _raw << bendl;
}
buffer::raw *raw = p._raw;
release();
if (raw) {
_raw = raw;
_off = p._off;
_len = p._len;
} else {
_off = _len = 0;
}
return *this;
}
buffer::ptr& buffer::ptr::operator= (ptr&& p) noexcept
{
release();
buffer::raw *raw = p._raw;
if (raw) {
_raw = raw;
_off = p._off;
_len = p._len;
p._raw = nullptr;
p._off = p._len = 0;
} else {
_off = _len = 0;
}
return *this;
}
void buffer::ptr::swap(ptr& other) noexcept
{
raw *r = _raw;
unsigned o = _off;
unsigned l = _len;
_raw = other._raw;
_off = other._off;
_len = other._len;
other._raw = r;
other._off = o;
other._len = l;
}
void buffer::ptr::release()
{
// BE CAREFUL: this is called also for hypercombined ptr_node. After
// freeing underlying raw, `*this` can become inaccessible as well!
//
// cache the pointer to avoid unncecessary reloads and repeated
// checks.
if (auto* const cached_raw = std::exchange(_raw, nullptr);
cached_raw) {
bdout << "ptr " << this << " release " << cached_raw << bendl;
// optimize the common case where a particular `buffer::raw` has
// only a single reference. Altogether with initializing `nref` of
// freshly fabricated one with `1` through the std::atomic's ctor
// (which doesn't impose a memory barrier on the strongly-ordered
// x86), this allows to avoid all atomical operations in such case.
const bool last_one = \
(1 == cached_raw->nref.load(std::memory_order_acquire));
if (likely(last_one) || --cached_raw->nref == 0) {
bdout << "deleting raw " << static_cast<void*>(cached_raw)
<< " len " << cached_raw->get_len() << bendl;
ANNOTATE_HAPPENS_AFTER(&cached_raw->nref);
ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&cached_raw->nref);
delete cached_raw; // dealloc old (if any)
} else {
ANNOTATE_HAPPENS_BEFORE(&cached_raw->nref);
}
}
}
int buffer::ptr::get_mempool() const {
if (_raw) {
return _raw->mempool;
}
return mempool::mempool_buffer_anon;
}
void buffer::ptr::reassign_to_mempool(int pool) {
if (_raw) {
_raw->reassign_to_mempool(pool);
}
}
void buffer::ptr::try_assign_to_mempool(int pool) {
if (_raw) {
_raw->try_assign_to_mempool(pool);
}
}
const char *buffer::ptr::c_str() const {
ceph_assert(_raw);
return _raw->get_data() + _off;
}
char *buffer::ptr::c_str() {
ceph_assert(_raw);
return _raw->get_data() + _off;
}
const char *buffer::ptr::end_c_str() const {
ceph_assert(_raw);
return _raw->get_data() + _off + _len;
}
char *buffer::ptr::end_c_str() {
ceph_assert(_raw);
return _raw->get_data() + _off + _len;
}
unsigned buffer::ptr::unused_tail_length() const
{
return _raw ? _raw->get_len() - (_off + _len) : 0;
}
const char& buffer::ptr::operator[](unsigned n) const
{
ceph_assert(_raw);
ceph_assert(n < _len);
return _raw->get_data()[_off + n];
}
char& buffer::ptr::operator[](unsigned n)
{
ceph_assert(_raw);
ceph_assert(n < _len);
return _raw->get_data()[_off + n];
}
const char *buffer::ptr::raw_c_str() const { ceph_assert(_raw); return _raw->get_data(); }
unsigned buffer::ptr::raw_length() const { ceph_assert(_raw); return _raw->get_len(); }
int buffer::ptr::raw_nref() const { ceph_assert(_raw); return _raw->nref; }
void buffer::ptr::copy_out(unsigned o, unsigned l, char *dest) const {
ceph_assert(_raw);
if (o+l > _len)
throw end_of_buffer();
char* src = _raw->get_data() + _off + o;
maybe_inline_memcpy(dest, src, l, 8);
}
unsigned buffer::ptr::wasted() const
{
return _raw->get_len() - _len;
}
int buffer::ptr::cmp(const ptr& o) const
{
int l = _len < o._len ? _len : o._len;
if (l) {
int r = memcmp(c_str(), o.c_str(), l);
if (r)
return r;
}
if (_len < o._len)
return -1;
if (_len > o._len)
return 1;
return 0;
}
bool buffer::ptr::is_zero() const
{
return mem_is_zero(c_str(), _len);
}
unsigned buffer::ptr::append(char c)
{
ceph_assert(_raw);
ceph_assert(1 <= unused_tail_length());
char* ptr = _raw->get_data() + _off + _len;
*ptr = c;
_len++;
return _len + _off;
}
unsigned buffer::ptr::append(const char *p, unsigned l)
{
ceph_assert(_raw);
ceph_assert(l <= unused_tail_length());
char* c = _raw->get_data() + _off + _len;
maybe_inline_memcpy(c, p, l, 32);
_len += l;
return _len + _off;
}
unsigned buffer::ptr::append_zeros(unsigned l)
{
ceph_assert(_raw);
ceph_assert(l <= unused_tail_length());
char* c = _raw->get_data() + _off + _len;
// FIPS zeroization audit 20191115: this memset is not security related.
memset(c, 0, l);
_len += l;
return _len + _off;
}
void buffer::ptr::copy_in(unsigned o, unsigned l, const char *src, bool crc_reset)
{
ceph_assert(_raw);
ceph_assert(o <= _len);
ceph_assert(o+l <= _len);
char* dest = _raw->get_data() + _off + o;
if (crc_reset)
_raw->invalidate_crc();
maybe_inline_memcpy(dest, src, l, 64);
}
void buffer::ptr::zero(bool crc_reset)
{
if (crc_reset)
_raw->invalidate_crc();
// FIPS zeroization audit 20191115: this memset is not security related.
memset(c_str(), 0, _len);
}
void buffer::ptr::zero(unsigned o, unsigned l, bool crc_reset)
{
ceph_assert(o+l <= _len);
if (crc_reset)
_raw->invalidate_crc();
// FIPS zeroization audit 20191115: this memset is not security related.
memset(c_str()+o, 0, l);
}
template<bool B>
buffer::ptr::iterator_impl<B>& buffer::ptr::iterator_impl<B>::operator +=(size_t len) {
pos += len;
if (pos > end_ptr)
throw end_of_buffer();
return *this;
}
template buffer::ptr::iterator_impl<false>&
buffer::ptr::iterator_impl<false>::operator +=(size_t len);
template buffer::ptr::iterator_impl<true>&
buffer::ptr::iterator_impl<true>::operator +=(size_t len);
// -- buffer::list::iterator --
/*
buffer::list::iterator operator=(const buffer::list::iterator& other)
{
if (this != &other) {
bl = other.bl;
ls = other.ls;
off = other.off;
p = other.p;
p_off = other.p_off;
}
return *this;
}*/
template<bool is_const>
buffer::list::iterator_impl<is_const>::iterator_impl(bl_t *l, unsigned o)
: bl(l), ls(&bl->_buffers), p(ls->begin()), off(0), p_off(0)
{
*this += o;
}
template<bool is_const>
buffer::list::iterator_impl<is_const>::iterator_impl(const buffer::list::iterator& i)
: iterator_impl<is_const>(i.bl, i.off, i.p, i.p_off) {}
template<bool is_const>
auto buffer::list::iterator_impl<is_const>::operator +=(unsigned o)
-> iterator_impl&
{
//cout << this << " advance " << o << " from " << off
// << " (p_off " << p_off << " in " << p->length() << ")"
// << std::endl;
p_off +=o;
while (p != ls->end()) {
if (p_off >= p->length()) {
// skip this buffer
p_off -= p->length();
p++;
} else {
// somewhere in this buffer!
break;
}
}
if (p == ls->end() && p_off) {
throw end_of_buffer();
}
off += o;
return *this;
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::seek(unsigned o)
{
p = ls->begin();
off = p_off = 0;
*this += o;
}
template<bool is_const>
char buffer::list::iterator_impl<is_const>::operator*() const
{
if (p == ls->end())
throw end_of_buffer();
return (*p)[p_off];
}
template<bool is_const>
buffer::list::iterator_impl<is_const>&
buffer::list::iterator_impl<is_const>::operator++()
{
if (p == ls->end())
throw end_of_buffer();
*this += 1;
return *this;
}
template<bool is_const>
buffer::ptr buffer::list::iterator_impl<is_const>::get_current_ptr() const
{
if (p == ls->end())
throw end_of_buffer();
return ptr(*p, p_off, p->length() - p_off);
}
template<bool is_const>
bool buffer::list::iterator_impl<is_const>::is_pointing_same_raw(
const ptr& other) const
{
if (p == ls->end())
throw end_of_buffer();
return p->_raw == other._raw;
}
// copy data out.
// note that these all _append_ to dest!
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy(unsigned len, char *dest)
{
if (p == ls->end()) seek(off);
while (len > 0) {
if (p == ls->end())
throw end_of_buffer();
unsigned howmuch = p->length() - p_off;
if (len < howmuch) howmuch = len;
p->copy_out(p_off, howmuch, dest);
dest += howmuch;
len -= howmuch;
*this += howmuch;
}
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy(unsigned len, ptr &dest)
{
copy_deep(len, dest);
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy_deep(unsigned len, ptr &dest)
{
if (!len) {
return;
}
if (p == ls->end())
throw end_of_buffer();
dest = create(len);
copy(len, dest.c_str());
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy_shallow(unsigned len,
ptr &dest)
{
if (!len) {
return;
}
if (p == ls->end())
throw end_of_buffer();
unsigned howmuch = p->length() - p_off;
if (howmuch < len) {
dest = create(len);
copy(len, dest.c_str());
} else {
dest = ptr(*p, p_off, len);
*this += len;
}
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy(unsigned len, list &dest)
{
if (p == ls->end())
seek(off);
while (len > 0) {
if (p == ls->end())
throw end_of_buffer();
unsigned howmuch = p->length() - p_off;
if (len < howmuch)
howmuch = len;
dest.append(*p, p_off, howmuch);
len -= howmuch;
*this += howmuch;
}
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy(unsigned len, std::string &dest)
{
if (p == ls->end())
seek(off);
while (len > 0) {
if (p == ls->end())
throw end_of_buffer();
unsigned howmuch = p->length() - p_off;
const char *c_str = p->c_str();
if (len < howmuch)
howmuch = len;
dest.append(c_str + p_off, howmuch);
len -= howmuch;
*this += howmuch;
}
}
template<bool is_const>
void buffer::list::iterator_impl<is_const>::copy_all(list &dest)
{
if (p == ls->end())
seek(off);
while (1) {
if (p == ls->end())
return;
unsigned howmuch = p->length() - p_off;
const char *c_str = p->c_str();
dest.append(c_str + p_off, howmuch);
*this += howmuch;
}
}
template<bool is_const>
size_t buffer::list::iterator_impl<is_const>::get_ptr_and_advance(
size_t want, const char **data)
{
if (p == ls->end()) {
seek(off);
if (p == ls->end()) {
return 0;
}
}
*data = p->c_str() + p_off;
size_t l = std::min<size_t>(p->length() - p_off, want);
p_off += l;
if (p_off == p->length()) {
++p;
p_off = 0;
}
off += l;
return l;
}
template<bool is_const>
uint32_t buffer::list::iterator_impl<is_const>::crc32c(
size_t length, uint32_t crc)
{
length = std::min<size_t>(length, get_remaining());
while (length > 0) {
const char *p;
size_t l = get_ptr_and_advance(length, &p);
crc = ceph_crc32c(crc, (unsigned char*)p, l);
length -= l;
}
return crc;
}
// explicitly instantiate only the iterator types we need, so we can hide the
// details in this compilation unit without introducing unnecessary link time
// dependencies.
template class buffer::list::iterator_impl<true>;
template class buffer::list::iterator_impl<false>;
buffer::list::iterator::iterator(bl_t *l, unsigned o)
: iterator_impl(l, o)
{}
buffer::list::iterator::iterator(bl_t *l, unsigned o, list_iter_t ip, unsigned po)
: iterator_impl(l, o, ip, po)
{}
// copy data in
void buffer::list::iterator::copy_in(unsigned len, const char *src, bool crc_reset)
{
// copy
if (p == ls->end())
seek(off);
while (len > 0) {
if (p == ls->end())
throw end_of_buffer();
unsigned howmuch = p->length() - p_off;
if (len < howmuch)
howmuch = len;
p->copy_in(p_off, howmuch, src, crc_reset);
src += howmuch;
len -= howmuch;
*this += howmuch;
}
}
void buffer::list::iterator::copy_in(unsigned len, const list& otherl)
{
if (p == ls->end())
seek(off);
unsigned left = len;
for (const auto& node : otherl._buffers) {
unsigned l = node.length();
if (left < l)
l = left;
copy_in(l, node.c_str());
left -= l;
if (left == 0)
break;
}
}
// -- buffer::list --
void buffer::list::swap(list& other) noexcept
{
std::swap(_len, other._len);
std::swap(_num, other._num);
std::swap(_carriage, other._carriage);
_buffers.swap(other._buffers);
}
bool buffer::list::contents_equal(const ceph::buffer::list& other) const
{
if (length() != other.length())
return false;
// buffer-wise comparison
if (true) {
auto a = std::cbegin(_buffers);
auto b = std::cbegin(other._buffers);
unsigned aoff = 0, boff = 0;
while (a != std::cend(_buffers)) {
unsigned len = a->length() - aoff;
if (len > b->length() - boff)
len = b->length() - boff;
if (memcmp(a->c_str() + aoff, b->c_str() + boff, len) != 0)
return false;
aoff += len;
if (aoff == a->length()) {
aoff = 0;
++a;
}
boff += len;
if (boff == b->length()) {
boff = 0;
++b;
}
}
return true;
}
// byte-wise comparison
if (false) {
bufferlist::const_iterator me = begin();
bufferlist::const_iterator him = other.begin();
while (!me.end()) {
if (*me != *him)
return false;
++me;
++him;
}
return true;
}
}
bool buffer::list::contents_equal(const void* const other,
size_t length) const
{
if (this->length() != length) {
return false;
}
const auto* other_buf = reinterpret_cast<const char*>(other);
for (const auto& bp : buffers()) {
assert(bp.length() <= length);
if (std::memcmp(bp.c_str(), other_buf, bp.length()) != 0) {
return false;
} else {
length -= bp.length();
other_buf += bp.length();
}
}
return true;
}
bool buffer::list::is_provided_buffer(const char* const dst) const
{
if (_buffers.empty()) {
return false;
}
return (is_contiguous() && (_buffers.front().c_str() == dst));
}
bool buffer::list::is_aligned(const unsigned align) const
{
for (const auto& node : _buffers) {
if (!node.is_aligned(align)) {
return false;
}
}
return true;
}
bool buffer::list::is_n_align_sized(const unsigned align) const
{
for (const auto& node : _buffers) {
if (!node.is_n_align_sized(align)) {
return false;
}
}
return true;
}
bool buffer::list::is_aligned_size_and_memory(
const unsigned align_size,
const unsigned align_memory) const
{
for (const auto& node : _buffers) {
if (!node.is_aligned(align_memory) || !node.is_n_align_sized(align_size)) {
return false;
}
}
return true;
}
bool buffer::list::is_zero() const {
for (const auto& node : _buffers) {
if (!node.is_zero()) {
return false;
}
}
return true;
}
void buffer::list::zero()
{
for (auto& node : _buffers) {
node.zero();
}
}
void buffer::list::zero(const unsigned o, const unsigned l)
{
ceph_assert(o+l <= _len);
unsigned p = 0;
for (auto& node : _buffers) {
if (p + node.length() > o) {
if (p >= o && p+node.length() <= o+l) {
// 'o'------------- l -----------|
// 'p'-- node.length() --|
node.zero();
} else if (p >= o) {
// 'o'------------- l -----------|
// 'p'------- node.length() -------|
node.zero(0, o+l-p);
} else if (p + node.length() <= o+l) {
// 'o'------------- l -----------|
// 'p'------- node.length() -------|
node.zero(o-p, node.length()-(o-p));
} else {
// 'o'----------- l -----------|
// 'p'---------- node.length() ----------|
node.zero(o-p, l);
}
}
p += node.length();
if (o+l <= p) {
break; // done
}
}
}
bool buffer::list::is_contiguous() const
{
return _num <= 1;
}
bool buffer::list::is_n_page_sized() const
{
return is_n_align_sized(CEPH_PAGE_SIZE);
}
bool buffer::list::is_page_aligned() const
{
return is_aligned(CEPH_PAGE_SIZE);
}
int buffer::list::get_mempool() const
{
if (_buffers.empty()) {
return mempool::mempool_buffer_anon;
}
return _buffers.back().get_mempool();
}
void buffer::list::reassign_to_mempool(int pool)
{
for (auto& p : _buffers) {
p._raw->reassign_to_mempool(pool);
}
}
void buffer::list::try_assign_to_mempool(int pool)
{
for (auto& p : _buffers) {
p._raw->try_assign_to_mempool(pool);
}
}
uint64_t buffer::list::get_wasted_space() const
{
if (_num == 1)
return _buffers.back().wasted();
std::vector<const raw*> raw_vec;
raw_vec.reserve(_num);
for (const auto& p : _buffers)
raw_vec.push_back(p._raw);
std::sort(raw_vec.begin(), raw_vec.end());
uint64_t total = 0;
const raw *last = nullptr;
for (const auto r : raw_vec) {
if (r == last)
continue;
last = r;
total += r->get_len();
}
// If multiple buffers are sharing the same raw buffer and they overlap
// with each other, the wasted space will be underestimated.
if (total <= length())
return 0;
return total - length();
}
void buffer::list::rebuild()
{
if (_len == 0) {
_carriage = &always_empty_bptr;
_buffers.clear_and_dispose();
_num = 0;
return;
}
if ((_len & ~CEPH_PAGE_MASK) == 0)
rebuild(ptr_node::create(buffer::create_page_aligned(_len)));
else
rebuild(ptr_node::create(buffer::create(_len)));
}
void buffer::list::rebuild(
std::unique_ptr<buffer::ptr_node, buffer::ptr_node::disposer> nb)
{
unsigned pos = 0;
int mempool = _buffers.front().get_mempool();
nb->reassign_to_mempool(mempool);
for (auto& node : _buffers) {
nb->copy_in(pos, node.length(), node.c_str(), false);
pos += node.length();
}
_buffers.clear_and_dispose();
if (likely(nb->length())) {
_carriage = nb.get();
_buffers.push_back(*nb.release());
_num = 1;
} else {
_carriage = &always_empty_bptr;
_num = 0;
}
invalidate_crc();
}
bool buffer::list::rebuild_aligned(unsigned align)
{
return rebuild_aligned_size_and_memory(align, align);
}
bool buffer::list::rebuild_aligned_size_and_memory(unsigned align_size,
unsigned align_memory,
unsigned max_buffers)
{
bool had_to_rebuild = false;
if (max_buffers && _num > max_buffers && _len > (max_buffers * align_size)) {
align_size = round_up_to(round_up_to(_len, max_buffers) / max_buffers, align_size);
}
auto p = std::begin(_buffers);
auto p_prev = _buffers.before_begin();
while (p != std::end(_buffers)) {
// keep anything that's already align and sized aligned
if (p->is_aligned(align_memory) && p->is_n_align_sized(align_size)) {
/*cout << " segment " << (void*)p->c_str()
<< " offset " << ((unsigned long)p->c_str() & (align - 1))
<< " length " << p->length()
<< " " << (p->length() & (align - 1)) << " ok" << std::endl;
*/
p_prev = p++;
continue;
}
// consolidate unaligned items, until we get something that is sized+aligned
list unaligned;
unsigned offset = 0;
do {
/*cout << " segment " << (void*)p->c_str()
<< " offset " << ((unsigned long)p->c_str() & (align - 1))
<< " length " << p->length() << " " << (p->length() & (align - 1))
<< " overall offset " << offset << " " << (offset & (align - 1))
<< " not ok" << std::endl;
*/
offset += p->length();
// no need to reallocate, relinking is enough thankfully to bi::list.
auto p_after = _buffers.erase_after(p_prev);
_num -= 1;
unaligned._buffers.push_back(*p);
unaligned._len += p->length();
unaligned._num += 1;
p = p_after;
} while (p != std::end(_buffers) &&
(!p->is_aligned(align_memory) ||
!p->is_n_align_sized(align_size) ||
(offset % align_size)));
if (!(unaligned.is_contiguous() && unaligned._buffers.front().is_aligned(align_memory))) {
unaligned.rebuild(
ptr_node::create(
buffer::create_aligned(unaligned._len, align_memory)));
had_to_rebuild = true;
}
if (unaligned.get_num_buffers()) {
_buffers.insert_after(p_prev, *ptr_node::create(unaligned._buffers.front()).release());
_num += 1;
} else {
// a bufferlist containing only 0-length bptrs is rebuilt as empty
}
++p_prev;
}
return had_to_rebuild;
}
bool buffer::list::rebuild_page_aligned()
{
return rebuild_aligned(CEPH_PAGE_SIZE);
}
void buffer::list::reserve(size_t prealloc)
{
if (get_append_buffer_unused_tail_length() < prealloc) {
auto ptr = ptr_node::create(buffer::create_small_page_aligned(prealloc));
ptr->set_length(0); // unused, so far.
_carriage = ptr.get();
_buffers.push_back(*ptr.release());
_num += 1;
}
}
void buffer::list::claim_append(list& bl)
{
// check overflow
assert(_len + bl._len >= _len);
// steal the other guy's buffers
_len += bl._len;
_num += bl._num;
_buffers.splice_back(bl._buffers);
bl.clear();
}
void buffer::list::append(char c)
{
// put what we can into the existing append_buffer.
unsigned gap = get_append_buffer_unused_tail_length();
if (!gap) {
// make a new buffer!
auto buf = ptr_node::create(
raw_combined::create(CEPH_BUFFER_APPEND_SIZE, 0, get_mempool()));
buf->set_length(0); // unused, so far.
_carriage = buf.get();
_buffers.push_back(*buf.release());
_num += 1;
} else if (unlikely(_carriage != &_buffers.back())) {
auto bptr = ptr_node::create(*_carriage, _carriage->length(), 0);
_carriage = bptr.get();
_buffers.push_back(*bptr.release());
_num += 1;
}
_carriage->append(c);
_len++;
}
buffer::ptr_node buffer::list::always_empty_bptr;
buffer::ptr_node& buffer::list::refill_append_space(const unsigned len)
{
// make a new buffer. fill out a complete page, factoring in the
// raw_combined overhead.
size_t need = round_up_to(len, sizeof(size_t)) + sizeof(raw_combined);
size_t alen = round_up_to(need, CEPH_BUFFER_ALLOC_UNIT);
if (_carriage == &_buffers.back()) {
size_t nlen = round_up_to(_carriage->raw_length(), CEPH_BUFFER_ALLOC_UNIT) * 2;
nlen = std::min(nlen, CEPH_BUFFER_ALLOC_UNIT_MAX);
alen = std::max(alen, nlen);
}
alen -= sizeof(raw_combined);
auto new_back = \
ptr_node::create(raw_combined::create(alen, 0, get_mempool()));
new_back->set_length(0); // unused, so far.
_carriage = new_back.get();
_buffers.push_back(*new_back.release());
_num += 1;
return _buffers.back();
}
void buffer::list::append(const char *data, unsigned len)
{
_len += len;
const unsigned free_in_last = get_append_buffer_unused_tail_length();
const unsigned first_round = std::min(len, free_in_last);
if (first_round) {
// _buffers and carriage can desynchronize when 1) a new ptr
// we don't own has been added into the _buffers 2) _buffers
// has been emptied as as a result of std::move or stolen by
// claim_append.
if (unlikely(_carriage != &_buffers.back())) {
auto bptr = ptr_node::create(*_carriage, _carriage->length(), 0);
_carriage = bptr.get();
_buffers.push_back(*bptr.release());
_num += 1;
}
_carriage->append(data, first_round);
}
const unsigned second_round = len - first_round;
if (second_round) {
auto& new_back = refill_append_space(second_round);
new_back.append(data + first_round, second_round);
}
}
buffer::list::reserve_t buffer::list::obtain_contiguous_space(
const unsigned len)
{
// note: if len < the normal append_buffer size it *might*
// be better to allocate a normal-sized append_buffer and
// use part of it. however, that optimizes for the case of
// old-style types including new-style types. and in most
// such cases, this won't be the very first thing encoded to
// the list, so append_buffer will already be allocated.
// OTOH if everything is new-style, we *should* allocate
// only what we need and conserve memory.
if (unlikely(get_append_buffer_unused_tail_length() < len)) {
auto new_back = \
buffer::ptr_node::create(buffer::create(len)).release();
new_back->set_length(0); // unused, so far.
_buffers.push_back(*new_back);
_num += 1;
_carriage = new_back;
return { new_back->c_str(), &new_back->_len, &_len };
} else {
ceph_assert(!_buffers.empty());
if (unlikely(_carriage != &_buffers.back())) {
auto bptr = ptr_node::create(*_carriage, _carriage->length(), 0);
_carriage = bptr.get();
_buffers.push_back(*bptr.release());
_num += 1;
}
return { _carriage->end_c_str(), &_carriage->_len, &_len };
}
}
void buffer::list::append(const ptr& bp)
{
push_back(bp);
}
void buffer::list::append(ptr&& bp)
{
push_back(std::move(bp));
}
void buffer::list::append(const ptr& bp, unsigned off, unsigned len)
{
ceph_assert(len+off <= bp.length());
if (!_buffers.empty()) {
ptr &l = _buffers.back();
if (l._raw == bp._raw && l.end() == bp.start() + off) {
// yay contiguous with tail bp!
l.set_length(l.length()+len);
_len += len;
return;
}
}
// add new item to list
_buffers.push_back(*ptr_node::create(bp, off, len).release());
_len += len;
_num += 1;
}
void buffer::list::append(const list& bl)
{
_len += bl._len;
_num += bl._num;
for (const auto& node : bl._buffers) {
_buffers.push_back(*ptr_node::create(node).release());
}
}
void buffer::list::append(std::istream& in)
{
while (!in.eof()) {
std::string s;
getline(in, s);
append(s.c_str(), s.length());
if (s.length())
append("\n", 1);
}
}
buffer::list::contiguous_filler buffer::list::append_hole(const unsigned len)
{
_len += len;
if (unlikely(get_append_buffer_unused_tail_length() < len)) {
// make a new append_buffer. fill out a complete page, factoring in
// the raw_combined overhead.
auto& new_back = refill_append_space(len);
new_back.set_length(len);
return { new_back.c_str() };
} else if (unlikely(_carriage != &_buffers.back())) {
auto bptr = ptr_node::create(*_carriage, _carriage->length(), 0);
_carriage = bptr.get();
_buffers.push_back(*bptr.release());
_num += 1;
}
_carriage->set_length(_carriage->length() + len);
return { _carriage->end_c_str() - len };
}
void buffer::list::prepend_zero(unsigned len)
{
auto bp = ptr_node::create(len);
bp->zero(false);
_len += len;
_num += 1;
_buffers.push_front(*bp.release());
}
void buffer::list::append_zero(unsigned len)
{
_len += len;
const unsigned free_in_last = get_append_buffer_unused_tail_length();
const unsigned first_round = std::min(len, free_in_last);
if (first_round) {
if (unlikely(_carriage != &_buffers.back())) {
auto bptr = ptr_node::create(*_carriage, _carriage->length(), 0);
_carriage = bptr.get();
_buffers.push_back(*bptr.release());
_num += 1;
}
_carriage->append_zeros(first_round);
}
const unsigned second_round = len - first_round;
if (second_round) {
auto& new_back = refill_append_space(second_round);
new_back.set_length(second_round);
new_back.zero(false);
}
}
/*
* get a char
*/
const char& buffer::list::operator[](unsigned n) const
{
if (n >= _len)
throw end_of_buffer();
for (const auto& node : _buffers) {
if (n >= node.length()) {
n -= node.length();
continue;
}
return node[n];
}
ceph_abort();
}
/*
* return a contiguous ptr to whole bufferlist contents.
*/
char *buffer::list::c_str()
{
if (const auto len = length(); len == 0) {
return nullptr; // no non-empty buffers
} else if (len != _buffers.front().length()) {
rebuild();
} else {
// there are two *main* scenarios that hit this branch:
// 1. bufferlist with single, non-empty buffer;
// 2. bufferlist with single, non-empty buffer followed by
// empty buffer. splice() tries to not waste our appendable
// space; to carry it an empty bptr is added at the end.
// we account for these and don't rebuild unnecessarily
}
return _buffers.front().c_str();
}
string buffer::list::to_str() const {
string s;
s.reserve(length());
for (const auto& node : _buffers) {
if (node.length()) {
s.append(node.c_str(), node.length());
}
}
return s;
}
void buffer::list::substr_of(const list& other, unsigned off, unsigned len)
{
if (off + len > other.length())
throw end_of_buffer();
clear();
// skip off
auto curbuf = std::cbegin(other._buffers);
while (off > 0 && off >= curbuf->length()) {
// skip this buffer
//cout << "skipping over " << *curbuf << std::endl;
off -= (*curbuf).length();
++curbuf;
}
ceph_assert(len == 0 || curbuf != std::cend(other._buffers));
while (len > 0) {
// partial?
if (off + len < curbuf->length()) {
//cout << "copying partial of " << *curbuf << std::endl;
_buffers.push_back(*ptr_node::create(*curbuf, off, len).release());
_len += len;
_num += 1;
break;
}
// through end
//cout << "copying end (all?) of " << *curbuf << std::endl;
unsigned howmuch = curbuf->length() - off;
_buffers.push_back(*ptr_node::create(*curbuf, off, howmuch).release());
_len += howmuch;
_num += 1;
len -= howmuch;
off = 0;
++curbuf;
}
}
// funky modifer
void buffer::list::splice(unsigned off, unsigned len, list *claim_by /*, bufferlist& replace_with */)
{ // fixme?
if (len == 0)
return;
if (off >= length())
throw end_of_buffer();
ceph_assert(len > 0);
//cout << "splice off " << off << " len " << len << " ... mylen = " << length() << std::endl;
// skip off
auto curbuf = std::begin(_buffers);
auto curbuf_prev = _buffers.before_begin();
while (off > 0) {
ceph_assert(curbuf != std::end(_buffers));
if (off >= (*curbuf).length()) {
// skip this buffer
//cout << "off = " << off << " skipping over " << *curbuf << std::endl;
off -= (*curbuf).length();
curbuf_prev = curbuf++;
} else {
// somewhere in this buffer!
//cout << "off = " << off << " somewhere in " << *curbuf << std::endl;
break;
}
}
if (off) {
// add a reference to the front bit, insert it before curbuf (which
// we'll lose).
//cout << "keeping front " << off << " of " << *curbuf << std::endl;
_buffers.insert_after(curbuf_prev,
*ptr_node::create(*curbuf, 0, off).release());
_len += off;
_num += 1;
++curbuf_prev;
}
while (len > 0) {
// partial or the last (appendable) one?
if (const auto to_drop = off + len; to_drop < curbuf->length()) {
//cout << "keeping end of " << *curbuf << ", losing first " << off+len << std::endl;
if (claim_by)
claim_by->append(*curbuf, off, len);
curbuf->set_offset(to_drop + curbuf->offset()); // ignore beginning big
curbuf->set_length(curbuf->length() - to_drop);
_len -= to_drop;
//cout << " now " << *curbuf << std::endl;
break;
}
// hose though the end
unsigned howmuch = curbuf->length() - off;
//cout << "discarding " << howmuch << " of " << *curbuf << std::endl;
if (claim_by)
claim_by->append(*curbuf, off, howmuch);
_len -= curbuf->length();
if (curbuf == _carriage) {
// no need to reallocate, shrinking and relinking is enough.
curbuf = _buffers.erase_after(curbuf_prev);
_carriage->set_offset(_carriage->offset() + _carriage->length());
_carriage->set_length(0);
_buffers.push_back(*_carriage);
} else {
curbuf = _buffers.erase_after_and_dispose(curbuf_prev);
_num -= 1;
}
len -= howmuch;
off = 0;
}
// splice in *replace (implement me later?)
}
void buffer::list::write(int off, int len, std::ostream& out) const
{
list s;
s.substr_of(*this, off, len);
for (const auto& node : s._buffers) {
if (node.length()) {
out.write(node.c_str(), node.length());
}
}
}
void buffer::list::encode_base64(buffer::list& o)
{
bufferptr bp(length() * 4 / 3 + 3);
int l = ceph_armor(bp.c_str(), bp.c_str() + bp.length(), c_str(), c_str() + length());
bp.set_length(l);
o.push_back(std::move(bp));
}
void buffer::list::decode_base64(buffer::list& e)
{
bufferptr bp(4 + ((e.length() * 3) / 4));
int l = ceph_unarmor(bp.c_str(), bp.c_str() + bp.length(), e.c_str(), e.c_str() + e.length());
if (l < 0) {
std::ostringstream oss;
oss << "decode_base64: decoding failed:\n";
hexdump(oss);
throw buffer::malformed_input(oss.str().c_str());
}
ceph_assert(l <= (int)bp.length());
bp.set_length(l);
push_back(std::move(bp));
}
ssize_t buffer::list::pread_file(const char *fn, uint64_t off, uint64_t len, std::string *error)
{
int fd = TEMP_FAILURE_RETRY(::open(fn, O_RDONLY|O_CLOEXEC|O_BINARY));
if (fd < 0) {
int err = errno;
std::ostringstream oss;
oss << "can't open " << fn << ": " << cpp_strerror(err);
*error = oss.str();
return -err;
}
struct stat st;
// FIPS zeroization audit 20191115: this memset is not security related.
memset(&st, 0, sizeof(st));
if (::fstat(fd, &st) < 0) {
int err = errno;
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): stat error: "
<< cpp_strerror(err);
*error = oss.str();
VOID_TEMP_FAILURE_RETRY(::close(fd));
return -err;
}
if (off > (uint64_t)st.st_size) {
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): read error: size < offset";
*error = oss.str();
VOID_TEMP_FAILURE_RETRY(::close(fd));
return 0;
}
if (len > st.st_size - off) {
len = st.st_size - off;
}
ssize_t ret = lseek64(fd, off, SEEK_SET);
if (ret != (ssize_t)off) {
return -errno;
}
ret = read_fd(fd, len);
if (ret < 0) {
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): read error:"
<< cpp_strerror(ret);
*error = oss.str();
VOID_TEMP_FAILURE_RETRY(::close(fd));
return ret;
} else if (ret != (ssize_t)len) {
// Premature EOF.
// Perhaps the file changed between stat() and read()?
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): warning: got premature EOF.";
*error = oss.str();
// not actually an error, but weird
}
VOID_TEMP_FAILURE_RETRY(::close(fd));
return 0;
}
int buffer::list::read_file(const char *fn, std::string *error)
{
int fd = TEMP_FAILURE_RETRY(::open(fn, O_RDONLY|O_CLOEXEC|O_BINARY));
if (fd < 0) {
int err = errno;
std::ostringstream oss;
oss << "can't open " << fn << ": " << cpp_strerror(err);
*error = oss.str();
return -err;
}
struct stat st;
// FIPS zeroization audit 20191115: this memset is not security related.
memset(&st, 0, sizeof(st));
if (::fstat(fd, &st) < 0) {
int err = errno;
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): stat error: "
<< cpp_strerror(err);
*error = oss.str();
VOID_TEMP_FAILURE_RETRY(::close(fd));
return -err;
}
ssize_t ret = read_fd(fd, st.st_size);
if (ret < 0) {
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): read error:"
<< cpp_strerror(ret);
*error = oss.str();
VOID_TEMP_FAILURE_RETRY(::close(fd));
return ret;
}
else if (ret != st.st_size) {
// Premature EOF.
// Perhaps the file changed between stat() and read()?
std::ostringstream oss;
oss << "bufferlist::read_file(" << fn << "): warning: got premature EOF.";
*error = oss.str();
// not actually an error, but weird
}
VOID_TEMP_FAILURE_RETRY(::close(fd));
return 0;
}
ssize_t buffer::list::read_fd(int fd, size_t len)
{
auto bp = ptr_node::create(buffer::create(len));
ssize_t ret = safe_read(fd, (void*)bp->c_str(), len);
if (ret >= 0) {
bp->set_length(ret);
push_back(std::move(bp));
}
return ret;
}
ssize_t buffer::list::recv_fd(int fd, size_t len)
{
auto bp = ptr_node::create(buffer::create(len));
ssize_t ret = safe_recv(fd, (void*)bp->c_str(), len);
if (ret >= 0) {
bp->set_length(ret);
push_back(std::move(bp));
}
return ret;
}
int buffer::list::write_file(const char *fn, int mode)
{
int fd = TEMP_FAILURE_RETRY(::open(fn, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_BINARY, mode));
if (fd < 0) {
int err = errno;
cerr << "bufferlist::write_file(" << fn << "): failed to open file: "
<< cpp_strerror(err) << std::endl;
return -err;
}
int ret = write_fd(fd);
if (ret) {
cerr << "bufferlist::write_fd(" << fn << "): write_fd error: "
<< cpp_strerror(ret) << std::endl;
VOID_TEMP_FAILURE_RETRY(::close(fd));
return ret;
}
if (TEMP_FAILURE_RETRY(::close(fd))) {
int err = errno;
cerr << "bufferlist::write_file(" << fn << "): close error: "
<< cpp_strerror(err) << std::endl;
return -err;
}
return 0;
}
static int do_writev(int fd, struct iovec *vec, uint64_t offset, unsigned veclen, unsigned bytes)
{
while (bytes > 0) {
ssize_t r = 0;
#ifdef HAVE_PWRITEV
r = ::pwritev(fd, vec, veclen, offset);
#else
r = ::lseek64(fd, offset, SEEK_SET);
if (r != offset) {
return -errno;
}
r = ::writev(fd, vec, veclen);
#endif
if (r < 0) {
if (errno == EINTR)
continue;
return -errno;
}
bytes -= r;
offset += r;
if (bytes == 0) break;
while (r > 0) {
if (vec[0].iov_len <= (size_t)r) {
// drain this whole item
r -= vec[0].iov_len;
++vec;
--veclen;
} else {
vec[0].iov_base = (char *)vec[0].iov_base + r;
vec[0].iov_len -= r;
break;
}
}
}
return 0;
}
#ifndef _WIN32
int buffer::list::write_fd(int fd) const
{
// use writev!
iovec iov[IOV_MAX];
int iovlen = 0;
ssize_t bytes = 0;
auto p = std::cbegin(_buffers);
while (p != std::cend(_buffers)) {
if (p->length() > 0) {
iov[iovlen].iov_base = (void *)p->c_str();
iov[iovlen].iov_len = p->length();
bytes += p->length();
iovlen++;
}
++p;
if (iovlen == IOV_MAX ||
p == _buffers.end()) {
iovec *start = iov;
int num = iovlen;
ssize_t wrote;
retry:
wrote = ::writev(fd, start, num);
if (wrote < 0) {
int err = errno;
if (err == EINTR)
goto retry;
return -err;
}
if (wrote < bytes) {
// partial write, recover!
while ((size_t)wrote >= start[0].iov_len) {
wrote -= start[0].iov_len;
bytes -= start[0].iov_len;
start++;
num--;
}
if (wrote > 0) {
start[0].iov_len -= wrote;
start[0].iov_base = (char *)start[0].iov_base + wrote;
bytes -= wrote;
}
goto retry;
}
iovlen = 0;
bytes = 0;
}
}
return 0;
}
int buffer::list::send_fd(int fd) const {
return buffer::list::write_fd(fd);
}
int buffer::list::write_fd(int fd, uint64_t offset) const
{
iovec iov[IOV_MAX];
auto p = std::cbegin(_buffers);
uint64_t left_pbrs = get_num_buffers();
while (left_pbrs) {
ssize_t bytes = 0;
unsigned iovlen = 0;
uint64_t size = std::min<uint64_t>(left_pbrs, IOV_MAX);
left_pbrs -= size;
while (size > 0) {
iov[iovlen].iov_base = (void *)p->c_str();
iov[iovlen].iov_len = p->length();
iovlen++;
bytes += p->length();
++p;
size--;
}
int r = do_writev(fd, iov, offset, iovlen, bytes);
if (r < 0)
return r;
offset += bytes;
}
return 0;
}
#else
int buffer::list::write_fd(int fd) const
{
// There's no writev on Windows. WriteFileGather may be an option,
// but it has strict requirements in terms of buffer size and alignment.
auto p = std::cbegin(_buffers);
uint64_t left_pbrs = get_num_buffers();
while (left_pbrs) {
int written = 0;
while (written < p->length()) {
int r = ::write(fd, p->c_str(), p->length() - written);
if (r < 0)
return -errno;
written += r;
}
left_pbrs--;
p++;
}
return 0;
}
int buffer::list::send_fd(int fd) const
{
// There's no writev on Windows. WriteFileGather may be an option,
// but it has strict requirements in terms of buffer size and alignment.
auto p = std::cbegin(_buffers);
uint64_t left_pbrs = get_num_buffers();
while (left_pbrs) {
int written = 0;
while (written < p->length()) {
int r = ::send(fd, p->c_str(), p->length() - written, 0);
if (r < 0)
return -ceph_sock_errno();
written += r;
}
left_pbrs--;
p++;
}
return 0;
}
int buffer::list::write_fd(int fd, uint64_t offset) const
{
int r = ::lseek64(fd, offset, SEEK_SET);
if (r != offset)
return -errno;
return write_fd(fd);
}
#endif
buffer::list::iov_vec_t buffer::list::prepare_iovs() const
{
size_t index = 0;
uint64_t off = 0;
iov_vec_t iovs{_num / IOV_MAX + 1};
auto it = iovs.begin();
for (auto& bp : _buffers) {
if (index == 0) {
it->offset = off;
it->length = 0;
size_t nr_iov_created = std::distance(iovs.begin(), it);
it->iov.resize(
std::min(_num - IOV_MAX * nr_iov_created, (size_t)IOV_MAX));
}
it->iov[index].iov_base = (void*)bp.c_str();
it->iov[index].iov_len = bp.length();
off += bp.length();
it->length += bp.length();
if (++index == IOV_MAX) {
// continue with a new vector<iov> if we have more buf
++it;
index = 0;
}
}
return iovs;
}
__u32 buffer::list::crc32c(__u32 crc) const
{
int cache_misses = 0;
int cache_hits = 0;
int cache_adjusts = 0;
for (const auto& node : _buffers) {
if (node.length()) {
raw* const r = node._raw;
pair<size_t, size_t> ofs(node.offset(), node.offset() + node.length());
pair<uint32_t, uint32_t> ccrc;
if (r->get_crc(ofs, &ccrc)) {
if (ccrc.first == crc) {
// got it already
crc = ccrc.second;
cache_hits++;
} else {
/* If we have cached crc32c(buf, v) for initial value v,
* we can convert this to a different initial value v' by:
* crc32c(buf, v') = crc32c(buf, v) ^ adjustment
* where adjustment = crc32c(0*len(buf), v ^ v')
*
* http://crcutil.googlecode.com/files/crc-doc.1.0.pdf
* note, u for our crc32c implementation is 0
*/
crc = ccrc.second ^ ceph_crc32c(ccrc.first ^ crc, NULL, node.length());
cache_adjusts++;
}
} else {
cache_misses++;
uint32_t base = crc;
crc = ceph_crc32c(crc, (unsigned char*)node.c_str(), node.length());
r->set_crc(ofs, make_pair(base, crc));
}
}
}
if (buffer_track_crc) {
if (cache_adjusts)
buffer_cached_crc_adjusted += cache_adjusts;
if (cache_hits)
buffer_cached_crc += cache_hits;
if (cache_misses)
buffer_missed_crc += cache_misses;
}
return crc;
}
void buffer::list::invalidate_crc()
{
for (const auto& node : _buffers) {
if (node._raw) {
node._raw->invalidate_crc();
}
}
}
/**
* Binary write all contents to a C++ stream
*/
void buffer::list::write_stream(std::ostream &out) const
{
for (const auto& node : _buffers) {
if (node.length() > 0) {
out.write(node.c_str(), node.length());
}
}
}
void buffer::list::hexdump(std::ostream &out, bool trailing_newline) const
{
if (!length())
return;
std::ios_base::fmtflags original_flags = out.flags();
// do our best to match the output of hexdump -C, for better
// diff'ing!
out.setf(std::ios::right);
out.fill('0');
unsigned per = 16;
char last_row_char = '\0';
bool was_same = false, did_star = false;
for (unsigned o=0; o<length(); o += per) {
if (o == 0) {
last_row_char = (*this)[o];
}
if (o + per < length()) {
bool row_is_same = true;
for (unsigned i=0; i<per && o+i<length(); i++) {
char current_char = (*this)[o+i];
if (current_char != last_row_char) {
if (i == 0) {
last_row_char = current_char;
was_same = false;
did_star = false;
} else {
row_is_same = false;
}
}
}
if (row_is_same) {
if (was_same) {
if (!did_star) {
out << "\n*";
did_star = true;
}
continue;
}
was_same = true;
} else {
was_same = false;
did_star = false;
}
}
if (o)
out << "\n";
out << std::hex << std::setw(8) << o << " ";
unsigned i;
for (i=0; i<per && o+i<length(); i++) {
if (i == 8)
out << ' ';
out << " " << std::setw(2) << ((unsigned)(*this)[o+i] & 0xff);
}
for (; i<per; i++) {
if (i == 8)
out << ' ';
out << " ";
}
out << " |";
for (i=0; i<per && o+i<length(); i++) {
char c = (*this)[o+i];
if (isupper(c) || islower(c) || isdigit(c) || c == ' ' || ispunct(c))
out << c;
else
out << '.';
}
out << '|' << std::dec;
}
if (trailing_newline) {
out << "\n" << std::hex << std::setw(8) << length();
out << "\n";
}
out.flags(original_flags);
}
buffer::list buffer::list::static_from_mem(char* c, size_t l) {
list bl;
bl.push_back(ptr_node::create(create_static(l, c)));
return bl;
}
buffer::list buffer::list::static_from_cstring(char* c) {
return static_from_mem(c, std::strlen(c));
}
buffer::list buffer::list::static_from_string(string& s) {
// C++14 just has string::data return a char* from a non-const
// string.
return static_from_mem(const_cast<char*>(s.data()), s.length());
// But the way buffer::list mostly doesn't work in a sane way with
// const makes me generally sad.
}
// buffer::raw is not a standard layout type.
#define BUF_OFFSETOF(type, field) \
(reinterpret_cast<std::uintptr_t>(&(((type*)1024)->field)) - 1024u)
bool buffer::ptr_node::dispose_if_hypercombined(
buffer::ptr_node* const delete_this)
{
// in case _raw is nullptr
const std::uintptr_t bptr =
(reinterpret_cast<std::uintptr_t>(delete_this->_raw) +
BUF_OFFSETOF(buffer::raw, bptr_storage));
const bool is_hypercombined =
reinterpret_cast<std::uintptr_t>(delete_this) == bptr;
if (is_hypercombined) {
ceph_assert_always("hypercombining is currently disabled" == nullptr);
delete_this->~ptr_node();
return true;
} else {
return false;
}
}
std::unique_ptr<buffer::ptr_node, buffer::ptr_node::disposer>
buffer::ptr_node::create_hypercombined(ceph::unique_leakable_ptr<buffer::raw> r)
{
// FIXME: we don't currently hypercombine buffers due to crashes
// observed in the rados suite. After fixing we'll use placement
// new to create ptr_node on buffer::raw::bptr_storage.
return std::unique_ptr<buffer::ptr_node, buffer::ptr_node::disposer>(
new ptr_node(std::move(r)));
}
buffer::ptr_node* buffer::ptr_node::cloner::operator()(
const buffer::ptr_node& clone_this)
{
return new ptr_node(clone_this);
}
std::ostream& buffer::operator<<(std::ostream& out, const buffer::raw &r) {
return out << "buffer::raw("
<< (void*)r.get_data() << " len " << r.get_len()
<< " nref " << r.nref.load() << ")";
}
std::ostream& buffer::operator<<(std::ostream& out, const buffer::ptr& bp) {
if (bp.have_raw())
out << "buffer::ptr(" << bp.offset() << "~" << bp.length()
<< " " << (void*)bp.c_str()
<< " in raw " << (void*)bp.raw_c_str()
<< " len " << bp.raw_length()
<< " nref " << bp.raw_nref() << ")";
else
out << "buffer:ptr(" << bp.offset() << "~" << bp.length() << " no raw)";
return out;
}
std::ostream& buffer::operator<<(std::ostream& out, const buffer::list& bl) {
out << "buffer::list(len=" << bl.length() << ",\n";
for (const auto& node : bl.buffers()) {
out << "\t" << node;
if (&node != &bl.buffers().back()) {
out << ",\n";
}
}
out << "\n)";
return out;
}
MEMPOOL_DEFINE_OBJECT_FACTORY(buffer::raw_malloc, buffer_raw_malloc,
buffer_meta);
MEMPOOL_DEFINE_OBJECT_FACTORY(buffer::raw_posix_aligned,
buffer_raw_posix_aligned, buffer_meta);
MEMPOOL_DEFINE_OBJECT_FACTORY(buffer::raw_claimed_char, buffer_raw_claimed_char,
buffer_meta);
MEMPOOL_DEFINE_OBJECT_FACTORY(buffer::raw_static, buffer_raw_static,
buffer_meta);
void ceph::buffer::list::page_aligned_appender::_refill(size_t len) {
const unsigned alloc =
std::max(min_alloc,
shift_round_up(static_cast<unsigned>(len),
static_cast<unsigned>(CEPH_PAGE_SHIFT)));
auto new_back = \
ptr_node::create(buffer::create_page_aligned(alloc));
new_back->set_length(0); // unused, so far.
bl.push_back(std::move(new_back));
}
namespace ceph::buffer {
inline namespace v15_2_0 {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
class buffer_error_category : public ceph::converting_category {
public:
buffer_error_category(){}
const char* name() const noexcept override;
const char* message(int ev, char*, std::size_t) const noexcept override;
std::string message(int ev) const override;
boost::system::error_condition default_error_condition(int ev) const noexcept
override;
using ceph::converting_category::equivalent;
bool equivalent(int ev, const boost::system::error_condition& c) const
noexcept override;
int from_code(int ev) const noexcept override;
};
#pragma GCC diagnostic pop
#pragma clang diagnostic pop
const char* buffer_error_category::name() const noexcept {
return "buffer";
}
const char*
buffer_error_category::message(int ev, char*, std::size_t) const noexcept {
using ceph::buffer::errc;
if (ev == 0)
return "No error";
switch (static_cast<errc>(ev)) {
case errc::bad_alloc:
return "Bad allocation";
case errc::end_of_buffer:
return "End of buffer";
case errc::malformed_input:
return "Malformed input";
}
return "Unknown error";
}
std::string buffer_error_category::message(int ev) const {
return message(ev, nullptr, 0);
}
boost::system::error_condition
buffer_error_category::default_error_condition(int ev)const noexcept {
using ceph::buffer::errc;
switch (static_cast<errc>(ev)) {
case errc::bad_alloc:
return boost::system::errc::not_enough_memory;
case errc::end_of_buffer:
case errc::malformed_input:
return boost::system::errc::io_error;
}
return { ev, *this };
}
bool buffer_error_category::equivalent(int ev, const boost::system::error_condition& c) const noexcept {
return default_error_condition(ev) == c;
}
int buffer_error_category::from_code(int ev) const noexcept {
using ceph::buffer::errc;
switch (static_cast<errc>(ev)) {
case errc::bad_alloc:
return -ENOMEM;
case errc::end_of_buffer:
return -EIO;
case errc::malformed_input:
return -EIO;
}
return -EDOM;
}
const boost::system::error_category& buffer_category() noexcept {
static const buffer_error_category c;
return c;
}
}
}
| 63,861 | 26.071641 | 104 | cc |
null | ceph-main/src/common/buffer_instrumentation.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "include/buffer.h"
#include "include/buffer_raw.h"
namespace ceph::buffer_instrumentation {
// this is nothing more than an intermediary for a class hierarchy which
// can placed between a user's custom raw and the `ceph::buffer::raw` to
// detect whether a given `ceph::buffer::ptr` instance wraps a particular
// raw's implementation (via `dynamic_cast` or `typeid`).
//
// users are supposed to define marker type (e.g. `class my_marker{}`).
// this marker. i
template <class MarkerT>
struct instrumented_raw : public ceph::buffer::raw {
using raw::raw;
};
struct instrumented_bptr : public ceph::buffer::ptr {
const ceph::buffer::raw* get_raw() const {
return _raw;
}
template <class MarkerT>
bool is_raw_marked() const {
return dynamic_cast<const instrumented_raw<MarkerT>*>(get_raw()) != nullptr;
}
};
} // namespace ceph::buffer_instrumentation
| 985 | 28.878788 | 80 | h |
null | ceph-main/src/common/buffer_seastar.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <seastar/core/sharded.hh>
#include <seastar/net/packet.hh>
#include "include/buffer_raw.h"
#include "buffer_seastar.h"
using temporary_buffer = seastar::temporary_buffer<char>;
namespace ceph::buffer {
class raw_seastar_foreign_ptr : public raw {
seastar::foreign_ptr<temporary_buffer> ptr;
public:
raw_seastar_foreign_ptr(temporary_buffer&& buf)
: raw(buf.get_write(), buf.size()), ptr(std::move(buf)) {}
};
class raw_seastar_local_ptr : public raw {
temporary_buffer buf;
public:
raw_seastar_local_ptr(temporary_buffer&& buf)
: raw(buf.get_write(), buf.size()), buf(std::move(buf)) {}
};
inline namespace v15_2_0 {
ceph::unique_leakable_ptr<buffer::raw> create(temporary_buffer&& buf) {
return ceph::unique_leakable_ptr<buffer::raw>(
new raw_seastar_foreign_ptr(std::move(buf)));
}
ceph::unique_leakable_ptr<buffer::raw> create_local(temporary_buffer&& buf) {
return ceph::unique_leakable_ptr<buffer::raw>(
new raw_seastar_local_ptr(std::move(buf)));
}
} // inline namespace v15_2_0
// buffer::ptr conversions
ptr::operator seastar::temporary_buffer<char>() &
{
return {c_str(), _len, seastar::make_object_deleter(*this)};
}
ptr::operator seastar::temporary_buffer<char>() &&
{
auto data = c_str();
auto length = _len;
return {data, length, seastar::make_object_deleter(std::move(*this))};
}
// buffer::list conversions
list::operator seastar::net::packet() &&
{
seastar::net::packet p(_num);
for (auto& ptr : _buffers) {
// append each ptr as a temporary_buffer
p = seastar::net::packet(std::move(p), std::move(ptr));
}
clear();
return p;
}
} // namespace ceph::buffer
namespace {
using ceph::buffer::raw;
class raw_seastar_local_shared_ptr : public raw {
temporary_buffer buf;
public:
raw_seastar_local_shared_ptr(temporary_buffer& buf)
: raw(buf.get_write(), buf.size()), buf(buf.share()) {}
};
}
buffer::ptr seastar_buffer_iterator::get_ptr(size_t len)
{
buffer::ptr p{ceph::unique_leakable_ptr<buffer::raw>(
new raw_seastar_local_shared_ptr{buf})};
p.set_length(len);
return p;
}
buffer::ptr const_seastar_buffer_iterator::get_ptr(size_t len)
{
return buffer::ptr{ buffer::copy(get_pos_add(len), len) };
}
| 2,622 | 23.980952 | 77 | cc |
null | ceph-main/src/common/buffer_seastar.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <seastar/core/temporary_buffer.hh>
#include "include/buffer.h"
#include "common/error_code.h"
namespace details {
template<bool is_const>
class buffer_iterator_impl {
public:
using pointer = std::conditional_t<is_const, const char*, char *>;
buffer_iterator_impl(pointer first, const char* last)
: pos(first), end_ptr(last)
{}
pointer get_pos_add(size_t n) {
auto r = pos;
pos += n;
if (pos > end_ptr) {
throw buffer::end_of_buffer{};
}
return r;
}
pointer get() const {
return pos;
}
protected:
pointer pos;
const char* end_ptr;
};
} // namespace details
class seastar_buffer_iterator : details::buffer_iterator_impl<false> {
using parent = details::buffer_iterator_impl<false>;
using temporary_buffer = seastar::temporary_buffer<char>;
public:
seastar_buffer_iterator(temporary_buffer& b)
: parent(b.get_write(), b.end()), buf(b)
{}
using parent::pointer;
using parent::get_pos_add;
using parent::get;
ceph::buffer::ptr get_ptr(size_t len);
private:
// keep the reference to buf around, so it can be "shared" by get_ptr()
temporary_buffer& buf;
};
class const_seastar_buffer_iterator : details::buffer_iterator_impl<true> {
using parent = details::buffer_iterator_impl<true>;
using temporary_buffer = seastar::temporary_buffer<char>;
public:
const_seastar_buffer_iterator(temporary_buffer& b)
: parent(b.get_write(), b.end())
{}
using parent::pointer;
using parent::get_pos_add;
using parent::get;
ceph::buffer::ptr get_ptr(size_t len);
};
| 1,651 | 25.222222 | 75 | h |
null | ceph-main/src/common/ceph_argparse.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 <stdarg.h>
#include "auth/Auth.h"
#include "common/ceph_argparse.h"
#include "common/config.h"
#include "common/version.h"
#include "include/str_list.h"
/*
* Ceph argument parsing library
*
* We probably should eventually replace this with something standard like popt.
* Until we do that, though, this file is the place for argv parsing
* stuff to live.
*/
#undef dout
#undef pdout
#undef derr
#undef generic_dout
#undef dendl
struct strict_str_convert {
const char *str;
std::string *err;
strict_str_convert(const char *str, std::string *err)
: str(str), err(err) {}
inline operator float() const
{
return strict_strtof(str, err);
}
inline operator int() const
{
return strict_strtol(str, 10, err);
}
inline operator long long() const
{
return strict_strtoll(str, 10, err);
}
};
void string_to_vec(std::vector<std::string>& args, std::string argstr)
{
std::istringstream iss(argstr);
while(iss) {
std::string sub;
iss >> sub;
if (sub == "") break;
args.push_back(sub);
}
}
std::pair<std::vector<const char*>, std::vector<const char*>>
split_dashdash(const std::vector<const char*>& args) {
auto dashdash = std::find_if(args.begin(), args.end(),
[](const char* arg) {
return strcmp(arg, "--") == 0;
});
std::vector<const char*> options{args.begin(), dashdash};
if (dashdash != args.end()) {
++dashdash;
}
std::vector<const char*> arguments{dashdash, args.end()};
return {std::move(options), std::move(arguments)};
}
static std::mutex g_str_vec_lock;
static std::vector<std::string> g_str_vec;
void clear_g_str_vec()
{
g_str_vec_lock.lock();
g_str_vec.clear();
g_str_vec_lock.unlock();
}
void env_to_vec(std::vector<const char*>& args, const char *name)
{
if (!name)
name = "CEPH_ARGS";
/*
* We can only populate str_vec once. Other threads could hold pointers into
* it, so clearing it out and replacing it is not currently safe.
*/
g_str_vec_lock.lock();
if (g_str_vec.empty()) {
char *p = getenv(name);
if (!p) {
g_str_vec_lock.unlock();
return;
}
get_str_vec(p, " ", g_str_vec);
}
std::vector<const char*> env;
for (const auto& s : g_str_vec) {
env.push_back(s.c_str());
}
g_str_vec_lock.unlock();
auto [env_options, env_arguments] = split_dashdash(env);
auto [options, arguments] = split_dashdash(args);
args.clear();
args.insert(args.end(), env_options.begin(), env_options.end());
args.insert(args.end(), options.begin(), options.end());
if (arguments.empty() && env_arguments.empty()) {
return;
}
args.push_back("--");
args.insert(args.end(), env_arguments.begin(), env_arguments.end());
args.insert(args.end(), arguments.begin(), arguments.end());
}
std::vector<const char*> argv_to_vec(int argc, const char* const * argv)
{
assert(argc > 0);
return {argv + 1, argv + argc};
}
void vec_to_argv(const char *argv0, std::vector<const char*>& args,
int *argc, const char ***argv)
{
*argv = (const char**)malloc(sizeof(char*) * (args.size() + 1));
if (!*argv)
throw std::bad_alloc();
*argc = 1;
(*argv)[0] = argv0;
for (unsigned i=0; i<args.size(); i++)
(*argv)[(*argc)++] = args[i];
}
void ceph_arg_value_type(const char * nextargstr, bool *bool_option, bool *bool_numeric)
{
bool is_numeric = true;
bool is_float = false;
bool is_option;
if (nextargstr == NULL) {
return;
}
if (strlen(nextargstr) < 2) {
is_option = false;
} else {
is_option = (nextargstr[0] == '-') && (nextargstr[1] == '-');
}
for (unsigned int i = 0; i < strlen(nextargstr); i++) {
if (!(nextargstr[i] >= '0' && nextargstr[i] <= '9')) {
// May be negative numeral value
if ((i == 0) && (strlen(nextargstr) >= 2)) {
if (nextargstr[0] == '-')
continue;
}
if ( (nextargstr[i] == '.') && (is_float == false) ) {
is_float = true;
continue;
}
is_numeric = false;
break;
}
}
// -<option>
if (nextargstr[0] == '-' && is_numeric == false) {
is_option = true;
}
*bool_option = is_option;
*bool_numeric = is_numeric;
return;
}
bool parse_ip_port_vec(const char *s, std::vector<entity_addrvec_t>& vec, int type)
{
// first split by [ ;], which are not valid for an addrvec
std::list<std::string> items;
get_str_list(s, " ;", items);
for (auto& i : items) {
const char *s = i.c_str();
while (*s) {
const char *end;
// try parsing as an addr
entity_addr_t a;
if (a.parse(s, &end, type)) {
vec.push_back(entity_addrvec_t(a));
s = end;
if (*s == ',') {
++s;
}
continue;
}
// ok, try parsing as an addrvec
entity_addrvec_t av;
if (!av.parse(s, &end)) {
return false;
}
vec.push_back(av);
s = end;
if (*s == ',') {
++s;
}
}
}
return true;
}
// The defaults for CephInitParameters
CephInitParameters::CephInitParameters(uint32_t module_type_)
: module_type(module_type_)
{
name.set(module_type, "admin");
}
static void dashes_to_underscores(const char *input, char *output)
{
char c = 0;
char *o = output;
const char *i = input;
// first two characters are copied as-is
*o = *i++;
if (*o++ == '\0')
return;
*o = *i++;
if (*o++ == '\0')
return;
for (; ((c = *i)); ++i) {
if (c == '=') {
strcpy(o, i);
return;
}
if (c == '-')
*o++ = '_';
else
*o++ = c;
}
*o++ = '\0';
}
/** Once we see a standalone double dash, '--', we should remove it and stop
* looking for any other options and flags. */
bool ceph_argparse_double_dash(std::vector<const char*> &args,
std::vector<const char*>::iterator &i)
{
if (strcmp(*i, "--") == 0) {
i = args.erase(i);
return true;
}
return false;
}
bool ceph_argparse_flag(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, ...)
{
const char *first = *i;
char tmp[strlen(first)+1];
dashes_to_underscores(first, tmp);
first = tmp;
va_list ap;
va_start(ap, i);
while (1) {
const char *a = va_arg(ap, char*);
if (a == NULL) {
va_end(ap);
return false;
}
char a2[strlen(a)+1];
dashes_to_underscores(a, a2);
if (strcmp(a2, first) == 0) {
i = args.erase(i);
va_end(ap);
return true;
}
}
}
static bool check_bool_str(const char *val, int *ret)
{
if ((strcmp(val, "true") == 0) || (strcmp(val, "1") == 0)) {
*ret = 1;
return true;
} else if ((strcmp(val, "false") == 0) || (strcmp(val, "0") == 0)) {
*ret = 0;
return true;
}
return false;
}
static bool va_ceph_argparse_binary_flag(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, int *ret,
std::ostream *oss, va_list ap)
{
const char *first = *i;
char tmp[strlen(first)+1];
dashes_to_underscores(first, tmp);
first = tmp;
// does this argument match any of the possibilities?
while (1) {
const char *a = va_arg(ap, char*);
if (a == NULL)
return false;
int strlen_a = strlen(a);
char a2[strlen_a+1];
dashes_to_underscores(a, a2);
if (strncmp(a2, first, strlen(a2)) == 0) {
if (first[strlen_a] == '=') {
i = args.erase(i);
const char *val = first + strlen_a + 1;
if (check_bool_str(val, ret)) {
return true;
}
if (oss) {
(*oss) << "Parse error parsing binary flag " << a
<< ". Expected true or false, but got '" << val << "'\n";
}
*ret = -EINVAL;
return true;
}
else if (first[strlen_a] == '\0') {
auto next = i+1;
if (next != args.end() &&
*next &&
(*next)[0] != '-') {
if (check_bool_str(*next, ret)) {
i = args.erase(i);
i = args.erase(i);
return true;
}
}
i = args.erase(i);
*ret = 1;
return true;
}
}
}
}
bool ceph_argparse_binary_flag(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, int *ret,
std::ostream *oss, ...)
{
bool r;
va_list ap;
va_start(ap, oss);
r = va_ceph_argparse_binary_flag(args, i, ret, oss, ap);
va_end(ap);
return r;
}
static int va_ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, std::string *ret,
std::ostream &oss, va_list ap)
{
const char *first = *i;
char tmp[strlen(first)+1];
dashes_to_underscores(first, tmp);
first = tmp;
// does this argument match any of the possibilities?
while (1) {
const char *a = va_arg(ap, char*);
if (a == NULL)
return 0;
int strlen_a = strlen(a);
char a2[strlen_a+1];
dashes_to_underscores(a, a2);
if (strncmp(a2, first, strlen(a2)) == 0) {
if (first[strlen_a] == '=') {
*ret = first + strlen_a + 1;
i = args.erase(i);
return 1;
}
else if (first[strlen_a] == '\0') {
// find second part (or not)
if (i+1 == args.end()) {
oss << "Option " << *i << " requires an argument." << std::endl;
i = args.erase(i);
return -EINVAL;
}
i = args.erase(i);
*ret = *i;
i = args.erase(i);
return 1;
}
}
}
}
template<class T>
bool ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, T *ret,
std::ostream &oss, ...)
{
int r;
va_list ap;
bool is_option = false;
bool is_numeric = true;
std::string str;
va_start(ap, oss);
r = va_ceph_argparse_witharg(args, i, &str, oss, ap);
va_end(ap);
if (r == 0) {
return false;
} else if (r < 0) {
return true;
}
ceph_arg_value_type(str.c_str(), &is_option, &is_numeric);
if ((is_option == true) || (is_numeric == false)) {
*ret = EXIT_FAILURE;
if (is_option == true) {
oss << "Missing option value";
} else {
oss << "The option value '" << str << "' is invalid";
}
return true;
}
std::string err;
T myret = strict_str_convert(str.c_str(), &err);
*ret = myret;
if (!err.empty()) {
oss << err;
}
return true;
}
template bool ceph_argparse_witharg<int>(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, int *ret,
std::ostream &oss, ...);
template bool ceph_argparse_witharg<long long>(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, long long *ret,
std::ostream &oss, ...);
template bool ceph_argparse_witharg<float>(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, float *ret,
std::ostream &oss, ...);
bool ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, std::string *ret,
std::ostream &oss, ...)
{
int r;
va_list ap;
va_start(ap, oss);
r = va_ceph_argparse_witharg(args, i, ret, oss, ap);
va_end(ap);
return r != 0;
}
bool ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, std::string *ret, ...)
{
int r;
va_list ap;
va_start(ap, ret);
r = va_ceph_argparse_witharg(args, i, ret, std::cerr, ap);
va_end(ap);
if (r < 0)
_exit(1);
return r != 0;
}
CephInitParameters ceph_argparse_early_args
(std::vector<const char*>& args, uint32_t module_type,
std::string *cluster, std::string *conf_file_list)
{
CephInitParameters iparams(module_type);
std::string val;
auto orig_args = args;
for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
if (strcmp(*i, "--") == 0) {
/* Normally we would use ceph_argparse_double_dash. However, in this
* function we *don't* want to remove the double dash, because later
* argument parses will still need to see it. */
break;
}
else if (ceph_argparse_flag(args, i, "--version", "-v", (char*)NULL)) {
std::cout << pretty_version_to_str() << std::endl;
_exit(0);
}
else if (ceph_argparse_witharg(args, i, &val, "--conf", "-c", (char*)NULL)) {
*conf_file_list = val;
}
else if (ceph_argparse_flag(args, i, "--no-config-file", (char*)NULL)) {
iparams.no_config_file = true;
}
else if (ceph_argparse_witharg(args, i, &val, "--cluster", (char*)NULL)) {
*cluster = val;
}
else if ((module_type != CEPH_ENTITY_TYPE_CLIENT) &&
(ceph_argparse_witharg(args, i, &val, "-i", (char*)NULL))) {
iparams.name.set_id(val);
}
else if (ceph_argparse_witharg(args, i, &val, "--id", "--user", (char*)NULL)) {
iparams.name.set_id(val);
}
else if (ceph_argparse_witharg(args, i, &val, "--name", "-n", (char*)NULL)) {
if (!iparams.name.from_str(val)) {
std::cerr << "error parsing '" << val << "': expected string of the form TYPE.ID, "
<< "valid types are: " << EntityName::get_valid_types_as_str()
<< std::endl;
_exit(1);
}
}
else if (ceph_argparse_flag(args, i, "--show_args", (char*)NULL)) {
std::cout << "args: ";
for (std::vector<const char *>::iterator ci = orig_args.begin(); ci != orig_args.end(); ++ci) {
if (ci != orig_args.begin())
std::cout << " ";
std::cout << *ci;
}
std::cout << std::endl;
}
else {
// ignore
++i;
}
}
return iparams;
}
static void generic_usage(bool is_server)
{
std::cout <<
" --conf/-c FILE read configuration from the given configuration file" << std::endl <<
(is_server ?
" --id/-i ID set ID portion of my name" :
" --id ID set ID portion of my name") << std::endl <<
" --name/-n TYPE.ID set name" << std::endl <<
" --cluster NAME set cluster name (default: ceph)" << std::endl <<
" --setuser USER set uid to user or uid (and gid to user's gid)" << std::endl <<
" --setgroup GROUP set gid to group or gid" << std::endl <<
" --version show version and quit" << std::endl
<< std::endl;
if (is_server) {
std::cout <<
" -d run in foreground, log to stderr" << std::endl <<
" -f run in foreground, log to usual location" << std::endl <<
std::endl <<
" --debug_ms N set message debug level (e.g. 1)" << std::endl;
}
std::cout.flush();
}
bool ceph_argparse_need_usage(const std::vector<const char*>& args)
{
if (args.empty()) {
return true;
}
for (auto a : args) {
if (strcmp(a, "-h") == 0 ||
strcmp(a, "--help") == 0) {
return true;
}
}
return false;
}
void generic_server_usage()
{
generic_usage(true);
}
void generic_client_usage()
{
generic_usage(false);
}
| 14,874 | 23.874582 | 101 | cc |
null | ceph-main/src/common/ceph_argparse.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_ARGPARSE_H
#define CEPH_ARGPARSE_H
/*
* Ceph argument parsing library
*
* We probably should eventually replace this with something standard like popt.
* Until we do that, though, this file is the place for argv parsing
* stuff to live.
*/
#include <string>
#include <vector>
#include "common/entity_name.h"
#include "include/encoding.h"
/////////////////////// Types ///////////////////////
class CephInitParameters
{
public:
explicit CephInitParameters(uint32_t module_type_);
uint32_t module_type;
EntityName name;
bool no_config_file = false;
void encode(ceph::buffer::list& bl) const {
ENCODE_START(1, 1, bl);
encode(module_type, bl);
encode(name, bl);
encode(no_config_file, bl);
ENCODE_FINISH(bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
DECODE_START(1, bl);
decode(module_type, bl);
decode(name, bl);
decode(no_config_file, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(CephInitParameters)
/////////////////////// Functions ///////////////////////
extern void string_to_vec(std::vector<std::string>& args, std::string argstr);
extern void clear_g_str_vec();
extern void env_to_vec(std::vector<const char*>& args, const char *name=nullptr);
extern std::vector<const char*> argv_to_vec(int argc, const char* const * argv);
extern void vec_to_argv(const char *argv0, std::vector<const char*>& args,
int *argc, const char ***argv);
extern bool parse_ip_port_vec(const char *s, std::vector<entity_addrvec_t>& vec,
int type=0);
bool ceph_argparse_double_dash(std::vector<const char*> &args,
std::vector<const char*>::iterator &i);
bool ceph_argparse_flag(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, ...);
bool ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, std::string *ret,
std::ostream &oss, ...);
bool ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, std::string *ret, ...);
template<class T>
bool ceph_argparse_witharg(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, T *ret,
std::ostream &oss, ...);
bool ceph_argparse_binary_flag(std::vector<const char*> &args,
std::vector<const char*>::iterator &i, int *ret,
std::ostream *oss, ...);
extern CephInitParameters ceph_argparse_early_args
(std::vector<const char*>& args, uint32_t module_type,
std::string *cluster, std::string *conf_file_list);
extern bool ceph_argparse_need_usage(const std::vector<const char*>& args);
extern void generic_server_usage();
extern void generic_client_usage();
#endif
| 3,045 | 31.752688 | 81 | h |
null | ceph-main/src/common/ceph_atomic.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <atomic>
// What and why
// ============
//
// ceph::atomic – thin wrapper to differentiate behavior of atomics.
//
// Not all users of the common truly need costly atomic operations to
// synchronize data between CPUs and threads. Some, like crimson-osd,
// stick to shared-nothing approach. Enforcing issue of atomics in
// such cases is wasteful – on x86 any locked instruction works actually
// like a full memory barrier stalling execution till CPU's store and
// load buffers are drained.
#if defined(WITH_SEASTAR) && !defined(WITH_BLUESTORE)
#include <type_traits>
namespace ceph {
template <class T>
class dummy_atomic {
T value;
public:
dummy_atomic() = default;
dummy_atomic(const dummy_atomic&) = delete;
dummy_atomic(T value) : value(std::move(value)) {
}
bool is_lock_free() const noexcept {
return true;
}
void store(T desired, std::memory_order) noexcept {
value = std::move(desired);
}
T load(std::memory_order = std::memory_order_seq_cst) const noexcept {
return value;
}
T operator=(T desired) noexcept {
value = std::move(desired);
return *this;
}
operator T() const noexcept {
return value;
}
// We need to differentiate with SFINAE as std::atomic offers beefier
// interface for integral types.
template<class TT=T>
std::enable_if_t<!std::is_enum_v<TT> && std::is_integral_v<TT>, TT> operator++() {
return ++value;
}
template<class TT=T>
std::enable_if_t<!std::is_enum_v<TT> && std::is_integral_v<TT>, TT> operator++(int) {
return value++;
}
template<class TT=T>
std::enable_if_t<!std::is_enum_v<TT> && std::is_integral_v<TT>, TT> operator--() {
return --value;
}
template<class TT=T>
std::enable_if_t<!std::is_enum_v<TT> && std::is_integral_v<TT>, TT> operator--(int) {
return value--;
}
template<class TT=T>
std::enable_if_t<!std::is_enum_v<TT> && std::is_integral_v<TT>, TT> operator+=(const dummy_atomic& b) {
value += b;
return value;
}
template<class TT=T>
std::enable_if_t<!std::is_enum_v<TT> && std::is_integral_v<TT>, TT> operator-=(const dummy_atomic& b) {
value -= b;
return value;
}
static constexpr bool is_always_lock_free = true;
};
template <class T> using atomic = dummy_atomic<T>;
} // namespace ceph
#else // WITH_SEASTAR
namespace ceph {
template <class T> using atomic = ::std::atomic<T>;
} // namespace ceph
#endif // WITH_SEASTAR
| 2,650 | 27.202128 | 107 | h |
null | ceph-main/src/common/ceph_context.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/ceph_context.h"
#include <mutex>
#include <iostream>
#include <pthread.h>
#include <boost/algorithm/string.hpp>
#include "include/common_fwd.h"
#include "include/mempool.h"
#include "include/stringify.h"
#include "common/admin_socket.h"
#include "common/code_environment.h"
#include "common/ceph_mutex.h"
#include "common/debug.h"
#include "common/config.h"
#include "common/ceph_crypto.h"
#include "common/hostname.h"
#include "common/HeartbeatMap.h"
#include "common/errno.h"
#include "common/Graylog.h"
#ifdef CEPH_DEBUG_MUTEX
#include "common/lockdep.h"
#endif
#include "log/Log.h"
#include "auth/Crypto.h"
#include "include/str_list.h"
#include "common/config.h"
#include "common/config_obs.h"
#include "common/PluginRegistry.h"
#include "common/valgrind.h"
#include "include/spinlock.h"
#if !(defined(WITH_SEASTAR) && !defined(WITH_ALIEN))
#include "mon/MonMap.h"
#endif
// for CINIT_FLAGS
#include "common/common_init.h"
#include <iostream>
#include <pthread.h>
using namespace std::literals;
using ceph::bufferlist;
using ceph::HeartbeatMap;
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
namespace crimson::common {
CephContext::CephContext()
: _conf{crimson::common::local_conf()},
_perf_counters_collection{crimson::common::local_perf_coll()},
_crypto_random{std::make_unique<CryptoRandom>()}
{}
// define the dtor in .cc as CryptoRandom is an incomplete type in the header
CephContext::~CephContext()
{}
uint32_t CephContext::get_module_type() const
{
return CEPH_ENTITY_TYPE_OSD;
}
CryptoRandom* CephContext::random() const
{
return _crypto_random.get();
}
CephContext* CephContext::get()
{
++nref;
return this;
}
void CephContext::put()
{
if (--nref == 0) {
delete this;
}
}
PerfCountersCollectionImpl* CephContext::get_perfcounters_collection()
{
return _perf_counters_collection.get_perf_collection();
}
}
#else // WITH_SEASTAR
namespace {
#ifdef CEPH_DEBUG_MUTEX
class LockdepObs : public md_config_obs_t {
public:
explicit LockdepObs(CephContext *cct)
: m_cct(cct), m_registered(false), lock(ceph::make_mutex("lock_dep_obs")) {
}
~LockdepObs() override {
if (m_registered) {
lockdep_unregister_ceph_context(m_cct);
}
}
const char** get_tracked_conf_keys() const override {
static const char *KEYS[] = {"lockdep", NULL};
return KEYS;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override {
std::unique_lock locker(lock);
if (conf->lockdep && !m_registered) {
lockdep_register_ceph_context(m_cct);
m_registered = true;
} else if (!conf->lockdep && m_registered) {
lockdep_unregister_ceph_context(m_cct);
m_registered = false;
}
}
private:
CephContext *m_cct;
bool m_registered;
ceph::mutex lock;
};
#endif // CEPH_DEBUG_MUTEX
class MempoolObs : public md_config_obs_t,
public AdminSocketHook {
CephContext *cct;
ceph::mutex lock;
public:
explicit MempoolObs(CephContext *cct)
: cct(cct), lock(ceph::make_mutex("mem_pool_obs")) {
cct->_conf.add_observer(this);
int r = cct->get_admin_socket()->register_command(
"dump_mempools",
this,
"get mempool stats");
ceph_assert(r == 0);
}
~MempoolObs() override {
cct->_conf.remove_observer(this);
cct->get_admin_socket()->unregister_commands(this);
}
// md_config_obs_t
const char** get_tracked_conf_keys() const override {
static const char *KEYS[] = {
"mempool_debug",
NULL
};
return KEYS;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override {
std::unique_lock locker(lock);
if (changed.count("mempool_debug")) {
mempool::set_debug_mode(cct->_conf->mempool_debug);
}
}
// AdminSocketHook
int call(std::string_view command, const cmdmap_t& cmdmap,
const bufferlist& inbl,
ceph::Formatter *f,
std::ostream& errss,
bufferlist& out) override {
if (command == "dump_mempools") {
f->open_object_section("mempools");
mempool::dump(f);
f->close_section();
return 0;
}
return -ENOSYS;
}
};
} // anonymous namespace
namespace ceph::common {
class CephContextServiceThread : public Thread
{
public:
explicit CephContextServiceThread(CephContext *cct)
: _reopen_logs(false), _exit_thread(false), _cct(cct)
{
}
~CephContextServiceThread() override {}
void *entry() override
{
while (1) {
std::unique_lock l(_lock);
if (_exit_thread) {
break;
}
if (_cct->_conf->heartbeat_interval) {
auto interval = ceph::make_timespan(_cct->_conf->heartbeat_interval);
_cond.wait_for(l, interval);
} else
_cond.wait(l);
if (_exit_thread) {
break;
}
if (_reopen_logs) {
_cct->_log->reopen_log_file();
_reopen_logs = false;
}
_cct->_heartbeat_map->check_touch_file();
// refresh the perf coutners
_cct->_refresh_perf_values();
}
return NULL;
}
void reopen_logs()
{
std::lock_guard l(_lock);
_reopen_logs = true;
_cond.notify_all();
}
void exit_thread()
{
std::lock_guard l(_lock);
_exit_thread = true;
_cond.notify_all();
}
private:
ceph::mutex _lock = ceph::make_mutex("CephContextServiceThread::_lock");
ceph::condition_variable _cond;
bool _reopen_logs;
bool _exit_thread;
CephContext *_cct;
};
}
/**
* observe logging config changes
*
* The logging subsystem sits below most of the ceph code, including
* the config subsystem, to keep it simple and self-contained. Feed
* logging-related config changes to the log.
*/
class LogObs : public md_config_obs_t {
ceph::logging::Log *log;
ceph::mutex lock;
public:
explicit LogObs(ceph::logging::Log *l)
: log(l), lock(ceph::make_mutex("log_obs")) {
}
const char** get_tracked_conf_keys() const override {
static const char *KEYS[] = {
"log_file",
"log_max_new",
"log_max_recent",
"log_to_file",
"log_to_syslog",
"err_to_syslog",
"log_stderr_prefix",
"log_to_stderr",
"err_to_stderr",
"log_to_graylog",
"err_to_graylog",
"log_graylog_host",
"log_graylog_port",
"log_to_journald",
"err_to_journald",
"log_coarse_timestamps",
"fsid",
"host",
NULL
};
return KEYS;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override {
std::unique_lock locker(lock);
// stderr
if (changed.count("log_to_stderr") || changed.count("err_to_stderr")) {
int l = conf->log_to_stderr ? 99 : (conf->err_to_stderr ? -1 : -2);
log->set_stderr_level(l, l);
}
// syslog
if (changed.count("log_to_syslog")) {
int l = conf->log_to_syslog ? 99 : (conf->err_to_syslog ? -1 : -2);
log->set_syslog_level(l, l);
}
// file
if (changed.count("log_file") ||
changed.count("log_to_file")) {
if (conf->log_to_file) {
log->set_log_file(conf->log_file);
} else {
log->set_log_file({});
}
log->reopen_log_file();
}
if (changed.count("log_stderr_prefix")) {
log->set_log_stderr_prefix(conf.get_val<std::string>("log_stderr_prefix"));
}
if (changed.count("log_max_new")) {
log->set_max_new(conf->log_max_new);
}
if (changed.count("log_max_recent")) {
log->set_max_recent(conf->log_max_recent);
}
// graylog
if (changed.count("log_to_graylog") || changed.count("err_to_graylog")) {
int l = conf->log_to_graylog ? 99 : (conf->err_to_graylog ? -1 : -2);
log->set_graylog_level(l, l);
if (conf->log_to_graylog || conf->err_to_graylog) {
log->start_graylog(conf->host, conf.get_val<uuid_d>("fsid"));
} else if (! (conf->log_to_graylog && conf->err_to_graylog)) {
log->stop_graylog();
}
}
if (log->graylog() && (changed.count("log_graylog_host") || changed.count("log_graylog_port"))) {
log->graylog()->set_destination(conf->log_graylog_host, conf->log_graylog_port);
}
// journald
if (changed.count("log_to_journald") || changed.count("err_to_journald")) {
int l = conf.get_val<bool>("log_to_journald") ? 99 : (conf.get_val<bool>("err_to_journald") ? -1 : -2);
log->set_journald_level(l, l);
if (l > -2) {
log->start_journald_logger();
} else {
log->stop_journald_logger();
}
}
if (changed.find("log_coarse_timestamps") != changed.end()) {
log->set_coarse_timestamps(conf.get_val<bool>("log_coarse_timestamps"));
}
// metadata
if (log->graylog() && changed.count("host")) {
log->graylog()->set_hostname(conf->host);
}
if (log->graylog() && changed.count("fsid")) {
log->graylog()->set_fsid(conf.get_val<uuid_d>("fsid"));
}
}
};
namespace ceph::common {
// cct config watcher
class CephContextObs : public md_config_obs_t {
CephContext *cct;
public:
explicit CephContextObs(CephContext *cct) : cct(cct) {}
const char** get_tracked_conf_keys() const override {
static const char *KEYS[] = {
"enable_experimental_unrecoverable_data_corrupting_features",
"crush_location",
"container_image", // just so we don't hear complaints about it!
NULL
};
return KEYS;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override {
if (changed.count(
"enable_experimental_unrecoverable_data_corrupting_features")) {
std::lock_guard lg(cct->_feature_lock);
cct->_experimental_features.clear();
auto add_experimental_feature = [this] (auto feature) {
cct->_experimental_features.emplace(std::string{feature});
};
for_each_substr(conf->enable_experimental_unrecoverable_data_corrupting_features,
";,= \t", add_experimental_feature);
if (getenv("CEPH_DEV") == NULL) {
if (!cct->_experimental_features.empty()) {
if (cct->_experimental_features.count("*")) {
lderr(cct) << "WARNING: all dangerous and experimental features are enabled." << dendl;
} else {
lderr(cct) << "WARNING: the following dangerous and experimental features are enabled: "
<< cct->_experimental_features << dendl;
}
}
}
}
if (changed.count("crush_location")) {
cct->crush_location.update_from_conf();
}
}
};
// perfcounter hooks
class CephContextHook : public AdminSocketHook {
CephContext *m_cct;
public:
explicit CephContextHook(CephContext *cct) : m_cct(cct) {}
int call(std::string_view command, const cmdmap_t& cmdmap,
const bufferlist& inbl,
Formatter *f,
std::ostream& errss,
bufferlist& out) override {
try {
return m_cct->do_command(command, cmdmap, f, errss, &out);
} catch (const bad_cmd_get& e) {
return -EINVAL;
}
}
};
bool CephContext::check_experimental_feature_enabled(const std::string& feat)
{
std::stringstream message;
bool enabled = check_experimental_feature_enabled(feat, &message);
lderr(this) << message.str() << dendl;
return enabled;
}
bool CephContext::check_experimental_feature_enabled(const std::string& feat,
std::ostream *message)
{
std::unique_lock<ceph::spinlock> lg(_feature_lock);
bool enabled = (_experimental_features.count(feat) ||
_experimental_features.count("*"));
if (enabled) {
(*message) << "WARNING: experimental feature '" << feat << "' is enabled\n";
(*message) << "Please be aware that this feature is experimental, untested,\n";
(*message) << "unsupported, and may result in data corruption, data loss,\n";
(*message) << "and/or irreparable damage to your cluster. Do not use\n";
(*message) << "feature with important data.\n";
} else {
(*message) << "*** experimental feature '" << feat << "' is not enabled ***\n";
(*message) << "This feature is marked as experimental, which means it\n";
(*message) << " - is untested\n";
(*message) << " - is unsupported\n";
(*message) << " - may corrupt your data\n";
(*message) << " - may break your cluster is an unrecoverable fashion\n";
(*message) << "To enable this feature, add this to your ceph.conf:\n";
(*message) << " enable experimental unrecoverable data corrupting features = " << feat << "\n";
}
return enabled;
}
int CephContext::do_command(std::string_view command, const cmdmap_t& cmdmap,
Formatter *f,
std::ostream& ss,
bufferlist *out)
{
try {
return _do_command(command, cmdmap, f, ss, out);
} catch (const bad_cmd_get& e) {
ss << e.what();
return -EINVAL;
}
}
#pragma GCC push_options
#pragma GCC optimize ("O0")
static void leak_some_memory() {
volatile char *foo = new char[1234];
(void)foo;
}
#pragma GCC pop_options
int CephContext::_do_command(
std::string_view command, const cmdmap_t& cmdmap,
Formatter *f,
std::ostream& ss,
bufferlist *out)
{
int r = 0;
lgeneric_dout(this, 1) << "do_command '" << command << "' '" << cmdmap << "'"
<< dendl;
ceph_assert_always(!(command == "assert" && _conf->debug_asok_assert_abort));
if (command == "abort") {
if (_conf->debug_asok_assert_abort) {
ceph_abort();
} else {
return -EPERM;
}
}
if (command == "leak_some_memory") {
leak_some_memory();
}
else if (command == "perfcounters_dump" || command == "1" ||
command == "perf dump") {
std::string logger;
std::string counter;
cmd_getval(cmdmap, "logger", logger);
cmd_getval(cmdmap, "counter", counter);
_perf_counters_collection->dump_formatted(f, false, false, logger, counter);
}
else if (command == "perfcounters_schema" || command == "2" ||
command == "perf schema") {
_perf_counters_collection->dump_formatted(f, true, false);
}
else if (command == "counter dump") {
_perf_counters_collection->dump_formatted(f, false, true);
}
else if (command == "counter schema") {
_perf_counters_collection->dump_formatted(f, true, true);
}
else if (command == "perf histogram dump") {
std::string logger;
std::string counter;
cmd_getval(cmdmap, "logger", logger);
cmd_getval(cmdmap, "counter", counter);
_perf_counters_collection->dump_formatted_histograms(f, false, logger,
counter);
}
else if (command == "perf histogram schema") {
_perf_counters_collection->dump_formatted_histograms(f, true);
}
else if (command == "perf reset") {
std::string var;
std::string section(command);
f->open_object_section(section.c_str());
if (!cmd_getval(cmdmap, "var", var)) {
f->dump_string("error", "syntax error: 'perf reset <var>'");
} else {
if(!_perf_counters_collection->reset(var))
f->dump_stream("error") << "Not find: " << var;
else
f->dump_string("success", std::string(command) + ' ' + var);
}
f->close_section();
}
else {
std::string section(command);
boost::replace_all(section, " ", "_");
f->open_object_section(section.c_str());
if (command == "config show") {
_conf.show_config(f);
}
else if (command == "config unset") {
std::string var;
if (!(cmd_getval(cmdmap, "var", var))) {
r = -EINVAL;
} else {
r = _conf.rm_val(var.c_str());
if (r < 0 && r != -ENOENT) {
ss << "error unsetting '" << var << "': "
<< cpp_strerror(r);
} else {
_conf.apply_changes(&ss);
r = 0;
}
}
}
else if (command == "config set") {
std::string var;
std::vector<std::string> val;
if (!(cmd_getval(cmdmap, "var", var)) ||
!(cmd_getval(cmdmap, "val", val))) {
r = -EINVAL;
} else {
// val may be multiple words
auto valstr = str_join(val, " ");
r = _conf.set_val(var.c_str(), valstr.c_str());
if (r < 0) {
ss << "error setting '" << var << "' to '" << valstr << "': "
<< cpp_strerror(r);
} else {
std::stringstream ss;
_conf.apply_changes(&ss);
f->dump_string("success", ss.str());
}
}
} else if (command == "config get") {
std::string var;
if (!cmd_getval(cmdmap, "var", var)) {
r = -EINVAL;
} else {
char buf[4096];
// FIPS zeroization audit 20191115: this memset is not security related.
memset(buf, 0, sizeof(buf));
char *tmp = buf;
r = _conf.get_val(var.c_str(), &tmp, sizeof(buf));
if (r < 0) {
ss << "error getting '" << var << "': " << cpp_strerror(r);
} else {
f->dump_string(var.c_str(), buf);
}
}
} else if (command == "config help") {
std::string var;
if (cmd_getval(cmdmap, "var", var)) {
// Output a single one
std::string key = ConfFile::normalize_key_name(var);
auto schema = _conf.get_schema(key);
if (!schema) {
ss << "Setting not found: '" << key << "'";
r = -ENOENT;
} else {
f->dump_object("option", *schema);
}
} else {
// Output all
f->open_array_section("options");
for (const auto &option : ceph_options) {
f->dump_object("option", option);
}
f->close_section();
}
} else if (command == "config diff") {
f->open_object_section("diff");
_conf.diff(f);
f->close_section(); // unknown
} else if (command == "config diff get") {
std::string setting;
f->open_object_section("diff");
_conf.diff(f, setting);
f->close_section(); // unknown
}
else if (command == "injectargs") {
std::vector<std::string> argsvec;
cmd_getval(cmdmap, "injected_args", argsvec);
if (!argsvec.empty()) {
auto args = joinify<std::string>(argsvec.begin(), argsvec.end(), " ");
r = _conf.injectargs(args, &ss);
}
}
else if (command == "log flush") {
_log->flush();
}
else if (command == "log dump") {
_log->dump_recent();
}
else if (command == "log reopen") {
_log->reopen_log_file();
}
else {
ceph_abort_msg("registered under wrong command?");
}
f->close_section();
}
lgeneric_dout(this, 1) << "do_command '" << command << "' '" << cmdmap
<< "' result is " << out->length() << " bytes" << dendl;
return r;
}
CephContext::CephContext(uint32_t module_type_,
enum code_environment_t code_env,
int init_flags_)
: CephContext(module_type_, create_options{code_env, init_flags_, nullptr})
{}
CephContext::CephContext(uint32_t module_type_,
const create_options& options)
: nref(1),
_conf{options.code_env == CODE_ENVIRONMENT_DAEMON},
_log(NULL),
_module_type(module_type_),
_init_flags(options.init_flags),
_set_uid(0),
_set_gid(0),
_set_uid_string(),
_set_gid_string(),
_crypto_inited(0),
_service_thread(NULL),
_log_obs(NULL),
_admin_socket(NULL),
_perf_counters_collection(NULL),
_perf_counters_conf_obs(NULL),
_heartbeat_map(NULL),
_crypto_none(NULL),
_crypto_aes(NULL),
_plugin_registry(NULL),
#ifdef CEPH_DEBUG_MUTEX
_lockdep_obs(NULL),
#endif
crush_location(this)
{
if (options.create_log) {
_log = options.create_log(&_conf->subsys);
} else {
_log = new ceph::logging::Log(&_conf->subsys);
}
_log_obs = new LogObs(_log);
_conf.add_observer(_log_obs);
_cct_obs = new CephContextObs(this);
_conf.add_observer(_cct_obs);
#ifdef CEPH_DEBUG_MUTEX
_lockdep_obs = new LockdepObs(this);
_conf.add_observer(_lockdep_obs);
#endif
_perf_counters_collection = new PerfCountersCollection(this);
_admin_socket = new AdminSocket(this);
_heartbeat_map = new HeartbeatMap(this);
_plugin_registry = new PluginRegistry(this);
_admin_hook = new CephContextHook(this);
_admin_socket->register_command("assert", _admin_hook, "");
_admin_socket->register_command("abort", _admin_hook, "");
_admin_socket->register_command("leak_some_memory", _admin_hook, "");
_admin_socket->register_command("perfcounters_dump", _admin_hook, "");
_admin_socket->register_command("1", _admin_hook, "");
_admin_socket->register_command("perf dump name=logger,type=CephString,req=false name=counter,type=CephString,req=false", _admin_hook, "dump non-labeled counters and their values");
_admin_socket->register_command("perfcounters_schema", _admin_hook, "");
_admin_socket->register_command("perf histogram dump name=logger,type=CephString,req=false name=counter,type=CephString,req=false", _admin_hook, "dump perf histogram values");
_admin_socket->register_command("2", _admin_hook, "");
_admin_socket->register_command("perf schema", _admin_hook, "dump non-labeled counters schemas");
_admin_socket->register_command("counter dump", _admin_hook, "dump all labeled and non-labeled counters and their values");
_admin_socket->register_command("counter schema", _admin_hook, "dump all labeled and non-labeled counters schemas");
_admin_socket->register_command("perf histogram schema", _admin_hook, "dump perf histogram schema");
_admin_socket->register_command("perf reset name=var,type=CephString", _admin_hook, "perf reset <name>: perf reset all or one perfcounter name");
_admin_socket->register_command("config show", _admin_hook, "dump current config settings");
_admin_socket->register_command("config help name=var,type=CephString,req=false", _admin_hook, "get config setting schema and descriptions");
_admin_socket->register_command("config set name=var,type=CephString name=val,type=CephString,n=N", _admin_hook, "config set <field> <val> [<val> ...]: set a config variable");
_admin_socket->register_command("config unset name=var,type=CephString", _admin_hook, "config unset <field>: unset a config variable");
_admin_socket->register_command("config get name=var,type=CephString", _admin_hook, "config get <field>: get the config value");
_admin_socket->register_command(
"config diff", _admin_hook,
"dump diff of current config and default config");
_admin_socket->register_command(
"config diff get name=var,type=CephString", _admin_hook,
"dump diff get <field>: dump diff of current and default config setting <field>");
_admin_socket->register_command("injectargs name=injected_args,type=CephString,n=N", _admin_hook, "inject configuration arguments into running daemon"),
_admin_socket->register_command("log flush", _admin_hook, "flush log entries to log file");
_admin_socket->register_command("log dump", _admin_hook, "dump recent log entries to log file");
_admin_socket->register_command("log reopen", _admin_hook, "reopen log file");
_crypto_none = CryptoHandler::create(CEPH_CRYPTO_NONE);
_crypto_aes = CryptoHandler::create(CEPH_CRYPTO_AES);
_crypto_random.reset(new CryptoRandom());
lookup_or_create_singleton_object<MempoolObs>("mempool_obs", false, this);
}
CephContext::~CephContext()
{
associated_objs.clear();
join_service_thread();
if (_cct_perf) {
_perf_counters_collection->remove(_cct_perf);
delete _cct_perf;
_cct_perf = NULL;
}
delete _plugin_registry;
_admin_socket->unregister_commands(_admin_hook);
delete _admin_hook;
delete _admin_socket;
delete _heartbeat_map;
delete _perf_counters_collection;
_perf_counters_collection = NULL;
delete _perf_counters_conf_obs;
_perf_counters_conf_obs = NULL;
_conf.remove_observer(_log_obs);
delete _log_obs;
_log_obs = NULL;
_conf.remove_observer(_cct_obs);
delete _cct_obs;
_cct_obs = NULL;
#ifdef CEPH_DEBUG_MUTEX
_conf.remove_observer(_lockdep_obs);
delete _lockdep_obs;
_lockdep_obs = NULL;
#endif
_log->stop();
delete _log;
_log = NULL;
delete _crypto_none;
delete _crypto_aes;
if (_crypto_inited > 0) {
ceph_assert(_crypto_inited == 1); // or else someone explicitly did
// init but not shutdown
shutdown_crypto();
}
}
void CephContext::put() {
if (--nref == 0) {
ANNOTATE_HAPPENS_AFTER(&nref);
ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&nref);
if (g_ceph_context == this)
g_ceph_context = nullptr;
delete this;
} else {
ANNOTATE_HAPPENS_BEFORE(&nref);
}
}
void CephContext::init_crypto()
{
if (_crypto_inited++ == 0) {
TOPNSPC::crypto::init();
}
}
void CephContext::shutdown_crypto()
{
if (--_crypto_inited == 0) {
TOPNSPC::crypto::shutdown(g_code_env == CODE_ENVIRONMENT_LIBRARY);
}
}
void CephContext::start_service_thread()
{
{
std::lock_guard lg(_service_thread_lock);
if (_service_thread) {
return;
}
_service_thread = new CephContextServiceThread(this);
_service_thread->create("service");
}
if (!(get_init_flags() & CINIT_FLAG_NO_CCT_PERF_COUNTERS))
_enable_perf_counter();
// make logs flush on_exit()
if (_conf->log_flush_on_exit)
_log->set_flush_on_exit();
// Trigger callbacks on any config observers that were waiting for
// it to become safe to start threads.
_conf.set_safe_to_start_threads();
_conf.call_all_observers();
// start admin socket
if (_conf->admin_socket.length())
_admin_socket->init(_conf->admin_socket);
}
void CephContext::reopen_logs()
{
std::lock_guard lg(_service_thread_lock);
if (_service_thread)
_service_thread->reopen_logs();
}
void CephContext::join_service_thread()
{
std::unique_lock<ceph::spinlock> lg(_service_thread_lock);
CephContextServiceThread *thread = _service_thread;
if (!thread) {
return;
}
_service_thread = NULL;
lg.unlock();
thread->exit_thread();
thread->join();
delete thread;
if (!(get_init_flags() & CINIT_FLAG_NO_CCT_PERF_COUNTERS))
_disable_perf_counter();
}
uint32_t CephContext::get_module_type() const
{
return _module_type;
}
void CephContext::set_init_flags(int flags)
{
_init_flags = flags;
}
int CephContext::get_init_flags() const
{
return _init_flags;
}
PerfCountersCollection *CephContext::get_perfcounters_collection()
{
return _perf_counters_collection;
}
void CephContext::_enable_perf_counter()
{
assert(!_cct_perf);
PerfCountersBuilder plb(this, "cct", l_cct_first, l_cct_last);
plb.add_u64(l_cct_total_workers, "total_workers", "Total workers");
plb.add_u64(l_cct_unhealthy_workers, "unhealthy_workers", "Unhealthy workers");
_cct_perf = plb.create_perf_counters();
_perf_counters_collection->add(_cct_perf);
assert(_mempool_perf_names.empty());
assert(_mempool_perf_descriptions.empty());
_mempool_perf_names.reserve(mempool::num_pools * 2);
_mempool_perf_descriptions.reserve(mempool::num_pools * 2);
for (unsigned i = 0; i < mempool::num_pools; ++i) {
std::string n = mempool::get_pool_name(mempool::pool_index_t(i));
_mempool_perf_names.push_back(n + "_bytes"s);
_mempool_perf_descriptions.push_back(
"mempool "s + n + " total bytes");
_mempool_perf_names.push_back(n + "_items"s);
_mempool_perf_descriptions.push_back(
"mempool "s + n + " total items"s);
}
PerfCountersBuilder plb2(this, "mempool", l_mempool_first,
l_mempool_first + 1 + 2*mempool::num_pools);
unsigned l = l_mempool_first + 1;
for (unsigned i = 0; i < mempool::num_pools; ++i) {
plb2.add_u64(l++, _mempool_perf_names[i*2].c_str(),
_mempool_perf_descriptions[i*2].c_str());
plb2.add_u64(l++, _mempool_perf_names[i*2+1].c_str(),
_mempool_perf_descriptions[i*2+1].c_str());
}
_mempool_perf = plb2.create_perf_counters();
_perf_counters_collection->add(_mempool_perf);
}
void CephContext::_disable_perf_counter()
{
if (!_cct_perf) {
return;
}
_perf_counters_collection->remove(_cct_perf);
delete _cct_perf;
_cct_perf = nullptr;
_perf_counters_collection->remove(_mempool_perf);
delete _mempool_perf;
_mempool_perf = nullptr;
_mempool_perf_names.clear();
_mempool_perf_descriptions.clear();
}
void CephContext::_refresh_perf_values()
{
if (_cct_perf) {
_cct_perf->set(l_cct_total_workers, _heartbeat_map->get_total_workers());
_cct_perf->set(l_cct_unhealthy_workers, _heartbeat_map->get_unhealthy_workers());
}
unsigned l = l_mempool_first + 1;
for (unsigned i = 0; i < mempool::num_pools; ++i) {
mempool::pool_t& p = mempool::get_pool(mempool::pool_index_t(i));
_mempool_perf->set(l++, p.allocated_bytes());
_mempool_perf->set(l++, p.allocated_items());
}
}
AdminSocket *CephContext::get_admin_socket()
{
return _admin_socket;
}
CryptoHandler *CephContext::get_crypto_handler(int type)
{
switch (type) {
case CEPH_CRYPTO_NONE:
return _crypto_none;
case CEPH_CRYPTO_AES:
return _crypto_aes;
default:
return NULL;
}
}
void CephContext::notify_pre_fork()
{
{
std::lock_guard lg(_fork_watchers_lock);
for (auto &&t : _fork_watchers) {
t->handle_pre_fork();
}
}
{
// note: we don't hold a lock here, but we assume we are idle at
// fork time, which happens during process init and startup.
auto i = associated_objs.begin();
while (i != associated_objs.end()) {
if (associated_objs_drop_on_fork.count(i->first.first)) {
i = associated_objs.erase(i);
} else {
++i;
}
}
associated_objs_drop_on_fork.clear();
}
}
void CephContext::notify_post_fork()
{
ceph::spin_unlock(&_fork_watchers_lock);
for (auto &&t : _fork_watchers)
t->handle_post_fork();
}
void CephContext::set_mon_addrs(const MonMap& mm) {
std::vector<entity_addrvec_t> mon_addrs;
for (auto& i : mm.mon_info) {
mon_addrs.push_back(i.second.public_addrs);
}
set_mon_addrs(mon_addrs);
}
}
#endif // WITH_SEASTAR
| 30,193 | 27.484906 | 183 | cc |
null | ceph-main/src/common/ceph_context.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_CEPHCONTEXT_H
#define CEPH_CEPHCONTEXT_H
#include <atomic>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <string_view>
#include <typeinfo>
#include <typeindex>
#include <boost/intrusive_ptr.hpp>
#include "include/any.h"
#include "include/common_fwd.h"
#include "include/compat.h"
#include "common/cmdparse.h"
#include "common/code_environment.h"
#include "msg/msg_types.h"
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
#include "crimson/common/config_proxy.h"
#include "crimson/common/perf_counters_collection.h"
#else
#include "common/config_proxy.h"
#include "include/spinlock.h"
#include "common/perf_counters_collection.h"
#endif
#include "crush/CrushLocation.h"
class AdminSocket;
class CryptoHandler;
class CryptoRandom;
class MonMap;
namespace ceph::common {
class CephContextServiceThread;
class CephContextObs;
class CephContextHook;
}
namespace ceph {
class PluginRegistry;
class HeartbeatMap;
namespace logging {
class Log;
class SubsystemMap;
}
}
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
namespace crimson::common {
class CephContext {
public:
CephContext();
CephContext(uint32_t,
code_environment_t=CODE_ENVIRONMENT_UTILITY,
int = 0)
: CephContext{}
{}
CephContext(CephContext&&) = default;
~CephContext();
uint32_t get_module_type() const;
bool check_experimental_feature_enabled(const std::string& feature) {
// everything crimson is experimental...
return true;
}
ceph::PluginRegistry* get_plugin_registry() {
return _plugin_registry;
}
CryptoRandom* random() const;
PerfCountersCollectionImpl* get_perfcounters_collection();
crimson::common::ConfigProxy& _conf;
crimson::common::PerfCountersCollection& _perf_counters_collection;
CephContext* get();
void put();
private:
std::unique_ptr<CryptoRandom> _crypto_random;
unsigned nref;
ceph::PluginRegistry* _plugin_registry;
};
}
#else
#ifdef __cplusplus
namespace ceph::common {
#endif
/* A CephContext represents the context held by a single library user.
* There can be multiple CephContexts in the same process.
*
* For daemons and utility programs, there will be only one CephContext. The
* CephContext contains the configuration, the dout object, and anything else
* that you might want to pass to libcommon with every function call.
*/
class CephContext {
public:
CephContext(uint32_t module_type_,
enum code_environment_t code_env=CODE_ENVIRONMENT_UTILITY,
int init_flags_ = 0);
struct create_options {
enum code_environment_t code_env=CODE_ENVIRONMENT_UTILITY;
int init_flags = 0;
std::function<ceph::logging::Log* (const ceph::logging::SubsystemMap *)> create_log;
};
CephContext(uint32_t module_type_,
const create_options& options);
CephContext(const CephContext&) = delete;
CephContext& operator =(const CephContext&) = delete;
CephContext(CephContext&&) = delete;
CephContext& operator =(CephContext&&) = delete;
bool _finished = false;
~CephContext();
// ref count!
private:
std::atomic<unsigned> nref;
public:
CephContext *get() {
++nref;
return this;
}
void put();
ConfigProxy _conf;
ceph::logging::Log *_log;
/* init ceph::crypto */
void init_crypto();
/// shutdown crypto (should match init_crypto calls)
void shutdown_crypto();
/* Start the Ceph Context's service thread */
void start_service_thread();
/* Reopen the log files */
void reopen_logs();
/* Get the module type (client, mon, osd, mds, etc.) */
uint32_t get_module_type() const;
// this is here only for testing purposes!
void _set_module_type(uint32_t t) {
_module_type = t;
}
void set_init_flags(int flags);
int get_init_flags() const;
/* Get the PerfCountersCollection of this CephContext */
PerfCountersCollection *get_perfcounters_collection();
ceph::HeartbeatMap *get_heartbeat_map() {
return _heartbeat_map;
}
/**
* Get the admin socket associated with this CephContext.
*
* Currently there is always an admin socket object,
* so this will never return NULL.
*
* @return the admin socket
*/
AdminSocket *get_admin_socket();
/**
* process an admin socket command
*/
int do_command(std::string_view command, const cmdmap_t& cmdmap,
Formatter *f,
std::ostream& errss,
ceph::bufferlist *out);
int _do_command(std::string_view command, const cmdmap_t& cmdmap,
Formatter *f,
std::ostream& errss,
ceph::bufferlist *out);
static constexpr std::size_t largest_singleton = 8 * 72;
template<typename T, typename... Args>
T& lookup_or_create_singleton_object(std::string_view name,
bool drop_on_fork,
Args&&... args) {
static_assert(sizeof(T) <= largest_singleton,
"Please increase largest singleton.");
std::lock_guard lg(associated_objs_lock);
std::type_index type = typeid(T);
auto i = associated_objs.find(std::make_pair(name, type));
if (i == associated_objs.cend()) {
if (drop_on_fork) {
associated_objs_drop_on_fork.insert(std::string(name));
}
i = associated_objs.emplace_hint(
i,
std::piecewise_construct,
std::forward_as_tuple(name, type),
std::forward_as_tuple(std::in_place_type<T>,
std::forward<Args>(args)...));
}
return ceph::any_cast<T&>(i->second);
}
/**
* get a crypto handler
*/
CryptoHandler *get_crypto_handler(int type);
CryptoRandom* random() const { return _crypto_random.get(); }
/// check if experimental feature is enable, and emit appropriate warnings
bool check_experimental_feature_enabled(const std::string& feature);
bool check_experimental_feature_enabled(const std::string& feature,
std::ostream *message);
ceph::PluginRegistry *get_plugin_registry() {
return _plugin_registry;
}
void set_uid_gid(uid_t u, gid_t g) {
_set_uid = u;
_set_gid = g;
}
uid_t get_set_uid() const {
return _set_uid;
}
gid_t get_set_gid() const {
return _set_gid;
}
void set_uid_gid_strings(const std::string &u, const std::string &g) {
_set_uid_string = u;
_set_gid_string = g;
}
std::string get_set_uid_string() const {
return _set_uid_string;
}
std::string get_set_gid_string() const {
return _set_gid_string;
}
class ForkWatcher {
public:
virtual ~ForkWatcher() {}
virtual void handle_pre_fork() = 0;
virtual void handle_post_fork() = 0;
};
void register_fork_watcher(ForkWatcher *w) {
std::lock_guard lg(_fork_watchers_lock);
_fork_watchers.push_back(w);
}
void notify_pre_fork();
void notify_post_fork();
/**
* update CephContext with a copy of the passed in MonMap mon addrs
*
* @param mm MonMap to extract and update mon addrs
*/
void set_mon_addrs(const MonMap& mm);
void set_mon_addrs(const std::vector<entity_addrvec_t>& in) {
auto ptr = std::make_shared<std::vector<entity_addrvec_t>>(in);
atomic_store_explicit(&_mon_addrs, std::move(ptr), std::memory_order_relaxed);
}
std::shared_ptr<std::vector<entity_addrvec_t>> get_mon_addrs() const {
auto ptr = atomic_load_explicit(&_mon_addrs, std::memory_order_relaxed);
return ptr;
}
private:
/* Stop and join the Ceph Context's service thread */
void join_service_thread();
uint32_t _module_type;
int _init_flags;
uid_t _set_uid; ///< uid to drop privs to
gid_t _set_gid; ///< gid to drop privs to
std::string _set_uid_string;
std::string _set_gid_string;
int _crypto_inited;
std::shared_ptr<std::vector<entity_addrvec_t>> _mon_addrs;
/* libcommon service thread.
* SIGHUP wakes this thread, which then reopens logfiles */
friend class CephContextServiceThread;
CephContextServiceThread *_service_thread;
using md_config_obs_t = ceph::md_config_obs_impl<ConfigProxy>;
md_config_obs_t *_log_obs;
/* The admin socket associated with this context */
AdminSocket *_admin_socket;
/* lock which protects service thread creation, destruction, etc. */
ceph::spinlock _service_thread_lock;
/* The collection of profiling loggers associated with this context */
PerfCountersCollection *_perf_counters_collection;
md_config_obs_t *_perf_counters_conf_obs;
CephContextHook *_admin_hook;
ceph::HeartbeatMap *_heartbeat_map;
ceph::spinlock associated_objs_lock;
struct associated_objs_cmp {
using is_transparent = std::true_type;
template<typename T, typename U>
bool operator ()(const std::pair<T, std::type_index>& l,
const std::pair<U, std::type_index>& r) const noexcept {
return ((l.first < r.first) ||
(l.first == r.first && l.second < r.second));
}
};
std::map<std::pair<std::string, std::type_index>,
ceph::immobile_any<largest_singleton>,
associated_objs_cmp> associated_objs;
std::set<std::string> associated_objs_drop_on_fork;
ceph::spinlock _fork_watchers_lock;
std::vector<ForkWatcher*> _fork_watchers;
// crypto
CryptoHandler *_crypto_none;
CryptoHandler *_crypto_aes;
std::unique_ptr<CryptoRandom> _crypto_random;
// experimental
CephContextObs *_cct_obs;
ceph::spinlock _feature_lock;
std::set<std::string> _experimental_features;
ceph::PluginRegistry* _plugin_registry;
#ifdef CEPH_DEBUG_MUTEX
md_config_obs_t *_lockdep_obs;
#endif
public:
TOPNSPC::crush::CrushLocation crush_location;
private:
enum {
l_cct_first,
l_cct_total_workers,
l_cct_unhealthy_workers,
l_cct_last
};
enum {
l_mempool_first = 873222,
l_mempool_bytes,
l_mempool_items,
l_mempool_last
};
PerfCounters *_cct_perf = nullptr;
PerfCounters* _mempool_perf = nullptr;
std::vector<std::string> _mempool_perf_names, _mempool_perf_descriptions;
/**
* Enable the performance counters.
*/
void _enable_perf_counter();
/**
* Disable the performance counter.
*/
void _disable_perf_counter();
/**
* Refresh perf counter values.
*/
void _refresh_perf_values();
friend class CephContextObs;
};
#ifdef __cplusplus
}
#endif
#endif // WITH_SEASTAR
#if !(defined(WITH_SEASTAR) && !defined(WITH_ALIEN)) && defined(__cplusplus)
namespace ceph::common {
inline void intrusive_ptr_add_ref(CephContext* cct)
{
cct->get();
}
inline void intrusive_ptr_release(CephContext* cct)
{
cct->put();
}
}
#endif // !(defined(WITH_SEASTAR) && !defined(WITH_ALIEN)) && defined(__cplusplus)
#endif
| 10,853 | 24.538824 | 88 | h |
null | ceph-main/src/common/ceph_crypto.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) 2010-2011 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 <vector>
#include <utility>
#include "common/ceph_context.h"
#include "common/ceph_mutex.h"
#include "common/config.h"
#include "ceph_crypto.h"
#include <openssl/evp.h>
#if OPENSSL_VERSION_NUMBER < 0x10100000L
# include <openssl/conf.h>
# include <openssl/engine.h>
# include <openssl/err.h>
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
namespace TOPNSPC::crypto::ssl {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
static std::atomic_uint32_t crypto_refs;
static auto ssl_mutexes = ceph::make_lock_container<ceph::shared_mutex>(
static_cast<size_t>(std::max(CRYPTO_num_locks(), 0)),
[](const size_t i) {
return ceph::make_shared_mutex(
std::string("ssl-mutex-") + std::to_string(i));
});
static struct {
// we could use e.g. unordered_set instead at the price of providing
// std::hash<...> specialization. However, we can live with duplicates
// quite well while the benefit is not worth the effort.
std::vector<CRYPTO_THREADID> tids;
ceph::mutex lock = ceph::make_mutex("crypto::ssl::init_records::lock");;
} init_records;
static void
ssl_locking_callback(
const int mode,
const int mutex_num,
[[maybe_unused]] const char *file,
[[maybe_unused]] const int line)
{
if (mutex_num < 0 || static_cast<size_t>(mutex_num) >= ssl_mutexes.size()) {
ceph_assert_always("openssl passed wrong mutex index" == nullptr);
}
if (mode & CRYPTO_READ) {
if (mode & CRYPTO_LOCK) {
ssl_mutexes[mutex_num].lock_shared();
} else if (mode & CRYPTO_UNLOCK) {
ssl_mutexes[mutex_num].unlock_shared();
}
} else if (mode & CRYPTO_WRITE) {
if (mode & CRYPTO_LOCK) {
ssl_mutexes[mutex_num].lock();
} else if (mode & CRYPTO_UNLOCK) {
ssl_mutexes[mutex_num].unlock();
}
}
}
static unsigned long
ssl_get_thread_id(void)
{
static_assert(sizeof(unsigned long) >= sizeof(pthread_t));
/* pthread_t may be any data type, so a simple cast to unsigned long
* can rise a warning/error, depending on the platform.
* Here memcpy is used as an anything-to-anything cast. */
unsigned long ret = 0;
pthread_t t = pthread_self();
memcpy(&ret, &t, sizeof(pthread_t));
return ret;
}
#endif /* not OPENSSL_VERSION_NUMBER < 0x10100000L */
static void init() {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (++crypto_refs == 1) {
// according to
// https://wiki.openssl.org/index.php/Library_Initialization#libcrypto_Initialization
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
// initialize locking callbacks, needed for thread safety.
// http://www.openssl.org/support/faq.html#PROG1
CRYPTO_set_locking_callback(&ssl_locking_callback);
CRYPTO_set_id_callback(&ssl_get_thread_id);
OPENSSL_config(nullptr);
}
// we need to record IDs of all threads calling the initialization in
// order to *manually* free per-thread memory OpenSSL *automagically*
// allocated in ERR_get_state().
// XXX: this solution/nasty hack is IMPERFECT. A leak will appear when
// a client init()ializes the crypto subsystem with one thread and then
// uses it from another one in a way that results in ERR_get_state().
// XXX: for discussion about another approaches please refer to:
// https://www.mail-archive.com/[email protected]/msg59070.html
{
std::lock_guard l(init_records.lock);
CRYPTO_THREADID tmp;
CRYPTO_THREADID_current(&tmp);
init_records.tids.emplace_back(std::move(tmp));
}
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
}
static void shutdown() {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (--crypto_refs != 0) {
return;
}
// drop error queue for each thread that called the init() function to
// satisfy valgrind.
{
std::lock_guard l(init_records.lock);
// NOTE: in OpenSSL 1.0.2g the signature is:
// void ERR_remove_thread_state(const CRYPTO_THREADID *tid);
// but in 1.1.0j it has been changed to
// void ERR_remove_thread_state(void *);
// We're basing on the OPENSSL_VERSION_NUMBER check to preserve
// const-correctness without failing builds on modern envs.
for (const auto& tid : init_records.tids) {
ERR_remove_thread_state(&tid);
}
}
// Shutdown according to
// https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
// http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
//
// The call to CONF_modules_free() has been introduced after a valgring run.
CRYPTO_set_locking_callback(nullptr);
CRYPTO_set_id_callback(nullptr);
ENGINE_cleanup();
CONF_modules_free();
CONF_modules_unload(1);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
// NOTE: don't clear ssl_mutexes as we should be ready for init-deinit-init
// sequence.
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
}
void zeroize_for_security(void* const s, const size_t n) {
OPENSSL_cleanse(s, n);
}
} // namespace TOPNSPC::crypto::openssl
namespace TOPNSPC::crypto {
void init() {
ssl::init();
}
void shutdown([[maybe_unused]] const bool shared) {
ssl::shutdown();
}
void zeroize_for_security(void* const s, const size_t n) {
ssl::zeroize_for_security(s, n);
}
ssl::OpenSSLDigest::OpenSSLDigest(const EVP_MD * _type)
: mpContext(EVP_MD_CTX_create())
, mpType(_type) {
this->Restart();
}
ssl::OpenSSLDigest::~OpenSSLDigest() {
EVP_MD_CTX_destroy(mpContext);
if (mpType_FIPS) {
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
EVP_MD_free(mpType_FIPS);
#endif // OPENSSL_VERSION_NUMBER >= 0x30000000L
}
}
ssl::OpenSSLDigest::OpenSSLDigest(OpenSSLDigest&& o) noexcept
: mpContext(std::exchange(o.mpContext, nullptr)),
mpType(std::exchange(o.mpType, nullptr)),
mpType_FIPS(std::exchange(o.mpType_FIPS, nullptr))
{
}
ssl::OpenSSLDigest& ssl::OpenSSLDigest::operator=(OpenSSLDigest&& o) noexcept
{
std::swap(mpContext, o.mpContext);
std::swap(mpType, o.mpType);
std::swap(mpType_FIPS, o.mpType_FIPS);
return *this;
}
void ssl::OpenSSLDigest::Restart() {
if (mpType_FIPS) {
EVP_DigestInit_ex(mpContext, mpType_FIPS, NULL);
} else {
EVP_DigestInit_ex(mpContext, mpType, NULL);
}
}
void ssl::OpenSSLDigest::SetFlags(int flags) {
if (flags == EVP_MD_CTX_FLAG_NON_FIPS_ALLOW && OpenSSL_version_num() >= 0x30000000L && mpType == EVP_md5() && !mpType_FIPS) {
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
mpType_FIPS = EVP_MD_fetch(NULL, "MD5", "fips=no");
#endif // OPENSSL_VERSION_NUMBER >= 0x30000000L
} else {
EVP_MD_CTX_set_flags(mpContext, flags);
}
this->Restart();
}
void ssl::OpenSSLDigest::Update(const unsigned char *input, size_t length) {
if (length) {
EVP_DigestUpdate(mpContext, const_cast<void *>(reinterpret_cast<const void *>(input)), length);
}
}
void ssl::OpenSSLDigest::Final(unsigned char *digest) {
unsigned int s;
EVP_DigestFinal_ex(mpContext, digest, &s);
}
}
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
| 7,514 | 28.355469 | 127 | cc |
null | ceph-main/src/common/ceph_crypto.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#ifndef CEPH_CRYPTO_H
#define CEPH_CRYPTO_H
#include "acconfig.h"
#include <stdexcept>
#include "include/common_fwd.h"
#include "include/buffer.h"
#include "include/types.h"
#define CEPH_CRYPTO_MD5_DIGESTSIZE 16
#define CEPH_CRYPTO_HMACSHA1_DIGESTSIZE 20
#define CEPH_CRYPTO_SHA1_DIGESTSIZE 20
#define CEPH_CRYPTO_HMACSHA256_DIGESTSIZE 32
#define CEPH_CRYPTO_SHA256_DIGESTSIZE 32
#define CEPH_CRYPTO_SHA512_DIGESTSIZE 64
#include <openssl/evp.h>
#include <openssl/ossl_typ.h>
#include <openssl/hmac.h>
#include "include/ceph_assert.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
extern "C" {
const EVP_MD *EVP_md5(void);
const EVP_MD *EVP_sha1(void);
const EVP_MD *EVP_sha256(void);
const EVP_MD *EVP_sha512(void);
}
namespace TOPNSPC::crypto {
void assert_init();
void init();
void shutdown(bool shared=true);
void zeroize_for_security(void *s, size_t n);
class DigestException : public std::runtime_error
{
public:
DigestException(const char* what_arg) : runtime_error(what_arg)
{}
};
namespace ssl {
class OpenSSLDigest {
private:
EVP_MD_CTX *mpContext;
const EVP_MD *mpType;
EVP_MD *mpType_FIPS = nullptr;
public:
OpenSSLDigest (const EVP_MD *_type);
~OpenSSLDigest ();
OpenSSLDigest(OpenSSLDigest&& o) noexcept;
OpenSSLDigest& operator=(OpenSSLDigest&& o) noexcept;
void Restart();
void SetFlags(int flags);
void Update (const unsigned char *input, size_t length);
void Final (unsigned char *digest);
};
class MD5 : public OpenSSLDigest {
public:
static constexpr size_t digest_size = CEPH_CRYPTO_MD5_DIGESTSIZE;
MD5 () : OpenSSLDigest(EVP_md5()) { }
};
class SHA1 : public OpenSSLDigest {
public:
static constexpr size_t digest_size = CEPH_CRYPTO_SHA1_DIGESTSIZE;
SHA1 () : OpenSSLDigest(EVP_sha1()) { }
};
class SHA256 : public OpenSSLDigest {
public:
static constexpr size_t digest_size = CEPH_CRYPTO_SHA256_DIGESTSIZE;
SHA256 () : OpenSSLDigest(EVP_sha256()) { }
};
class SHA512 : public OpenSSLDigest {
public:
static constexpr size_t digest_size = CEPH_CRYPTO_SHA512_DIGESTSIZE;
SHA512 () : OpenSSLDigest(EVP_sha512()) { }
};
# if OPENSSL_VERSION_NUMBER < 0x10100000L
class HMAC {
private:
HMAC_CTX mContext;
const EVP_MD *mpType;
public:
HMAC (const EVP_MD *type, const unsigned char *key, size_t length)
: mpType(type) {
// the strict FIPS zeroization doesn't seem to be necessary here.
// just in the case.
::TOPNSPC::crypto::zeroize_for_security(&mContext, sizeof(mContext));
const auto r = HMAC_Init_ex(&mContext, key, length, mpType, nullptr);
if (r != 1) {
throw DigestException("HMAC_Init_ex() failed");
}
}
~HMAC () {
HMAC_CTX_cleanup(&mContext);
}
void Restart () {
const auto r = HMAC_Init_ex(&mContext, nullptr, 0, mpType, nullptr);
if (r != 1) {
throw DigestException("HMAC_Init_ex() failed");
}
}
void Update (const unsigned char *input, size_t length) {
if (length) {
const auto r = HMAC_Update(&mContext, input, length);
if (r != 1) {
throw DigestException("HMAC_Update() failed");
}
}
}
void Final (unsigned char *digest) {
unsigned int s;
const auto r = HMAC_Final(&mContext, digest, &s);
if (r != 1) {
throw DigestException("HMAC_Final() failed");
}
}
};
# else
class HMAC {
private:
HMAC_CTX *mpContext;
public:
HMAC (const EVP_MD *type, const unsigned char *key, size_t length)
: mpContext(HMAC_CTX_new()) {
const auto r = HMAC_Init_ex(mpContext, key, length, type, nullptr);
if (r != 1) {
throw DigestException("HMAC_Init_ex() failed");
}
}
~HMAC () {
HMAC_CTX_free(mpContext);
}
void Restart () {
const EVP_MD * const type = HMAC_CTX_get_md(mpContext);
const auto r = HMAC_Init_ex(mpContext, nullptr, 0, type, nullptr);
if (r != 1) {
throw DigestException("HMAC_Init_ex() failed");
}
}
void Update (const unsigned char *input, size_t length) {
if (length) {
const auto r = HMAC_Update(mpContext, input, length);
if (r != 1) {
throw DigestException("HMAC_Update() failed");
}
}
}
void Final (unsigned char *digest) {
unsigned int s;
const auto r = HMAC_Final(mpContext, digest, &s);
if (r != 1) {
throw DigestException("HMAC_Final() failed");
}
}
};
# endif // OPENSSL_VERSION_NUMBER < 0x10100000L
struct HMACSHA1 : public HMAC {
HMACSHA1 (const unsigned char *key, size_t length)
: HMAC(EVP_sha1(), key, length) {
}
};
struct HMACSHA256 : public HMAC {
HMACSHA256 (const unsigned char *key, size_t length)
: HMAC(EVP_sha256(), key, length) {
}
};
}
using ssl::SHA256;
using ssl::MD5;
using ssl::SHA1;
using ssl::SHA512;
using ssl::HMACSHA256;
using ssl::HMACSHA1;
template<class Digest>
auto digest(const ceph::buffer::list& bl)
{
unsigned char fingerprint[Digest::digest_size];
Digest gen;
for (auto& p : bl.buffers()) {
gen.Update((const unsigned char *)p.c_str(), p.length());
}
gen.Final(fingerprint);
return sha_digest_t<Digest::digest_size>{fingerprint};
}
}
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
#endif
| 5,574 | 24.573394 | 76 | h |
null | ceph-main/src/common/ceph_frag.cc | /*
* Ceph 'frag' type
*/
#include "include/types.h"
int ceph_frag_compare(__u32 a, __u32 b)
{
unsigned va = ceph_frag_value(a);
unsigned vb = ceph_frag_value(b);
if (va < vb)
return -1;
if (va > vb)
return 1;
va = ceph_frag_bits(a);
vb = ceph_frag_bits(b);
if (va < vb)
return -1;
if (va > vb)
return 1;
return 0;
}
| 336 | 14.318182 | 39 | cc |
null | ceph-main/src/common/ceph_fs.cc | /*
* ceph_fs.cc - Some Ceph functions that are shared between kernel space and
* user space.
*
*/
/*
* Some non-inline ceph helpers
*/
#include "include/types.h"
int ceph_flags_to_mode(int flags)
{
/* because CEPH_FILE_MODE_PIN is zero, so mode = -1 is error */
int mode = -1;
if ((flags & CEPH_O_DIRECTORY) == CEPH_O_DIRECTORY)
return CEPH_FILE_MODE_PIN;
switch (flags & O_ACCMODE) {
case CEPH_O_WRONLY:
mode = CEPH_FILE_MODE_WR;
break;
case CEPH_O_RDONLY:
mode = CEPH_FILE_MODE_RD;
break;
case CEPH_O_RDWR:
case O_ACCMODE: /* this is what the VFS does */
mode = CEPH_FILE_MODE_RDWR;
break;
}
if (flags & CEPH_O_LAZY)
mode |= CEPH_FILE_MODE_LAZY;
return mode;
}
int ceph_caps_for_mode(int mode)
{
int caps = CEPH_CAP_PIN;
if (mode & CEPH_FILE_MODE_RD)
caps |= CEPH_CAP_FILE_SHARED |
CEPH_CAP_FILE_RD | CEPH_CAP_FILE_CACHE;
if (mode & CEPH_FILE_MODE_WR)
caps |= CEPH_CAP_FILE_EXCL |
CEPH_CAP_FILE_WR | CEPH_CAP_FILE_BUFFER |
CEPH_CAP_AUTH_SHARED | CEPH_CAP_AUTH_EXCL |
CEPH_CAP_XATTR_SHARED | CEPH_CAP_XATTR_EXCL;
if (mode & CEPH_FILE_MODE_LAZY)
caps |= CEPH_CAP_FILE_LAZYIO;
return caps;
}
int ceph_flags_sys2wire(int flags)
{
int wire_flags = 0;
switch (flags & O_ACCMODE) {
case O_RDONLY:
wire_flags |= CEPH_O_RDONLY;
break;
case O_WRONLY:
wire_flags |= CEPH_O_WRONLY;
break;
case O_RDWR:
wire_flags |= CEPH_O_RDWR;
break;
}
flags &= ~O_ACCMODE;
#define ceph_sys2wire(a) if (flags & a) { wire_flags |= CEPH_##a; flags &= ~a; }
ceph_sys2wire(O_CREAT);
ceph_sys2wire(O_EXCL);
ceph_sys2wire(O_TRUNC);
#ifndef _WIN32
ceph_sys2wire(O_DIRECTORY);
ceph_sys2wire(O_NOFOLLOW);
// In some cases, FILE_FLAG_BACKUP_SEMANTICS may be used instead
// of O_DIRECTORY. We may need some workarounds in order to handle
// the fact that those flags are not available on Windows.
#endif
#undef ceph_sys2wire
return wire_flags;
}
| 2,099 | 21.826087 | 80 | cc |
null | ceph-main/src/common/ceph_hash.cc |
#include "include/types.h"
/*
* Robert Jenkin's hash function.
* http://burtleburtle.net/bob/hash/evahash.html
* This is in the public domain.
*/
#define mix(a, b, c) \
do { \
a = a - b; a = a - c; a = a ^ (c >> 13); \
b = b - c; b = b - a; b = b ^ (a << 8); \
c = c - a; c = c - b; c = c ^ (b >> 13); \
a = a - b; a = a - c; a = a ^ (c >> 12); \
b = b - c; b = b - a; b = b ^ (a << 16); \
c = c - a; c = c - b; c = c ^ (b >> 5); \
a = a - b; a = a - c; a = a ^ (c >> 3); \
b = b - c; b = b - a; b = b ^ (a << 10); \
c = c - a; c = c - b; c = c ^ (b >> 15); \
} while (0)
unsigned ceph_str_hash_rjenkins(const char *str, unsigned length)
{
const unsigned char *k = (const unsigned char *)str;
__u32 a, b, c; /* the internal state */
__u32 len; /* how many key bytes still need mixing */
/* Set up the internal state */
len = length;
a = 0x9e3779b9; /* the golden ratio; an arbitrary value */
b = a;
c = 0; /* variable initialization of internal state */
/* handle most of the key */
while (len >= 12) {
a = a + (k[0] + ((__u32)k[1] << 8) + ((__u32)k[2] << 16) +
((__u32)k[3] << 24));
b = b + (k[4] + ((__u32)k[5] << 8) + ((__u32)k[6] << 16) +
((__u32)k[7] << 24));
c = c + (k[8] + ((__u32)k[9] << 8) + ((__u32)k[10] << 16) +
((__u32)k[11] << 24));
mix(a, b, c);
k = k + 12;
len = len - 12;
}
/* handle the last 11 bytes */
c = c + length;
switch (len) { /* all the case statements fall through */
case 11:
c = c + ((__u32)k[10] << 24);
case 10:
c = c + ((__u32)k[9] << 16);
case 9:
c = c + ((__u32)k[8] << 8);
/* the first byte of c is reserved for the length */
case 8:
b = b + ((__u32)k[7] << 24);
case 7:
b = b + ((__u32)k[6] << 16);
case 6:
b = b + ((__u32)k[5] << 8);
case 5:
b = b + k[4];
case 4:
a = a + ((__u32)k[3] << 24);
case 3:
a = a + ((__u32)k[2] << 16);
case 2:
a = a + ((__u32)k[1] << 8);
case 1:
a = a + k[0];
/* case 0: nothing left to add */
}
mix(a, b, c);
return c;
}
/*
* linux dcache hash
*/
unsigned ceph_str_hash_linux(const char *str, unsigned length)
{
unsigned hash = 0;
while (length--) {
unsigned char c = *str++;
hash = (hash + (c << 4) + (c >> 4)) * 11;
}
return hash;
}
unsigned ceph_str_hash(int type, const char *s, unsigned len)
{
switch (type) {
case CEPH_STR_HASH_LINUX:
return ceph_str_hash_linux(s, len);
case CEPH_STR_HASH_RJENKINS:
return ceph_str_hash_rjenkins(s, len);
default:
return -1;
}
}
const char *ceph_str_hash_name(int type)
{
switch (type) {
case CEPH_STR_HASH_LINUX:
return "linux";
case CEPH_STR_HASH_RJENKINS:
return "rjenkins";
default:
return "unknown";
}
}
bool ceph_str_hash_valid(int type)
{
switch (type) {
case CEPH_STR_HASH_LINUX:
case CEPH_STR_HASH_RJENKINS:
return true;
default:
return false;
}
}
| 2,949 | 21.868217 | 69 | cc |
null | ceph-main/src/common/ceph_json.cc | #include "common/ceph_json.h"
#include "include/utime.h"
// for testing DELETE ME
#include <fstream>
#include <include/types.h>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include "json_spirit/json_spirit_writer_template.h"
using namespace json_spirit;
using std::ifstream;
using std::pair;
using std::ostream;
using std::string;
using std::vector;
using ceph::bufferlist;
using ceph::Formatter;
#define dout_subsys ceph_subsys_rgw
static JSONFormattable default_formattable;
void encode_json(const char *name, const JSONObj::data_val& v, Formatter *f)
{
if (v.quoted) {
encode_json(name, v.str, f);
} else {
f->dump_format_unquoted(name, "%s", v.str.c_str());
}
}
JSONObjIter::JSONObjIter()
{
}
JSONObjIter::~JSONObjIter()
{
}
void JSONObjIter::set(const JSONObjIter::map_iter_t &_cur, const JSONObjIter::map_iter_t &_last)
{
cur = _cur;
last = _last;
}
void JSONObjIter::operator++()
{
if (cur != last)
++cur;
}
JSONObj *JSONObjIter::operator*()
{
return cur->second;
}
// does not work, FIXME
ostream& operator<<(ostream &out, const JSONObj &obj) {
out << obj.name << ": " << obj.val;
return out;
}
JSONObj::~JSONObj()
{
for (auto iter = children.begin(); iter != children.end(); ++iter) {
JSONObj *obj = iter->second;
delete obj;
}
}
void JSONObj::add_child(string el, JSONObj *obj)
{
children.insert(pair<string, JSONObj *>(el, obj));
}
bool JSONObj::get_attr(string name, data_val& attr)
{
auto iter = attr_map.find(name);
if (iter == attr_map.end())
return false;
attr = iter->second;
return true;
}
JSONObjIter JSONObj::find(const string& name)
{
JSONObjIter iter;
auto first = children.find(name);
if (first != children.end()) {
auto last = children.upper_bound(name);
iter.set(first, last);
}
return iter;
}
JSONObjIter JSONObj::find_first()
{
JSONObjIter iter;
iter.set(children.begin(), children.end());
return iter;
}
JSONObjIter JSONObj::find_first(const string& name)
{
JSONObjIter iter;
auto first = children.find(name);
iter.set(first, children.end());
return iter;
}
JSONObj *JSONObj::find_obj(const string& name)
{
JSONObjIter iter = find(name);
if (iter.end())
return NULL;
return *iter;
}
bool JSONObj::get_data(const string& key, data_val *dest)
{
JSONObj *obj = find_obj(key);
if (!obj)
return false;
*dest = obj->get_data_val();
return true;
}
/* accepts a JSON Array or JSON Object contained in
* a JSON Spirit Value, v, and creates a JSONObj for each
* child contained in v
*/
void JSONObj::handle_value(Value v)
{
if (v.type() == obj_type) {
Object temp_obj = v.get_obj();
for (Object::size_type i = 0; i < temp_obj.size(); i++) {
Pair temp_pair = temp_obj[i];
string temp_name = temp_pair.name_;
Value temp_value = temp_pair.value_;
JSONObj *child = new JSONObj;
child->init(this, temp_value, temp_name);
add_child(temp_name, child);
}
} else if (v.type() == array_type) {
Array temp_array = v.get_array();
Value value;
for (unsigned j = 0; j < temp_array.size(); j++) {
Value cur = temp_array[j];
string temp_name;
JSONObj *child = new JSONObj;
child->init(this, cur, temp_name);
add_child(child->get_name(), child);
}
}
}
void JSONObj::init(JSONObj *p, Value v, string n)
{
name = n;
parent = p;
data = v;
handle_value(v);
if (v.type() == str_type) {
val.set(v.get_str(), true);
} else {
val.set(json_spirit::write_string(v), false);
}
attr_map.insert(pair<string,data_val>(name, val));
}
JSONObj *JSONObj::get_parent()
{
return parent;
}
bool JSONObj::is_object()
{
return (data.type() == obj_type);
}
bool JSONObj::is_array()
{
return (data.type() == array_type);
}
vector<string> JSONObj::get_array_elements()
{
vector<string> elements;
Array temp_array;
if (data.type() == array_type)
temp_array = data.get_array();
int array_size = temp_array.size();
if (array_size > 0)
for (int i = 0; i < array_size; i++) {
Value temp_value = temp_array[i];
string temp_string;
temp_string = write(temp_value, raw_utf8);
elements.push_back(temp_string);
}
return elements;
}
JSONParser::JSONParser() : buf_len(0), success(true)
{
}
JSONParser::~JSONParser()
{
}
void JSONParser::handle_data(const char *s, int len)
{
json_buffer.append(s, len); // check for problems with null termination FIXME
buf_len += len;
}
// parse a supplied JSON fragment
bool JSONParser::parse(const char *buf_, int len)
{
if (!buf_) {
set_failure();
return false;
}
string json_string(buf_, len);
success = read(json_string, data);
if (success) {
handle_value(data);
if (data.type() != obj_type &&
data.type() != array_type) {
if (data.type() == str_type) {
val.set(data.get_str(), true);
} else {
const std::string& s = json_spirit::write_string(data);
if (s.size() == (uint64_t)len) { /* Check if entire string is read */
val.set(s, false);
} else {
set_failure();
}
}
}
} else {
set_failure();
}
return success;
}
// parse the internal json_buffer up to len
bool JSONParser::parse(int len)
{
string json_string = json_buffer.substr(0, len);
success = read(json_string, data);
if (success)
handle_value(data);
else
set_failure();
return success;
}
// parse the complete internal json_buffer
bool JSONParser::parse()
{
success = read(json_buffer, data);
if (success)
handle_value(data);
else
set_failure();
return success;
}
// parse a supplied ifstream, for testing. DELETE ME
bool JSONParser::parse(const char *file_name)
{
ifstream is(file_name);
success = read(is, data);
if (success)
handle_value(data);
else
set_failure();
return success;
}
void decode_json_obj(long& val, JSONObj *obj)
{
string s = obj->get_data();
const char *start = s.c_str();
char *p;
errno = 0;
val = strtol(start, &p, 10);
/* Check for various possible errors */
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) ||
(errno != 0 && val == 0)) {
throw JSONDecoder::err("failed to parse number");
}
if (p == start) {
throw JSONDecoder::err("failed to parse number");
}
while (*p != '\0') {
if (!isspace(*p)) {
throw JSONDecoder::err("failed to parse number");
}
p++;
}
}
void decode_json_obj(unsigned long& val, JSONObj *obj)
{
string s = obj->get_data();
const char *start = s.c_str();
char *p;
errno = 0;
val = strtoul(start, &p, 10);
/* Check for various possible errors */
if ((errno == ERANGE && val == ULONG_MAX) ||
(errno != 0 && val == 0)) {
throw JSONDecoder::err("failed to number");
}
if (p == start) {
throw JSONDecoder::err("failed to parse number");
}
while (*p != '\0') {
if (!isspace(*p)) {
throw JSONDecoder::err("failed to parse number");
}
p++;
}
}
void decode_json_obj(long long& val, JSONObj *obj)
{
string s = obj->get_data();
const char *start = s.c_str();
char *p;
errno = 0;
val = strtoll(start, &p, 10);
/* Check for various possible errors */
if ((errno == ERANGE && (val == LLONG_MAX || val == LLONG_MIN)) ||
(errno != 0 && val == 0)) {
throw JSONDecoder::err("failed to parse number");
}
if (p == start) {
throw JSONDecoder::err("failed to parse number");
}
while (*p != '\0') {
if (!isspace(*p)) {
throw JSONDecoder::err("failed to parse number");
}
p++;
}
}
void decode_json_obj(unsigned long long& val, JSONObj *obj)
{
string s = obj->get_data();
const char *start = s.c_str();
char *p;
errno = 0;
val = strtoull(start, &p, 10);
/* Check for various possible errors */
if ((errno == ERANGE && val == ULLONG_MAX) ||
(errno != 0 && val == 0)) {
throw JSONDecoder::err("failed to number");
}
if (p == start) {
throw JSONDecoder::err("failed to parse number");
}
while (*p != '\0') {
if (!isspace(*p)) {
throw JSONDecoder::err("failed to parse number");
}
p++;
}
}
void decode_json_obj(int& val, JSONObj *obj)
{
long l;
decode_json_obj(l, obj);
#if LONG_MAX > INT_MAX
if (l > INT_MAX || l < INT_MIN) {
throw JSONDecoder::err("integer out of range");
}
#endif
val = (int)l;
}
void decode_json_obj(unsigned& val, JSONObj *obj)
{
unsigned long l;
decode_json_obj(l, obj);
#if ULONG_MAX > UINT_MAX
if (l > UINT_MAX) {
throw JSONDecoder::err("unsigned integer out of range");
}
#endif
val = (unsigned)l;
}
void decode_json_obj(bool& val, JSONObj *obj)
{
string s = obj->get_data();
if (strcasecmp(s.c_str(), "true") == 0) {
val = true;
return;
}
if (strcasecmp(s.c_str(), "false") == 0) {
val = false;
return;
}
int i;
decode_json_obj(i, obj);
val = (bool)i;
}
void decode_json_obj(bufferlist& val, JSONObj *obj)
{
string s = obj->get_data();
bufferlist bl;
bl.append(s.c_str(), s.size());
try {
val.decode_base64(bl);
} catch (ceph::buffer::error& err) {
throw JSONDecoder::err("failed to decode base64");
}
}
void decode_json_obj(utime_t& val, JSONObj *obj)
{
string s = obj->get_data();
uint64_t epoch;
uint64_t nsec;
int r = utime_t::parse_date(s, &epoch, &nsec);
if (r == 0) {
val = utime_t(epoch, nsec);
} else {
throw JSONDecoder::err("failed to decode utime_t");
}
}
void decode_json_obj(ceph::real_time& val, JSONObj *obj)
{
const std::string& s = obj->get_data();
uint64_t epoch;
uint64_t nsec;
int r = utime_t::parse_date(s, &epoch, &nsec);
if (r == 0) {
using namespace std::chrono;
val = real_time{seconds(epoch) + nanoseconds(nsec)};
} else {
throw JSONDecoder::err("failed to decode real_time");
}
}
void decode_json_obj(ceph::coarse_real_time& val, JSONObj *obj)
{
const std::string& s = obj->get_data();
uint64_t epoch;
uint64_t nsec;
int r = utime_t::parse_date(s, &epoch, &nsec);
if (r == 0) {
using namespace std::chrono;
val = coarse_real_time{seconds(epoch) + nanoseconds(nsec)};
} else {
throw JSONDecoder::err("failed to decode coarse_real_time");
}
}
void decode_json_obj(ceph_dir_layout& i, JSONObj *obj){
unsigned tmp;
JSONDecoder::decode_json("dir_hash", tmp, obj, true);
i.dl_dir_hash = tmp;
JSONDecoder::decode_json("unused1", tmp, obj, true);
i.dl_unused1 = tmp;
JSONDecoder::decode_json("unused2", tmp, obj, true);
i.dl_unused2 = tmp;
JSONDecoder::decode_json("unused3", tmp, obj, true);
i.dl_unused3 = tmp;
}
void encode_json(const char *name, std::string_view val, Formatter *f)
{
f->dump_string(name, val);
}
void encode_json(const char *name, const string& val, Formatter *f)
{
f->dump_string(name, val);
}
void encode_json(const char *name, const char *val, Formatter *f)
{
f->dump_string(name, val);
}
void encode_json(const char *name, bool val, Formatter *f)
{
f->dump_bool(name, val);
}
void encode_json(const char *name, int val, Formatter *f)
{
f->dump_int(name, val);
}
void encode_json(const char *name, long val, Formatter *f)
{
f->dump_int(name, val);
}
void encode_json(const char *name, unsigned val, Formatter *f)
{
f->dump_unsigned(name, val);
}
void encode_json(const char *name, unsigned long val, Formatter *f)
{
f->dump_unsigned(name, val);
}
void encode_json(const char *name, unsigned long long val, Formatter *f)
{
f->dump_unsigned(name, val);
}
void encode_json(const char *name, long long val, Formatter *f)
{
f->dump_int(name, val);
}
void encode_json(const char *name, const utime_t& val, Formatter *f)
{
val.gmtime(f->dump_stream(name));
}
void encode_json(const char *name, const ceph::real_time& val, Formatter *f)
{
encode_json(name, utime_t{val}, f);
}
void encode_json(const char *name, const ceph::coarse_real_time& val, Formatter *f)
{
encode_json(name, utime_t{val}, f);
}
void encode_json(const char *name, const bufferlist& bl, Formatter *f)
{
/* need to copy data from bl, as it is const bufferlist */
bufferlist src = bl;
bufferlist b64;
src.encode_base64(b64);
string s(b64.c_str(), b64.length());
encode_json(name, s, f);
}
/* JSONFormattable */
const JSONFormattable& JSONFormattable::operator[](const string& name) const
{
auto i = obj.find(name);
if (i == obj.end()) {
return default_formattable;
}
return i->second;
}
const JSONFormattable& JSONFormattable::operator[](size_t index) const
{
if (index >= arr.size()) {
return default_formattable;
}
return arr[index];
}
JSONFormattable& JSONFormattable::operator[](const string& name)
{
auto i = obj.find(name);
if (i == obj.end()) {
return default_formattable;
}
return i->second;
}
JSONFormattable& JSONFormattable::operator[](size_t index)
{
if (index >= arr.size()) {
return default_formattable;
}
return arr[index];
}
bool JSONFormattable::exists(const string& name) const
{
auto i = obj.find(name);
return (i != obj.end());
}
bool JSONFormattable::exists(size_t index) const
{
return (index < arr.size());
}
bool JSONFormattable::find(const string& name, string *val) const
{
auto i = obj.find(name);
if (i == obj.end()) {
return false;
}
*val = i->second.val();
return true;
}
int JSONFormattable::val_int() const {
return atoi(value.str.c_str());
}
long JSONFormattable::val_long() const {
return atol(value.str.c_str());
}
long long JSONFormattable::val_long_long() const {
return atoll(value.str.c_str());
}
bool JSONFormattable::val_bool() const {
return (boost::iequals(value.str, "true") ||
boost::iequals(value.str, "on") ||
boost::iequals(value.str, "yes") ||
boost::iequals(value.str, "1"));
}
string JSONFormattable::def(const string& def_val) const {
if (type == FMT_NONE) {
return def_val;
}
return val();
}
int JSONFormattable::def(int def_val) const {
if (type == FMT_NONE) {
return def_val;
}
return val_int();
}
bool JSONFormattable::def(bool def_val) const {
if (type == FMT_NONE) {
return def_val;
}
return val_bool();
}
string JSONFormattable::get(const string& name, const string& def_val) const
{
return (*this)[name].def(def_val);
}
int JSONFormattable::get_int(const string& name, int def_val) const
{
return (*this)[name].def(def_val);
}
bool JSONFormattable::get_bool(const string& name, bool def_val) const
{
return (*this)[name].def(def_val);
}
struct field_entity {
bool is_obj{false}; /* either obj field or array entity */
string name; /* if obj */
int index{0}; /* if array */
bool append{false};
field_entity() {}
explicit field_entity(const string& n) : is_obj(true), name(n) {}
explicit field_entity(int i) : is_obj(false), index(i) {}
};
static int parse_entity(const string& s, vector<field_entity> *result)
{
size_t ofs = 0;
while (ofs < s.size()) {
size_t next_arr = s.find('[', ofs);
if (next_arr == string::npos) {
if (ofs != 0) {
return -EINVAL;
}
result->push_back(field_entity(s));
return 0;
}
if (next_arr > ofs) {
string field = s.substr(ofs, next_arr - ofs);
result->push_back(field_entity(field));
ofs = next_arr;
}
size_t end_arr = s.find(']', next_arr + 1);
if (end_arr == string::npos) {
return -EINVAL;
}
string index_str = s.substr(next_arr + 1, end_arr - next_arr - 1);
ofs = end_arr + 1;
if (!index_str.empty()) {
result->push_back(field_entity(atoi(index_str.c_str())));
} else {
field_entity f;
f.append = true;
result->push_back(f);
}
}
return 0;
}
static bool is_numeric(const string& val)
{
try {
boost::lexical_cast<double>(val);
} catch (const boost::bad_lexical_cast& e) {
return false;
}
return true;
}
int JSONFormattable::set(const string& name, const string& val)
{
boost::escaped_list_separator<char> els('\\', '.', '"');
boost::tokenizer<boost::escaped_list_separator<char> > tok(name, els);
JSONFormattable *f = this;
JSONParser jp;
bool is_valid_json = jp.parse(val.c_str(), val.size());
for (const auto& i : tok) {
vector<field_entity> v;
int ret = parse_entity(i, &v);
if (ret < 0) {
return ret;
}
for (const auto& vi : v) {
if (f->type == FMT_NONE) {
if (vi.is_obj) {
f->type = FMT_OBJ;
} else {
f->type = FMT_ARRAY;
}
}
if (f->type == FMT_OBJ) {
if (!vi.is_obj) {
return -EINVAL;
}
f = &f->obj[vi.name];
} else if (f->type == FMT_ARRAY) {
if (vi.is_obj) {
return -EINVAL;
}
int index = vi.index;
if (vi.append) {
index = f->arr.size();
} else if (index < 0) {
index = f->arr.size() + index;
if (index < 0) {
return -EINVAL; /* out of bounds */
}
}
if ((size_t)index >= f->arr.size()) {
f->arr.resize(index + 1);
}
f = &f->arr[index];
}
}
}
if (is_valid_json) {
f->decode_json(&jp);
} else {
f->type = FMT_VALUE;
f->value.set(val, !is_numeric(val));
}
return 0;
}
int JSONFormattable::erase(const string& name)
{
boost::escaped_list_separator<char> els('\\', '.', '"');
boost::tokenizer<boost::escaped_list_separator<char> > tok(name, els);
JSONFormattable *f = this;
JSONFormattable *parent = nullptr;
field_entity last_entity;
for (auto& i : tok) {
vector<field_entity> v;
int ret = parse_entity(i, &v);
if (ret < 0) {
return ret;
}
for (const auto& vi : v) {
if (f->type == FMT_NONE ||
f->type == FMT_VALUE) {
if (vi.is_obj) {
f->type = FMT_OBJ;
} else {
f->type = FMT_ARRAY;
}
}
parent = f;
if (f->type == FMT_OBJ) {
if (!vi.is_obj) {
return -EINVAL;
}
auto iter = f->obj.find(vi.name);
if (iter == f->obj.end()) {
return 0; /* nothing to erase */
}
f = &iter->second;
} else if (f->type == FMT_ARRAY) {
if (vi.is_obj) {
return -EINVAL;
}
int index = vi.index;
if (index < 0) {
index = f->arr.size() + index;
if (index < 0) { /* out of bounds, nothing to remove */
return 0;
}
}
if ((size_t)index >= f->arr.size()) {
return 0; /* index beyond array boundaries */
}
f = &f->arr[index];
}
last_entity = vi;
}
}
if (!parent) {
*this = JSONFormattable(); /* erase everything */
} else {
if (last_entity.is_obj) {
parent->obj.erase(last_entity.name);
} else {
int index = (last_entity.index >= 0 ? last_entity.index : parent->arr.size() + last_entity.index);
if (index < 0 || (size_t)index >= parent->arr.size()) {
return 0;
}
parent->arr.erase(parent->arr.begin() + index);
}
}
return 0;
}
void JSONFormattable::derive_from(const JSONFormattable& parent)
{
for (auto& o : parent.obj) {
if (obj.find(o.first) == obj.end()) {
obj[o.first] = o.second;
}
}
}
void encode_json(const char *name, const JSONFormattable& v, Formatter *f)
{
v.encode_json(name, f);
}
void JSONFormattable::encode_json(const char *name, Formatter *f) const
{
switch (type) {
case JSONFormattable::FMT_VALUE:
::encode_json(name, value, f);
break;
case JSONFormattable::FMT_ARRAY:
::encode_json(name, arr, f);
break;
case JSONFormattable::FMT_OBJ:
f->open_object_section(name);
for (auto iter : obj) {
::encode_json(iter.first.c_str(), iter.second, f);
}
f->close_section();
break;
case JSONFormattable::FMT_NONE:
break;
}
}
bool JSONFormattable::handle_value(std::string_view name, std::string_view s, bool quoted) {
JSONFormattable *new_val;
if (cur_enc->is_array()) {
cur_enc->arr.push_back(JSONFormattable());
new_val = &cur_enc->arr.back();
} else {
cur_enc->set_type(JSONFormattable::FMT_OBJ);
new_val = &cur_enc->obj[string{name}];
}
new_val->set_type(JSONFormattable::FMT_VALUE);
new_val->value.set(s, quoted);
return false;
}
bool JSONFormattable::handle_open_section(std::string_view name,
const char *ns,
bool section_is_array) {
if (cur_enc->is_array()) {
cur_enc->arr.push_back(JSONFormattable());
cur_enc = &cur_enc->arr.back();
} else if (enc_stack.size() > 1) {
/* only open a new section if already nested,
* otherwise root is the container
*/
cur_enc = &cur_enc->obj[string{name}];
}
enc_stack.push_back(cur_enc);
if (section_is_array) {
cur_enc->set_type(JSONFormattable::FMT_ARRAY);
} else {
cur_enc->set_type(JSONFormattable::FMT_OBJ);
}
return false; /* continue processing */
}
bool JSONFormattable::handle_close_section() {
if (enc_stack.size() <= 1) {
return false;
}
enc_stack.pop_back();
cur_enc = enc_stack.back();
return false; /* continue processing */
}
| 21,286 | 20.37249 | 104 | cc |
null | ceph-main/src/common/ceph_json.h | #ifndef CEPH_JSON_H
#define CEPH_JSON_H
#include <stdexcept>
#include <typeindex>
#include <include/types.h>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <include/ceph_fs.h>
#include "common/ceph_time.h"
#include "json_spirit/json_spirit.h"
#include "Formatter.h"
class JSONObj;
class JSONObjIter {
typedef std::map<std::string, JSONObj *>::iterator map_iter_t;
map_iter_t cur;
map_iter_t last;
public:
JSONObjIter();
~JSONObjIter();
void set(const JSONObjIter::map_iter_t &_cur, const JSONObjIter::map_iter_t &_end);
void operator++();
JSONObj *operator*();
bool end() const {
return (cur == last);
}
};
class JSONObj
{
JSONObj *parent;
public:
struct data_val {
std::string str;
bool quoted{false};
void set(std::string_view s, bool q) {
str = s;
quoted = q;
}
};
protected:
std::string name; // corresponds to obj_type in XMLObj
json_spirit::Value data;
struct data_val val;
bool data_quoted{false};
std::multimap<std::string, JSONObj *> children;
std::map<std::string, data_val> attr_map;
void handle_value(json_spirit::Value v);
public:
JSONObj() : parent(NULL){}
virtual ~JSONObj();
void init(JSONObj *p, json_spirit::Value v, std::string n);
std::string& get_name() { return name; }
data_val& get_data_val() { return val; }
const std::string& get_data() { return val.str; }
bool get_data(const std::string& key, data_val *dest);
JSONObj *get_parent();
void add_child(std::string el, JSONObj *child);
bool get_attr(std::string name, data_val& attr);
JSONObjIter find(const std::string& name);
JSONObjIter find_first();
JSONObjIter find_first(const std::string& name);
JSONObj *find_obj(const std::string& name);
friend std::ostream& operator<<(std::ostream &out,
const JSONObj &obj); // does not work, FIXME
bool is_array();
bool is_object();
std::vector<std::string> get_array_elements();
};
inline std::ostream& operator<<(std::ostream &out, const JSONObj::data_val& dv) {
const char *q = (dv.quoted ? "\"" : "");
out << q << dv.str << q;
return out;
}
class JSONParser : public JSONObj
{
int buf_len;
std::string json_buffer;
bool success;
public:
JSONParser();
~JSONParser() override;
void handle_data(const char *s, int len);
bool parse(const char *buf_, int len);
bool parse(int len);
bool parse();
bool parse(const char *file_name);
const char *get_json() { return json_buffer.c_str(); }
void set_failure() { success = false; }
};
void encode_json(const char *name, const JSONObj::data_val& v, ceph::Formatter *f);
class JSONDecoder {
public:
struct err : std::runtime_error {
using runtime_error::runtime_error;
};
JSONParser parser;
JSONDecoder(ceph::buffer::list& bl) {
if (!parser.parse(bl.c_str(), bl.length())) {
std::cout << "JSONDecoder::err()" << std::endl;
throw JSONDecoder::err("failed to parse JSON input");
}
}
template<class T>
static bool decode_json(const char *name, T& val, JSONObj *obj, bool mandatory = false);
template<class C>
static bool decode_json(const char *name, C& container, void (*cb)(C&, JSONObj *obj), JSONObj *obj, bool mandatory = false);
template<class T>
static void decode_json(const char *name, T& val, const T& default_val, JSONObj *obj);
template<class T>
static bool decode_json(const char *name, boost::optional<T>& val, JSONObj *obj, bool mandatory = false);
template<class T>
static bool decode_json(const char *name, std::optional<T>& val, JSONObj *obj, bool mandatory = false);
};
template<class T>
void decode_json_obj(T& val, JSONObj *obj)
{
val.decode_json(obj);
}
inline void decode_json_obj(std::string& val, JSONObj *obj)
{
val = obj->get_data();
}
static inline void decode_json_obj(JSONObj::data_val& val, JSONObj *obj)
{
val = obj->get_data_val();
}
void decode_json_obj(unsigned long long& val, JSONObj *obj);
void decode_json_obj(long long& val, JSONObj *obj);
void decode_json_obj(unsigned long& val, JSONObj *obj);
void decode_json_obj(long& val, JSONObj *obj);
void decode_json_obj(unsigned& val, JSONObj *obj);
void decode_json_obj(int& val, JSONObj *obj);
void decode_json_obj(bool& val, JSONObj *obj);
void decode_json_obj(ceph::buffer::list& val, JSONObj *obj);
class utime_t;
void decode_json_obj(utime_t& val, JSONObj *obj);
void decode_json_obj(ceph_dir_layout& i, JSONObj *obj);
void decode_json_obj(ceph::real_time& val, JSONObj *obj);
void decode_json_obj(ceph::coarse_real_time& val, JSONObj *obj);
template<class T>
void decode_json_obj(std::list<T>& l, JSONObj *obj)
{
l.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
T val;
JSONObj *o = *iter;
decode_json_obj(val, o);
l.push_back(val);
}
}
template<class T>
void decode_json_obj(std::deque<T>& l, JSONObj *obj)
{
l.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
T val;
JSONObj *o = *iter;
decode_json_obj(val, o);
l.push_back(val);
}
}
template<class T>
void decode_json_obj(std::set<T>& l, JSONObj *obj)
{
l.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
T val;
JSONObj *o = *iter;
decode_json_obj(val, o);
l.insert(val);
}
}
template<class T, class Compare, class Alloc>
void decode_json_obj(boost::container::flat_set<T, Compare, Alloc>& l, JSONObj *obj)
{
l.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
T val;
JSONObj *o = *iter;
decode_json_obj(val, o);
l.insert(val);
}
}
template<class T>
void decode_json_obj(std::vector<T>& l, JSONObj *obj)
{
l.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
T val;
JSONObj *o = *iter;
decode_json_obj(val, o);
l.push_back(val);
}
}
template<class K, class V, class C = std::less<K> >
void decode_json_obj(std::map<K, V, C>& m, JSONObj *obj)
{
m.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
K key;
V val;
JSONObj *o = *iter;
JSONDecoder::decode_json("key", key, o);
JSONDecoder::decode_json("val", val, o);
m[key] = val;
}
}
template<class K, class V, class C = std::less<K> >
void decode_json_obj(boost::container::flat_map<K, V, C>& m, JSONObj *obj)
{
m.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
K key;
V val;
JSONObj *o = *iter;
JSONDecoder::decode_json("key", key, o);
JSONDecoder::decode_json("val", val, o);
m[key] = val;
}
}
template<class K, class V>
void decode_json_obj(std::multimap<K, V>& m, JSONObj *obj)
{
m.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
K key;
V val;
JSONObj *o = *iter;
JSONDecoder::decode_json("key", key, o);
JSONDecoder::decode_json("val", val, o);
m.insert(make_pair(key, val));
}
}
template<class K, class V>
void decode_json_obj(boost::container::flat_map<K, V>& m, JSONObj *obj)
{
m.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
K key;
V val;
JSONObj *o = *iter;
JSONDecoder::decode_json("key", key, o);
JSONDecoder::decode_json("val", val, o);
m[key] = val;
}
}
template<class C>
void decode_json_obj(C& container, void (*cb)(C&, JSONObj *obj), JSONObj *obj)
{
container.clear();
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
JSONObj *o = *iter;
cb(container, o);
}
}
template<class T>
bool JSONDecoder::decode_json(const char *name, T& val, JSONObj *obj, bool mandatory)
{
JSONObjIter iter = obj->find_first(name);
if (iter.end()) {
if (mandatory) {
std::string s = "missing mandatory field " + std::string(name);
throw err(s);
}
if constexpr (std::is_default_constructible_v<T>) {
val = T();
}
return false;
}
try {
decode_json_obj(val, *iter);
} catch (const err& e) {
std::string s = std::string(name) + ": ";
s.append(e.what());
throw err(s);
}
return true;
}
template<class C>
bool JSONDecoder::decode_json(const char *name, C& container, void (*cb)(C&, JSONObj *), JSONObj *obj, bool mandatory)
{
container.clear();
JSONObjIter iter = obj->find_first(name);
if (iter.end()) {
if (mandatory) {
std::string s = "missing mandatory field " + std::string(name);
throw err(s);
}
return false;
}
try {
decode_json_obj(container, cb, *iter);
} catch (const err& e) {
std::string s = std::string(name) + ": ";
s.append(e.what());
throw err(s);
}
return true;
}
template<class T>
void JSONDecoder::decode_json(const char *name, T& val, const T& default_val, JSONObj *obj)
{
JSONObjIter iter = obj->find_first(name);
if (iter.end()) {
val = default_val;
return;
}
try {
decode_json_obj(val, *iter);
} catch (const err& e) {
val = default_val;
std::string s = std::string(name) + ": ";
s.append(e.what());
throw err(s);
}
}
template<class T>
bool JSONDecoder::decode_json(const char *name, boost::optional<T>& val, JSONObj *obj, bool mandatory)
{
JSONObjIter iter = obj->find_first(name);
if (iter.end()) {
if (mandatory) {
std::string s = "missing mandatory field " + std::string(name);
throw err(s);
}
val = boost::none;
return false;
}
try {
val.reset(T());
decode_json_obj(val.get(), *iter);
} catch (const err& e) {
val.reset();
std::string s = std::string(name) + ": ";
s.append(e.what());
throw err(s);
}
return true;
}
template<class T>
bool JSONDecoder::decode_json(const char *name, std::optional<T>& val, JSONObj *obj, bool mandatory)
{
JSONObjIter iter = obj->find_first(name);
if (iter.end()) {
if (mandatory) {
std::string s = "missing mandatory field " + std::string(name);
throw err(s);
}
val.reset();
return false;
}
try {
val.emplace();
decode_json_obj(*val, *iter);
} catch (const err& e) {
val.reset();
std::string s = std::string(name) + ": ";
s.append(e.what());
throw err(s);
}
return true;
}
class JSONEncodeFilter
{
public:
class HandlerBase {
public:
virtual ~HandlerBase() {}
virtual std::type_index get_type() = 0;
virtual void encode_json(const char *name, const void *pval, ceph::Formatter *) const = 0;
};
template <class T>
class Handler : public HandlerBase {
public:
virtual ~Handler() {}
std::type_index get_type() override {
return std::type_index(typeid(const T&));
}
};
private:
std::map<std::type_index, HandlerBase *> handlers;
public:
void register_type(HandlerBase *h) {
handlers[h->get_type()] = h;
}
template <class T>
bool encode_json(const char *name, const T& val, ceph::Formatter *f) {
auto iter = handlers.find(std::type_index(typeid(val)));
if (iter == handlers.end()) {
return false;
}
iter->second->encode_json(name, (const void *)&val, f);
return true;
}
};
template<class T>
static void encode_json_impl(const char *name, const T& val, ceph::Formatter *f)
{
f->open_object_section(name);
val.dump(f);
f->close_section();
}
template<class T>
static void encode_json(const char *name, const T& val, ceph::Formatter *f)
{
JSONEncodeFilter *filter = static_cast<JSONEncodeFilter *>(f->get_external_feature_handler("JSONEncodeFilter"));
if (!filter ||
!filter->encode_json(name, val, f)) {
encode_json_impl(name, val, f);
}
}
class utime_t;
void encode_json(const char *name, std::string_view val, ceph::Formatter *f);
void encode_json(const char *name, const std::string& val, ceph::Formatter *f);
void encode_json(const char *name, const char *val, ceph::Formatter *f);
void encode_json(const char *name, bool val, ceph::Formatter *f);
void encode_json(const char *name, int val, ceph::Formatter *f);
void encode_json(const char *name, unsigned val, ceph::Formatter *f);
void encode_json(const char *name, long val, ceph::Formatter *f);
void encode_json(const char *name, unsigned long val, ceph::Formatter *f);
void encode_json(const char *name, long long val, ceph::Formatter *f);
void encode_json(const char *name, const utime_t& val, ceph::Formatter *f);
void encode_json(const char *name, const ceph::buffer::list& bl, ceph::Formatter *f);
void encode_json(const char *name, long long unsigned val, ceph::Formatter *f);
void encode_json(const char *name, const ceph::real_time& val, ceph::Formatter *f);
void encode_json(const char *name, const ceph::coarse_real_time& val, ceph::Formatter *f);
template<class T>
static void encode_json(const char *name, const std::list<T>& l, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = l.cbegin(); iter != l.cend(); ++iter) {
encode_json("obj", *iter, f);
}
f->close_section();
}
template<class T>
static void encode_json(const char *name, const std::deque<T>& l, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = l.cbegin(); iter != l.cend(); ++iter) {
encode_json("obj", *iter, f);
}
f->close_section();
}
template<class T, class Compare = std::less<T> >
static void encode_json(const char *name, const std::set<T, Compare>& l, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = l.cbegin(); iter != l.cend(); ++iter) {
encode_json("obj", *iter, f);
}
f->close_section();
}
template<class T, class Compare, class Alloc>
static void encode_json(const char *name,
const boost::container::flat_set<T, Compare, Alloc>& l,
ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = l.cbegin(); iter != l.cend(); ++iter) {
encode_json("obj", *iter, f);
}
f->close_section();
}
template<class T>
static void encode_json(const char *name, const std::vector<T>& l, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = l.cbegin(); iter != l.cend(); ++iter) {
encode_json("obj", *iter, f);
}
f->close_section();
}
template<class K, class V, class C = std::less<K>>
static void encode_json(const char *name, const std::map<K, V, C>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto i = m.cbegin(); i != m.cend(); ++i) {
f->open_object_section("entry");
encode_json("key", i->first, f);
encode_json("val", i->second, f);
f->close_section();
}
f->close_section();
}
template<class K, class V, class C = std::less<K> >
static void encode_json(const char *name, const boost::container::flat_map<K, V, C>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto i = m.cbegin(); i != m.cend(); ++i) {
f->open_object_section("entry");
encode_json("key", i->first, f);
encode_json("val", i->second, f);
f->close_section();
}
f->close_section();
}
template<class K, class V>
static void encode_json(const char *name, const std::multimap<K, V>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto i = m.begin(); i != m.end(); ++i) {
f->open_object_section("entry");
encode_json("key", i->first, f);
encode_json("val", i->second, f);
f->close_section();
}
f->close_section();
}
template<class K, class V>
static void encode_json(const char *name, const boost::container::flat_map<K, V>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto i = m.begin(); i != m.end(); ++i) {
f->open_object_section("entry");
encode_json("key", i->first, f);
encode_json("val", i->second, f);
f->close_section();
}
f->close_section();
}
template<class K, class V>
void encode_json_map(const char *name, const std::map<K, V>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = m.cbegin(); iter != m.cend(); ++iter) {
encode_json("obj", iter->second, f);
}
f->close_section();
}
template<class K, class V>
void encode_json_map(const char *name, const char *index_name,
const char *object_name, const char *value_name,
void (*cb)(const char *, const V&, ceph::Formatter *, void *), void *parent,
const std::map<K, V>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = m.cbegin(); iter != m.cend(); ++iter) {
if (index_name) {
f->open_object_section("key_value");
f->dump_string(index_name, iter->first);
}
if (object_name) {
f->open_object_section(object_name);
}
if (cb) {
cb(value_name, iter->second, f, parent);
} else {
encode_json(value_name, iter->second, f);
}
if (object_name) {
f->close_section();
}
if (index_name) {
f->close_section();
}
}
f->close_section();
}
template<class K, class V>
void encode_json_map(const char *name, const char *index_name,
const char *object_name, const char *value_name,
const std::map<K, V>& m, ceph::Formatter *f)
{
encode_json_map<K, V>(name, index_name, object_name, value_name, NULL, NULL, m, f);
}
template<class K, class V>
void encode_json_map(const char *name, const char *index_name, const char *value_name,
const std::map<K, V>& m, ceph::Formatter *f)
{
encode_json_map<K, V>(name, index_name, NULL, value_name, NULL, NULL, m, f);
}
template <class T>
static void encode_json(const char *name, const std::optional<T>& o, ceph::Formatter *f)
{
if (!o) {
return;
}
encode_json(name, *o, f);
}
template<class K, class V>
void encode_json_map(const char *name, const boost::container::flat_map<K, V>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = m.cbegin(); iter != m.cend(); ++iter) {
encode_json("obj", iter->second, f);
}
f->close_section();
}
template<class K, class V>
void encode_json_map(const char *name, const char *index_name,
const char *object_name, const char *value_name,
void (*cb)(const char *, const V&, ceph::Formatter *, void *), void *parent,
const boost::container::flat_map<K, V>& m, ceph::Formatter *f)
{
f->open_array_section(name);
for (auto iter = m.cbegin(); iter != m.cend(); ++iter) {
if (index_name) {
f->open_object_section("key_value");
f->dump_string(index_name, iter->first);
}
if (object_name) {
f->open_object_section(object_name);
}
if (cb) {
cb(value_name, iter->second, f, parent);
} else {
encode_json(value_name, iter->second, f);
}
if (object_name) {
f->close_section();
}
if (index_name) {
f->close_section();
}
}
f->close_section();
}
template<class K, class V>
void encode_json_map(const char *name, const char *index_name,
const char *object_name, const char *value_name,
const boost::container::flat_map<K, V>& m, ceph::Formatter *f)
{
encode_json_map<K, V>(name, index_name, object_name, value_name, NULL, NULL, m, f);
}
template<class K, class V>
void encode_json_map(const char *name, const char *index_name, const char *value_name,
const boost::container::flat_map<K, V>& m, ceph::Formatter *f)
{
encode_json_map<K, V>(name, index_name, NULL, value_name, NULL, NULL, m, f);
}
class JSONFormattable : public ceph::JSONFormatter {
JSONObj::data_val value;
std::vector<JSONFormattable> arr;
std::map<std::string, JSONFormattable> obj;
std::vector<JSONFormattable *> enc_stack;
JSONFormattable *cur_enc;
protected:
bool handle_value(std::string_view name, std::string_view s, bool quoted) override;
bool handle_open_section(std::string_view name, const char *ns, bool section_is_array) override;
bool handle_close_section() override;
public:
JSONFormattable(bool p = false) : JSONFormatter(p) {
cur_enc = this;
enc_stack.push_back(cur_enc);
}
enum Type {
FMT_NONE,
FMT_VALUE,
FMT_ARRAY,
FMT_OBJ,
} type{FMT_NONE};
void set_type(Type t) {
type = t;
}
void decode_json(JSONObj *jo) {
if (jo->is_array()) {
set_type(JSONFormattable::FMT_ARRAY);
decode_json_obj(arr, jo);
} else if (jo->is_object()) {
set_type(JSONFormattable::FMT_OBJ);
auto iter = jo->find_first();
for (;!iter.end(); ++iter) {
JSONObj *field = *iter;
decode_json_obj(obj[field->get_name()], field);
}
} else {
set_type(JSONFormattable::FMT_VALUE);
decode_json_obj(value, jo);
}
}
void encode(ceph::buffer::list& bl) const {
ENCODE_START(2, 1, bl);
encode((uint8_t)type, bl);
encode(value.str, bl);
encode(arr, bl);
encode(obj, bl);
encode(value.quoted, bl);
ENCODE_FINISH(bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
DECODE_START(2, bl);
uint8_t t;
decode(t, bl);
type = (Type)t;
decode(value.str, bl);
decode(arr, bl);
decode(obj, bl);
if (struct_v >= 2) {
decode(value.quoted, bl);
} else {
value.quoted = true;
}
DECODE_FINISH(bl);
}
const std::string& val() const {
return value.str;
}
int val_int() const;
long val_long() const;
long long val_long_long() const;
bool val_bool() const;
const std::map<std::string, JSONFormattable> object() const {
return obj;
}
const std::vector<JSONFormattable>& array() const {
return arr;
}
const JSONFormattable& operator[](const std::string& name) const;
const JSONFormattable& operator[](size_t index) const;
JSONFormattable& operator[](const std::string& name);
JSONFormattable& operator[](size_t index);
operator std::string() const {
return value.str;
}
explicit operator int() const {
return val_int();
}
explicit operator long() const {
return val_long();
}
explicit operator long long() const {
return val_long_long();
}
explicit operator bool() const {
return val_bool();
}
template<class T>
T operator[](const std::string& name) const {
return this->operator[](name)(T());
}
template<class T>
T operator[](const std::string& name) {
return this->operator[](name)(T());
}
std::string operator ()(const char *def_val) const {
return def(std::string(def_val));
}
int operator()(int def_val) const {
return def(def_val);
}
bool operator()(bool def_val) const {
return def(def_val);
}
bool exists(const std::string& name) const;
bool exists(size_t index) const;
std::string def(const std::string& def_val) const;
int def(int def_val) const;
bool def(bool def_val) const;
bool find(const std::string& name, std::string *val) const;
std::string get(const std::string& name, const std::string& def_val) const;
int get_int(const std::string& name, int def_val) const;
bool get_bool(const std::string& name, bool def_val) const;
int set(const std::string& name, const std::string& val);
int erase(const std::string& name);
void derive_from(const JSONFormattable& jf);
void encode_json(const char *name, ceph::Formatter *f) const;
bool is_array() const {
return (type == FMT_ARRAY);
}
};
WRITE_CLASS_ENCODER(JSONFormattable)
void encode_json(const char *name, const JSONFormattable& v, ceph::Formatter *f);
#endif
| 23,382 | 24.035332 | 126 | h |
null | ceph-main/src/common/ceph_mutex.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <utility>
#include "common/containers.h"
// What and why
// ============
//
// For general code making use of mutexes, use these ceph:: types.
// The key requirement is that you make use of the ceph::make_mutex()
// and make_recursive_mutex() factory methods, which take a string
// naming the mutex for the purposes of the lockdep debug variant.
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
#include <seastar/core/condition-variable.hh>
#include "crimson/common/log.h"
#include "include/ceph_assert.h"
#ifndef NDEBUG
#define FUT_DEBUG(FMT_MSG, ...) crimson::get_logger(ceph_subsys_).trace(FMT_MSG, ##__VA_ARGS__)
#else
#define FUT_DEBUG(FMT_MSG, ...)
#endif
namespace ceph {
// an empty class satisfying the mutex concept
struct dummy_mutex {
void lock() {}
bool try_lock() {
return true;
}
void unlock() {}
void lock_shared() {}
void unlock_shared() {}
};
struct dummy_shared_mutex : dummy_mutex {
void lock_shared() {}
void unlock_shared() {}
};
// this implementation assumes running within a seastar::thread
struct green_condition_variable : private seastar::condition_variable {
template <class LockT>
void wait(LockT&&) {
FUT_DEBUG("green_condition_variable::{}: before blocking", __func__);
seastar::condition_variable::wait().get();
FUT_DEBUG("green_condition_variable::{}: after blocking", __func__);
}
void notify_one() noexcept {
FUT_DEBUG("green_condition_variable::{}", __func__);
signal();
}
void notify_all() noexcept {
FUT_DEBUG("green_condition_variable::{}", __func__);
broadcast();
}
};
using mutex = dummy_mutex;
using recursive_mutex = dummy_mutex;
using shared_mutex = dummy_shared_mutex;
using condition_variable = green_condition_variable;
template <typename ...Args>
dummy_mutex make_mutex(Args&& ...args) {
return {};
}
template <typename ...Args>
recursive_mutex make_recursive_mutex(Args&& ...args) {
return {};
}
template <typename ...Args>
shared_mutex make_shared_mutex(Args&& ...args) {
return {};
}
#define ceph_mutex_is_locked(m) true
#define ceph_mutex_is_locked_by_me(m) true
}
#else // defined (WITH_SEASTAR) && !defined(WITH_ALIEN)
//
// For legacy Mutex users that passed recursive=true, use
// ceph::make_recursive_mutex. For legacy Mutex users that passed
// lockdep=false, use std::mutex directly.
#ifdef CEPH_DEBUG_MUTEX
// ============================================================================
// debug (lockdep-capable, various sanity checks and asserts)
// ============================================================================
//
// Note: this is known to cause deadlocks on Windows because
// of the winpthreads shared mutex implementation.
#include "common/condition_variable_debug.h"
#include "common/mutex_debug.h"
#include "common/shared_mutex_debug.h"
namespace ceph {
typedef ceph::mutex_debug mutex;
typedef ceph::mutex_recursive_debug recursive_mutex;
typedef ceph::condition_variable_debug condition_variable;
typedef ceph::shared_mutex_debug shared_mutex;
// pass arguments to mutex_debug ctor
template <typename ...Args>
mutex make_mutex(Args&& ...args) {
return {std::forward<Args>(args)...};
}
// pass arguments to recursive_mutex_debug ctor
template <typename ...Args>
recursive_mutex make_recursive_mutex(Args&& ...args) {
return {std::forward<Args>(args)...};
}
// pass arguments to shared_mutex_debug ctor
template <typename ...Args>
shared_mutex make_shared_mutex(Args&& ...args) {
return {std::forward<Args>(args)...};
}
// debug methods
#define ceph_mutex_is_locked(m) ((m).is_locked())
#define ceph_mutex_is_not_locked(m) (!(m).is_locked())
#define ceph_mutex_is_rlocked(m) ((m).is_rlocked())
#define ceph_mutex_is_wlocked(m) ((m).is_wlocked())
#define ceph_mutex_is_locked_by_me(m) ((m).is_locked_by_me())
#define ceph_mutex_is_not_locked_by_me(m) (!(m).is_locked_by_me())
}
#else
// ============================================================================
// release (fast and minimal)
// ============================================================================
#include <condition_variable>
#include <mutex>
// The winpthreads shared mutex implementation is broken.
// We'll use boost::shared_mutex instead.
// https://github.com/msys2/MINGW-packages/issues/3319
#if __MINGW32__
#include <boost/thread/shared_mutex.hpp>
#else
#include <shared_mutex>
#endif
namespace ceph {
typedef std::mutex mutex;
typedef std::recursive_mutex recursive_mutex;
typedef std::condition_variable condition_variable;
#if __MINGW32__
typedef boost::shared_mutex shared_mutex;
#else
typedef std::shared_mutex shared_mutex;
#endif
// discard arguments to make_mutex (they are for debugging only)
template <typename ...Args>
mutex make_mutex(Args&& ...args) {
return {};
}
template <typename ...Args>
recursive_mutex make_recursive_mutex(Args&& ...args) {
return {};
}
template <typename ...Args>
shared_mutex make_shared_mutex(Args&& ...args) {
return {};
}
// debug methods. Note that these can blindly return true
// because any code that does anything other than assert these
// are true is broken.
#define ceph_mutex_is_locked(m) true
#define ceph_mutex_is_not_locked(m) true
#define ceph_mutex_is_rlocked(m) true
#define ceph_mutex_is_wlocked(m) true
#define ceph_mutex_is_locked_by_me(m) true
#define ceph_mutex_is_not_locked_by_me(m) true
}
#endif // CEPH_DEBUG_MUTEX
#endif // WITH_SEASTAR
namespace ceph {
template <class LockT,
class LockFactoryT>
ceph::containers::tiny_vector<LockT> make_lock_container(
const std::size_t num_instances,
LockFactoryT&& lock_factory)
{
return {
num_instances, [&](const std::size_t i, auto emplacer) {
// this will be called `num_instances` times
new (emplacer.data()) LockT {lock_factory(i)};
}
};
}
} // namespace ceph
| 6,126 | 26.977169 | 95 | h |
null | ceph-main/src/common/ceph_releases.cc | #include "ceph_releases.h"
#include <ostream>
#include "ceph_ver.h"
std::ostream& operator<<(std::ostream& os, const ceph_release_t r)
{
return os << ceph_release_name(static_cast<int>(r));
}
ceph_release_t ceph_release()
{
return ceph_release_t{CEPH_RELEASE};
}
ceph_release_t ceph_release_from_name(std::string_view s)
{
ceph_release_t r = ceph_release_t::max;
while (--r != ceph_release_t::unknown) {
if (s == to_string(r)) {
return r;
}
}
return ceph_release_t::unknown;
}
bool can_upgrade_from(ceph_release_t from_release,
std::string_view from_release_name,
std::ostream& err)
{
if (from_release == ceph_release_t::unknown) {
// cannot tell, but i am optimistic
return true;
}
const ceph_release_t cutoff{static_cast<uint8_t>(static_cast<uint8_t>(from_release) + 2)};
const auto to_release = ceph_release();
if (cutoff < to_release) {
err << "recorded " << from_release_name << " "
<< to_integer<int>(from_release) << " (" << from_release << ") "
<< "is more than two releases older than installed "
<< to_integer<int>(to_release) << " (" << to_release << "); "
<< "you can only upgrade 2 releases at a time\n"
<< "you should first upgrade to ";
auto release = from_release;
while (++release <= cutoff) {
err << to_integer<int>(release) << " (" << release << ")";
if (release < cutoff) {
err << " or ";
} else {
err << "\n";
}
}
return false;
} else {
return true;
}
}
| 1,577 | 25.745763 | 92 | cc |
null | ceph-main/src/common/ceph_releases.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <cstdint>
#include <iosfwd>
#include <string_view>
#include "common/ceph_strings.h"
// the C++ version of CEPH_RELEASE_* defined by include/rados.h
enum class ceph_release_t : std::uint8_t {
unknown = 0,
argonaut,
bobtail,
cuttlefish,
dumpling,
emperor,
firefly,
giant,
hammer,
infernalis,
jewel,
kraken,
luminous,
mimic,
nautilus,
octopus,
pacific,
quincy,
reef,
max,
};
std::ostream& operator<<(std::ostream& os, const ceph_release_t r);
inline bool operator!(ceph_release_t& r) {
return (r < ceph_release_t::unknown ||
r == ceph_release_t::unknown);
}
inline ceph_release_t& operator--(ceph_release_t& r) {
r = static_cast<ceph_release_t>(static_cast<uint8_t>(r) - 1);
return r;
}
inline ceph_release_t& operator++(ceph_release_t& r) {
r = static_cast<ceph_release_t>(static_cast<uint8_t>(r) + 1);
return r;
}
inline bool operator<(ceph_release_t lhs, ceph_release_t rhs) {
// we used to use -1 for invalid release
if (static_cast<int8_t>(lhs) < 0) {
return true;
} else if (static_cast<int8_t>(rhs) < 0) {
return false;
}
return static_cast<uint8_t>(lhs) < static_cast<uint8_t>(rhs);
}
inline bool operator>(ceph_release_t lhs, ceph_release_t rhs) {
// we used to use -1 for invalid release
if (static_cast<int8_t>(lhs) < 0) {
return false;
} else if (static_cast<int8_t>(rhs) < 0) {
return true;
}
return static_cast<uint8_t>(lhs) > static_cast<uint8_t>(rhs);
}
inline bool operator>=(ceph_release_t lhs, ceph_release_t rhs) {
return !(lhs < rhs);
}
bool can_upgrade_from(ceph_release_t from_release,
std::string_view from_release_name,
std::ostream& err);
ceph_release_t ceph_release_from_name(std::string_view sv);
ceph_release_t ceph_release();
inline std::string_view to_string(ceph_release_t r) {
return ceph_release_name(static_cast<int>(r));
}
template<typename IntType> IntType to_integer(ceph_release_t r) {
return static_cast<IntType>(r);
}
| 2,108 | 22.433333 | 70 | h |
null | ceph-main/src/common/ceph_strings.cc | /*
* Ceph string constants
*/
#include "ceph_strings.h"
#include "include/types.h"
#include "include/ceph_features.h"
const char *ceph_entity_type_name(int type)
{
switch (type) {
case CEPH_ENTITY_TYPE_MDS: return "mds";
case CEPH_ENTITY_TYPE_OSD: return "osd";
case CEPH_ENTITY_TYPE_MON: return "mon";
case CEPH_ENTITY_TYPE_MGR: return "mgr";
case CEPH_ENTITY_TYPE_CLIENT: return "client";
case CEPH_ENTITY_TYPE_AUTH: return "auth";
default: return "unknown";
}
}
const char *ceph_con_mode_name(int con_mode)
{
switch (con_mode) {
case CEPH_CON_MODE_UNKNOWN: return "unknown";
case CEPH_CON_MODE_CRC: return "crc";
case CEPH_CON_MODE_SECURE: return "secure";
default: return "???";
}
}
const char *ceph_osd_op_name(int op)
{
switch (op) {
#define GENERATE_CASE(op, opcode, str) case CEPH_OSD_OP_##op: return (str);
__CEPH_FORALL_OSD_OPS(GENERATE_CASE)
#undef GENERATE_CASE
default:
return "???";
}
}
const char *ceph_osd_state_name(int s)
{
switch (s) {
case CEPH_OSD_EXISTS:
return "exists";
case CEPH_OSD_UP:
return "up";
case CEPH_OSD_AUTOOUT:
return "autoout";
case CEPH_OSD_NEW:
return "new";
case CEPH_OSD_FULL:
return "full";
case CEPH_OSD_NEARFULL:
return "nearfull";
case CEPH_OSD_BACKFILLFULL:
return "backfillfull";
case CEPH_OSD_DESTROYED:
return "destroyed";
case CEPH_OSD_NOUP:
return "noup";
case CEPH_OSD_NODOWN:
return "nodown";
case CEPH_OSD_NOIN:
return "noin";
case CEPH_OSD_NOOUT:
return "noout";
case CEPH_OSD_STOP:
return "stop";
default:
return "???";
}
}
const char *ceph_release_name(int r)
{
switch (r) {
case CEPH_RELEASE_ARGONAUT:
return "argonaut";
case CEPH_RELEASE_BOBTAIL:
return "bobtail";
case CEPH_RELEASE_CUTTLEFISH:
return "cuttlefish";
case CEPH_RELEASE_DUMPLING:
return "dumpling";
case CEPH_RELEASE_EMPEROR:
return "emperor";
case CEPH_RELEASE_FIREFLY:
return "firefly";
case CEPH_RELEASE_GIANT:
return "giant";
case CEPH_RELEASE_HAMMER:
return "hammer";
case CEPH_RELEASE_INFERNALIS:
return "infernalis";
case CEPH_RELEASE_JEWEL:
return "jewel";
case CEPH_RELEASE_KRAKEN:
return "kraken";
case CEPH_RELEASE_LUMINOUS:
return "luminous";
case CEPH_RELEASE_MIMIC:
return "mimic";
case CEPH_RELEASE_NAUTILUS:
return "nautilus";
case CEPH_RELEASE_OCTOPUS:
return "octopus";
case CEPH_RELEASE_PACIFIC:
return "pacific";
case CEPH_RELEASE_QUINCY:
return "quincy";
case CEPH_RELEASE_REEF:
return "reef";
default:
if (r < 0)
return "unspecified";
return "unknown";
}
}
uint64_t ceph_release_features(int r)
{
uint64_t req = 0;
req |= CEPH_FEATURE_CRUSH_TUNABLES;
if (r <= CEPH_RELEASE_CUTTLEFISH)
return req;
req |= CEPH_FEATURE_CRUSH_TUNABLES2 |
CEPH_FEATURE_OSDHASHPSPOOL;
if (r <= CEPH_RELEASE_EMPEROR)
return req;
req |= CEPH_FEATURE_CRUSH_TUNABLES3 |
CEPH_FEATURE_OSD_PRIMARY_AFFINITY |
CEPH_FEATURE_OSD_CACHEPOOL;
if (r <= CEPH_RELEASE_GIANT)
return req;
req |= CEPH_FEATURE_CRUSH_V4;
if (r <= CEPH_RELEASE_INFERNALIS)
return req;
req |= CEPH_FEATURE_CRUSH_TUNABLES5;
if (r <= CEPH_RELEASE_JEWEL)
return req;
req |= CEPH_FEATURE_MSG_ADDR2;
if (r <= CEPH_RELEASE_KRAKEN)
return req;
req |= CEPH_FEATUREMASK_CRUSH_CHOOSE_ARGS; // and overlaps
if (r <= CEPH_RELEASE_LUMINOUS)
return req;
return req;
}
/* return oldest/first release that supports these features */
int ceph_release_from_features(uint64_t features)
{
int r = 1;
while (true) {
uint64_t need = ceph_release_features(r);
if ((need & features) != need ||
r == CEPH_RELEASE_MAX) {
r--;
need = ceph_release_features(r);
/* we want the first release that looks like this */
while (r > 1 && ceph_release_features(r - 1) == need) {
r--;
}
break;
}
++r;
}
return r;
}
const char *ceph_osd_watch_op_name(int o)
{
switch (o) {
case CEPH_OSD_WATCH_OP_UNWATCH:
return "unwatch";
case CEPH_OSD_WATCH_OP_WATCH:
return "watch";
case CEPH_OSD_WATCH_OP_RECONNECT:
return "reconnect";
case CEPH_OSD_WATCH_OP_PING:
return "ping";
default:
return "???";
}
}
const char *ceph_osd_alloc_hint_flag_name(int f)
{
switch (f) {
case CEPH_OSD_ALLOC_HINT_FLAG_SEQUENTIAL_WRITE:
return "sequential_write";
case CEPH_OSD_ALLOC_HINT_FLAG_RANDOM_WRITE:
return "random_write";
case CEPH_OSD_ALLOC_HINT_FLAG_SEQUENTIAL_READ:
return "sequential_read";
case CEPH_OSD_ALLOC_HINT_FLAG_RANDOM_READ:
return "random_read";
case CEPH_OSD_ALLOC_HINT_FLAG_APPEND_ONLY:
return "append_only";
case CEPH_OSD_ALLOC_HINT_FLAG_IMMUTABLE:
return "immutable";
case CEPH_OSD_ALLOC_HINT_FLAG_SHORTLIVED:
return "shortlived";
case CEPH_OSD_ALLOC_HINT_FLAG_LONGLIVED:
return "longlived";
case CEPH_OSD_ALLOC_HINT_FLAG_COMPRESSIBLE:
return "compressible";
case CEPH_OSD_ALLOC_HINT_FLAG_INCOMPRESSIBLE:
return "incompressible";
default:
return "???";
}
}
const char *ceph_mds_state_name(int s)
{
switch (s) {
/* down and out */
case CEPH_MDS_STATE_DNE: return "down:dne";
case CEPH_MDS_STATE_STOPPED: return "down:stopped";
case CEPH_MDS_STATE_DAMAGED: return "down:damaged";
/* up and out */
case CEPH_MDS_STATE_BOOT: return "up:boot";
case CEPH_MDS_STATE_STANDBY: return "up:standby";
case CEPH_MDS_STATE_STANDBY_REPLAY: return "up:standby-replay";
case CEPH_MDS_STATE_REPLAYONCE: return "up:oneshot-replay";
case CEPH_MDS_STATE_CREATING: return "up:creating";
case CEPH_MDS_STATE_STARTING: return "up:starting";
/* up and in */
case CEPH_MDS_STATE_REPLAY: return "up:replay";
case CEPH_MDS_STATE_RESOLVE: return "up:resolve";
case CEPH_MDS_STATE_RECONNECT: return "up:reconnect";
case CEPH_MDS_STATE_REJOIN: return "up:rejoin";
case CEPH_MDS_STATE_CLIENTREPLAY: return "up:clientreplay";
case CEPH_MDS_STATE_ACTIVE: return "up:active";
case CEPH_MDS_STATE_STOPPING: return "up:stopping";
/* misc */
case CEPH_MDS_STATE_NULL: return "null";
}
return "???";
}
const char *ceph_session_op_name(int op)
{
switch (op) {
case CEPH_SESSION_REQUEST_OPEN: return "request_open";
case CEPH_SESSION_OPEN: return "open";
case CEPH_SESSION_REQUEST_CLOSE: return "request_close";
case CEPH_SESSION_CLOSE: return "close";
case CEPH_SESSION_REQUEST_RENEWCAPS: return "request_renewcaps";
case CEPH_SESSION_RENEWCAPS: return "renewcaps";
case CEPH_SESSION_STALE: return "stale";
case CEPH_SESSION_RECALL_STATE: return "recall_state";
case CEPH_SESSION_FLUSHMSG: return "flushmsg";
case CEPH_SESSION_FLUSHMSG_ACK: return "flushmsg_ack";
case CEPH_SESSION_FORCE_RO: return "force_ro";
case CEPH_SESSION_REJECT: return "reject";
case CEPH_SESSION_REQUEST_FLUSH_MDLOG: return "request_flushmdlog";
}
return "???";
}
const char *ceph_mds_op_name(int op)
{
switch (op) {
case CEPH_MDS_OP_LOOKUP: return "lookup";
case CEPH_MDS_OP_LOOKUPHASH: return "lookuphash";
case CEPH_MDS_OP_LOOKUPPARENT: return "lookupparent";
case CEPH_MDS_OP_LOOKUPINO: return "lookupino";
case CEPH_MDS_OP_LOOKUPNAME: return "lookupname";
case CEPH_MDS_OP_GETATTR: return "getattr";
case CEPH_MDS_OP_DUMMY: return "dummy";
case CEPH_MDS_OP_SETXATTR: return "setxattr";
case CEPH_MDS_OP_SETATTR: return "setattr";
case CEPH_MDS_OP_RMXATTR: return "rmxattr";
case CEPH_MDS_OP_SETLAYOUT: return "setlayou";
case CEPH_MDS_OP_SETDIRLAYOUT: return "setdirlayout";
case CEPH_MDS_OP_READDIR: return "readdir";
case CEPH_MDS_OP_MKNOD: return "mknod";
case CEPH_MDS_OP_LINK: return "link";
case CEPH_MDS_OP_UNLINK: return "unlink";
case CEPH_MDS_OP_RENAME: return "rename";
case CEPH_MDS_OP_MKDIR: return "mkdir";
case CEPH_MDS_OP_RMDIR: return "rmdir";
case CEPH_MDS_OP_SYMLINK: return "symlink";
case CEPH_MDS_OP_CREATE: return "create";
case CEPH_MDS_OP_OPEN: return "open";
case CEPH_MDS_OP_LOOKUPSNAP: return "lookupsnap";
case CEPH_MDS_OP_LSSNAP: return "lssnap";
case CEPH_MDS_OP_MKSNAP: return "mksnap";
case CEPH_MDS_OP_RMSNAP: return "rmsnap";
case CEPH_MDS_OP_RENAMESNAP: return "renamesnap";
case CEPH_MDS_OP_READDIR_SNAPDIFF: return "readdir_snapdiff";
case CEPH_MDS_OP_SETFILELOCK: return "setfilelock";
case CEPH_MDS_OP_GETFILELOCK: return "getfilelock";
case CEPH_MDS_OP_FRAGMENTDIR: return "fragmentdir";
case CEPH_MDS_OP_EXPORTDIR: return "exportdir";
case CEPH_MDS_OP_FLUSH: return "flush_path";
case CEPH_MDS_OP_ENQUEUE_SCRUB: return "enqueue_scrub";
case CEPH_MDS_OP_REPAIR_FRAGSTATS: return "repair_fragstats";
case CEPH_MDS_OP_REPAIR_INODESTATS: return "repair_inodestats";
}
return "???";
}
const char *ceph_cap_op_name(int op)
{
switch (op) {
case CEPH_CAP_OP_GRANT: return "grant";
case CEPH_CAP_OP_REVOKE: return "revoke";
case CEPH_CAP_OP_TRUNC: return "trunc";
case CEPH_CAP_OP_EXPORT: return "export";
case CEPH_CAP_OP_IMPORT: return "import";
case CEPH_CAP_OP_UPDATE: return "update";
case CEPH_CAP_OP_DROP: return "drop";
case CEPH_CAP_OP_FLUSH: return "flush";
case CEPH_CAP_OP_FLUSH_ACK: return "flush_ack";
case CEPH_CAP_OP_FLUSHSNAP: return "flushsnap";
case CEPH_CAP_OP_FLUSHSNAP_ACK: return "flushsnap_ack";
case CEPH_CAP_OP_RELEASE: return "release";
case CEPH_CAP_OP_RENEW: return "renew";
}
return "???";
}
const char *ceph_lease_op_name(int o)
{
switch (o) {
case CEPH_MDS_LEASE_REVOKE: return "revoke";
case CEPH_MDS_LEASE_RELEASE: return "release";
case CEPH_MDS_LEASE_RENEW: return "renew";
case CEPH_MDS_LEASE_REVOKE_ACK: return "revoke_ack";
}
return "???";
}
const char *ceph_snap_op_name(int o)
{
switch (o) {
case CEPH_SNAP_OP_UPDATE: return "update";
case CEPH_SNAP_OP_CREATE: return "create";
case CEPH_SNAP_OP_DESTROY: return "destroy";
case CEPH_SNAP_OP_SPLIT: return "split";
}
return "???";
}
const char *ceph_watch_event_name(int e)
{
switch (e) {
case CEPH_WATCH_EVENT_NOTIFY: return "notify";
case CEPH_WATCH_EVENT_NOTIFY_COMPLETE: return "notify_complete";
case CEPH_WATCH_EVENT_DISCONNECT: return "disconnect";
}
return "???";
}
const char *ceph_pool_op_name(int op)
{
switch (op) {
case POOL_OP_CREATE: return "create";
case POOL_OP_DELETE: return "delete";
case POOL_OP_AUID_CHANGE: return "auid change"; // (obsolete)
case POOL_OP_CREATE_SNAP: return "create snap";
case POOL_OP_DELETE_SNAP: return "delete snap";
case POOL_OP_CREATE_UNMANAGED_SNAP: return "create unmanaged snap";
case POOL_OP_DELETE_UNMANAGED_SNAP: return "delete unmanaged snap";
}
return "???";
}
const char *ceph_osd_backoff_op_name(int op)
{
switch (op) {
case CEPH_OSD_BACKOFF_OP_BLOCK: return "block";
case CEPH_OSD_BACKOFF_OP_ACK_BLOCK: return "ack-block";
case CEPH_OSD_BACKOFF_OP_UNBLOCK: return "unblock";
}
return "???";
}
| 10,775 | 26.560102 | 75 | cc |
null | ceph-main/src/common/ceph_strings.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <cstdint>
const char *ceph_entity_type_name(int type);
const char *ceph_con_mode_name(int con_mode);
const char *ceph_osd_op_name(int op);
const char *ceph_osd_state_name(int s);
const char *ceph_release_name(int r);
std::uint64_t ceph_release_features(int r);
int ceph_release_from_features(std::uint64_t features);
const char *ceph_osd_watch_op_name(int o);
const char *ceph_osd_alloc_hint_flag_name(int f);
const char *ceph_mds_state_name(int s);
const char *ceph_session_op_name(int op);
const char *ceph_mds_op_name(int op);
const char *ceph_cap_op_name(int op);
const char *ceph_lease_op_name(int o);
const char *ceph_snap_op_name(int o);
const char *ceph_watch_event_name(int e);
const char *ceph_pool_op_name(int op);
const char *ceph_osd_backoff_op_name(int op);
| 895 | 33.461538 | 70 | h |
null | ceph-main/src/common/ceph_time.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.
*
*/
// For ceph_timespec
#include "ceph_time.h"
#include <fmt/chrono.h>
#include <fmt/ostream.h>
#include "log/LogClock.h"
#include "config.h"
#include "strtol.h"
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#ifndef NSEC_PER_SEC
#define NSEC_PER_SEC 1000000000ULL
#endif
int clock_gettime(int clk_id, struct timespec *tp)
{
if (clk_id == CLOCK_REALTIME) {
// gettimeofday is much faster than clock_get_time
struct timeval now;
int ret = gettimeofday(&now, NULL);
if (ret)
return ret;
tp->tv_sec = now.tv_sec;
tp->tv_nsec = now.tv_usec * 1000L;
} else {
uint64_t t = mach_absolute_time();
static mach_timebase_info_data_t timebase_info;
if (timebase_info.denom == 0) {
(void)mach_timebase_info(&timebase_info);
}
auto nanos = t * timebase_info.numer / timebase_info.denom;
tp->tv_sec = nanos / NSEC_PER_SEC;
tp->tv_nsec = nanos - (tp->tv_sec * NSEC_PER_SEC);
}
return 0;
}
#endif
using namespace std::literals;
namespace ceph {
using std::chrono::seconds;
using std::chrono::nanoseconds;
void real_clock::to_ceph_timespec(const time_point& t,
struct ceph_timespec& ts) {
ts.tv_sec = to_time_t(t);
ts.tv_nsec = (t.time_since_epoch() % 1s).count();
}
struct ceph_timespec real_clock::to_ceph_timespec(const time_point& t) {
struct ceph_timespec ts;
to_ceph_timespec(t, ts);
return ts;
}
real_clock::time_point real_clock::from_ceph_timespec(
const struct ceph_timespec& ts) {
return time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
}
void coarse_real_clock::to_ceph_timespec(const time_point& t,
struct ceph_timespec& ts) {
ts.tv_sec = to_time_t(t);
ts.tv_nsec = (t.time_since_epoch() % seconds(1)).count();
}
struct ceph_timespec coarse_real_clock::to_ceph_timespec(
const time_point& t) {
struct ceph_timespec ts;
to_ceph_timespec(t, ts);
return ts;
}
coarse_real_clock::time_point coarse_real_clock::from_ceph_timespec(
const struct ceph_timespec& ts) {
return time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
}
using std::chrono::duration_cast;
using std::chrono::seconds;
using std::chrono::microseconds;
template<typename Clock,
typename std::enable_if<Clock::is_steady>::type*>
std::ostream& operator<<(std::ostream& m,
const std::chrono::time_point<Clock>& t) {
return m << std::fixed << std::chrono::duration<double>(
t.time_since_epoch()).count()
<< 's';
}
template<typename Clock,
typename std::enable_if<!Clock::is_steady>::type*>
std::ostream& operator<<(std::ostream& m,
const std::chrono::time_point<Clock>& t) {
m.setf(std::ios::right);
char oldfill = m.fill();
m.fill('0');
// localtime. this looks like an absolute time.
// conform to http://en.wikipedia.org/wiki/ISO_8601
struct tm bdt;
time_t tt = Clock::to_time_t(t);
localtime_r(&tt, &bdt);
char tz[32] = { 0 };
strftime(tz, sizeof(tz), "%z", &bdt);
m << std::setw(4) << (bdt.tm_year+1900) // 2007 -> '07'
<< '-' << std::setw(2) << (bdt.tm_mon+1)
<< '-' << std::setw(2) << bdt.tm_mday
<< 'T'
<< std::setw(2) << bdt.tm_hour
<< ':' << std::setw(2) << bdt.tm_min
<< ':' << std::setw(2) << bdt.tm_sec
<< "." << std::setw(6) << duration_cast<microseconds>(
t.time_since_epoch() % seconds(1)).count()
<< tz;
m.fill(oldfill);
m.unsetf(std::ios::right);
return m;
}
template std::ostream&
operator<< <mono_clock>(std::ostream& m, const mono_time& t);
template std::ostream&
operator<< <real_clock>(std::ostream& m, const real_time& t);
template std::ostream&
operator<< <coarse_mono_clock>(std::ostream& m, const coarse_mono_time& t);
template std::ostream&
operator<< <coarse_real_clock>(std::ostream& m, const coarse_real_time& t);
std::string timespan_str(timespan t)
{
// FIXME: somebody pretty please make a version of this function
// that isn't as lame as this one!
uint64_t nsec = std::chrono::nanoseconds(t).count();
std::ostringstream ss;
if (nsec < 2'000'000'000) {
ss << ((float)nsec / 1'000'000'000) << "s";
return ss.str();
}
uint64_t sec = nsec / 1'000'000'000;
if (sec < 120) {
ss << sec << "s";
return ss.str();
}
uint64_t min = sec / 60;
if (min < 120) {
ss << min << "m";
return ss.str();
}
uint64_t hr = min / 60;
if (hr < 48) {
ss << hr << "h";
return ss.str();
}
uint64_t day = hr / 24;
if (day < 14) {
ss << day << "d";
return ss.str();
}
uint64_t wk = day / 7;
if (wk < 12) {
ss << wk << "w";
return ss.str();
}
uint64_t mn = day / 30;
if (mn < 24) {
ss << mn << "M";
return ss.str();
}
uint64_t yr = day / 365;
ss << yr << "y";
return ss.str();
}
std::string exact_timespan_str(timespan t)
{
uint64_t nsec = std::chrono::nanoseconds(t).count();
uint64_t sec = nsec / 1'000'000'000;
nsec %= 1'000'000'000;
uint64_t yr = sec / (60 * 60 * 24 * 365);
std::ostringstream ss;
if (yr) {
ss << yr << "y";
sec -= yr * (60 * 60 * 24 * 365);
}
uint64_t mn = sec / (60 * 60 * 24 * 30);
if (mn >= 3) {
ss << mn << "mo";
sec -= mn * (60 * 60 * 24 * 30);
}
uint64_t wk = sec / (60 * 60 * 24 * 7);
if (wk >= 2) {
ss << wk << "w";
sec -= wk * (60 * 60 * 24 * 7);
}
uint64_t day = sec / (60 * 60 * 24);
if (day >= 2) {
ss << day << "d";
sec -= day * (60 * 60 * 24);
}
uint64_t hr = sec / (60 * 60);
if (hr >= 2) {
ss << hr << "h";
sec -= hr * (60 * 60);
}
uint64_t min = sec / 60;
if (min >= 2) {
ss << min << "m";
sec -= min * 60;
}
if (sec || nsec) {
if (nsec) {
ss << (((float)nsec / 1'000'000'000) + sec) << "s";
} else {
ss << sec << "s";
}
}
return ss.str();
}
std::chrono::seconds parse_timespan(const std::string& s)
{
static std::map<std::string,int> units = {
{ "s", 1 },
{ "sec", 1 },
{ "second", 1 },
{ "seconds", 1 },
{ "m", 60 },
{ "min", 60 },
{ "minute", 60 },
{ "minutes", 60 },
{ "h", 60*60 },
{ "hr", 60*60 },
{ "hour", 60*60 },
{ "hours", 60*60 },
{ "d", 24*60*60 },
{ "day", 24*60*60 },
{ "days", 24*60*60 },
{ "w", 7*24*60*60 },
{ "wk", 7*24*60*60 },
{ "week", 7*24*60*60 },
{ "weeks", 7*24*60*60 },
{ "mo", 30*24*60*60 },
{ "month", 30*24*60*60 },
{ "months", 30*24*60*60 },
{ "y", 365*24*60*60 },
{ "yr", 365*24*60*60 },
{ "year", 365*24*60*60 },
{ "years", 365*24*60*60 },
};
auto r = 0s;
auto pos = 0u;
while (pos < s.size()) {
// skip whitespace
while (std::isspace(s[pos])) {
++pos;
}
if (pos >= s.size()) {
break;
}
// consume any digits
auto val_start = pos;
while (std::isdigit(s[pos])) {
++pos;
}
if (val_start == pos) {
throw std::invalid_argument("expected digit");
}
auto n = s.substr(val_start, pos - val_start);
std::string err;
auto val = strict_strtoll(n.c_str(), 10, &err);
if (err.size()) {
throw std::invalid_argument(err);
}
// skip whitespace
while (std::isspace(s[pos])) {
++pos;
}
// consume unit
auto unit_start = pos;
while (std::isalpha(s[pos])) {
++pos;
}
if (unit_start != pos) {
auto unit = s.substr(unit_start, pos - unit_start);
auto p = units.find(unit);
if (p == units.end()) {
throw std::invalid_argument("unrecogized unit '"s + unit + "'");
}
val *= p->second;
} else if (pos < s.size()) {
throw std::invalid_argument("unexpected trailing '"s + s.substr(pos) + "'");
}
r += std::chrono::seconds(val);
}
return r;
}
}
namespace std {
template<typename Rep, typename Period>
ostream& operator<<(ostream& m, const chrono::duration<Rep, Period>& t) {
if constexpr (chrono::treat_as_floating_point_v<Rep> ||
Period::den > 1) {
using seconds_t = chrono::duration<float>;
::fmt::print(m, "{:.9}", chrono::duration_cast<seconds_t>(t));
} else {
::fmt::print(m, "{}", t);
}
return m;
}
template ostream&
operator<< <::ceph::timespan::rep,
::ceph::timespan::period> (ostream&, const ::ceph::timespan&);
template ostream&
operator<< <::ceph::signedspan::rep,
::ceph::signedspan::period> (ostream&, const ::ceph::signedspan&);
template ostream&
operator<< <chrono::seconds::rep,
chrono::seconds::period> (ostream&, const chrono::seconds&);
template ostream&
operator<< <chrono::milliseconds::rep,
chrono::milliseconds::period> (ostream&, const chrono::milliseconds&);
} // namespace std
| 9,023 | 24.709402 | 82 | cc |
null | ceph-main/src/common/ceph_time.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 COMMON_CEPH_TIME_H
#define COMMON_CEPH_TIME_H
#include <chrono>
#include <iostream>
#include <string>
#include <optional>
#if FMT_VERSION >= 90000
#include <fmt/ostream.h>
#endif
#include <sys/time.h>
#if defined(__APPLE__)
#include <sys/_types/_timespec.h>
#define CLOCK_REALTIME_COARSE CLOCK_REALTIME
#define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
int clock_gettime(int clk_id, struct timespec *tp);
#endif
#ifdef _WIN32
// Clock precision:
// mingw < 8.0.1:
// * CLOCK_REALTIME: ~10-55ms (GetSystemTimeAsFileTime)
// mingw >= 8.0.1:
// * CLOCK_REALTIME: <1us (GetSystemTimePreciseAsFileTime)
// * CLOCK_REALTIME_COARSE: ~10-55ms (GetSystemTimeAsFileTime)
//
// * CLOCK_MONOTONIC: <1us if TSC is usable, ~10-55ms otherwise
// (QueryPerformanceCounter)
// https://github.com/mirror/mingw-w64/commit/dcd990ed423381cf35702df9495d44f1979ebe50
#ifndef CLOCK_REALTIME_COARSE
#define CLOCK_REALTIME_COARSE CLOCK_REALTIME
#endif
#ifndef CLOCK_MONOTONIC_COARSE
#define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
#endif
#endif
struct ceph_timespec;
namespace ceph {
// Currently we use a 64-bit count of nanoseconds.
// We could, if we wished, use a struct holding a uint64_t count
// of seconds and a uint32_t count of nanoseconds.
// At least this way we can change it to something else if we
// want.
typedef uint64_t rep;
// duration is the concrete time representation for our code in the
// case that we are only interested in durations between now and the
// future. Using it means we don't have to have EVERY function that
// deals with a duration be a template. We can do so for user-facing
// APIs, however.
typedef std::chrono::duration<rep, std::nano> timespan;
// Like the above but signed.
typedef int64_t signed_rep;
// Similar to the above but for durations that can specify
// differences between now and a time point in the past.
typedef std::chrono::duration<signed_rep, std::nano> signedspan;
template<typename Duration>
struct timeval to_timeval(Duration d) {
struct timeval tv;
auto sec = std::chrono::duration_cast<std::chrono::seconds>(d);
tv.tv_sec = sec.count();
auto usec = std::chrono::duration_cast<std::chrono::microseconds>(d-sec);
tv.tv_usec = usec.count();
return tv;
}
// We define our own clocks so we can have our choice of all time
// sources supported by the operating system. With the standard
// library the resolution and cost are unspecified. (For example,
// the libc++ system_clock class gives only microsecond
// resolution.)
// One potential issue is that we should accept system_clock
// timepoints in user-facing APIs alongside (or instead of)
// ceph::real_clock times.
// High-resolution real-time clock
class real_clock {
public:
typedef timespan duration;
typedef duration::rep rep;
typedef duration::period period;
// The second template parameter defaults to the clock's duration
// type.
typedef std::chrono::time_point<real_clock> time_point;
static constexpr const bool is_steady = false;
static time_point now() noexcept {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return from_timespec(ts);
}
static bool is_zero(const time_point& t) {
return (t == time_point::min());
}
static time_point zero() {
return time_point::min();
}
// Allow conversion to/from any clock with the same interface as
// std::chrono::system_clock)
template<typename Clock, typename Duration>
static time_point to_system_time_point(
const std::chrono::time_point<Clock, Duration>& t) {
return time_point(seconds(Clock::to_time_t(t)) +
std::chrono::duration_cast<duration>(t.time_since_epoch() %
std::chrono::seconds(1)));
}
template<typename Clock, typename Duration>
static std::chrono::time_point<Clock, Duration> to_system_time_point(
const time_point& t) {
return (Clock::from_time_t(to_time_t(t)) +
std::chrono::duration_cast<Duration>(t.time_since_epoch() %
std::chrono::seconds(1)));
}
static time_t to_time_t(const time_point& t) noexcept {
return std::chrono::duration_cast<std::chrono::seconds>(t.time_since_epoch()).count();
}
static time_point from_time_t(const time_t& t) noexcept {
return time_point(std::chrono::seconds(t));
}
static void to_timespec(const time_point& t, struct timespec& ts) {
ts.tv_sec = to_time_t(t);
ts.tv_nsec = (t.time_since_epoch() % std::chrono::seconds(1)).count();
}
static struct timespec to_timespec(const time_point& t) {
struct timespec ts;
to_timespec(t, ts);
return ts;
}
static time_point from_timespec(const struct timespec& ts) {
return time_point(std::chrono::seconds(ts.tv_sec) +
std::chrono::nanoseconds(ts.tv_nsec));
}
static void to_ceph_timespec(const time_point& t,
struct ceph_timespec& ts);
static struct ceph_timespec to_ceph_timespec(const time_point& t);
static time_point from_ceph_timespec(const struct ceph_timespec& ts);
static void to_timeval(const time_point& t, struct timeval& tv) {
tv.tv_sec = to_time_t(t);
tv.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>(
t.time_since_epoch() % std::chrono::seconds(1)).count();
}
static struct timeval to_timeval(const time_point& t) {
struct timeval tv;
to_timeval(t, tv);
return tv;
}
static time_point from_timeval(const struct timeval& tv) {
return time_point(std::chrono::seconds(tv.tv_sec) +
std::chrono::microseconds(tv.tv_usec));
}
static double to_double(const time_point& t) {
return std::chrono::duration<double>(t.time_since_epoch()).count();
}
static time_point from_double(const double d) {
return time_point(std::chrono::duration_cast<duration>(
std::chrono::duration<double>(d)));
}
};
// Low-resolution but preusmably faster real-time clock
class coarse_real_clock {
public:
typedef timespan duration;
typedef duration::rep rep;
typedef duration::period period;
// The second template parameter defaults to the clock's duration
// type.
typedef std::chrono::time_point<coarse_real_clock> time_point;
static constexpr const bool is_steady = false;
static time_point now() noexcept {
struct timespec ts;
#if defined(CLOCK_REALTIME_COARSE)
// Linux systems have _COARSE clocks.
clock_gettime(CLOCK_REALTIME_COARSE, &ts);
#elif defined(CLOCK_REALTIME_FAST)
// BSD systems have _FAST clocks.
clock_gettime(CLOCK_REALTIME_FAST, &ts);
#else
// And if we find neither, you may wish to consult your system's
// documentation.
#warning Falling back to CLOCK_REALTIME, may be slow.
clock_gettime(CLOCK_REALTIME, &ts);
#endif
return from_timespec(ts);
}
static bool is_zero(const time_point& t) {
return (t == time_point::min());
}
static time_point zero() {
return time_point::min();
}
static time_t to_time_t(const time_point& t) noexcept {
return std::chrono::duration_cast<std::chrono::seconds>(
t.time_since_epoch()).count();
}
static time_point from_time_t(const time_t t) noexcept {
return time_point(std::chrono::seconds(t));
}
static void to_timespec(const time_point& t, struct timespec& ts) {
ts.tv_sec = to_time_t(t);
ts.tv_nsec = (t.time_since_epoch() % std::chrono::seconds(1)).count();
}
static struct timespec to_timespec(const time_point& t) {
struct timespec ts;
to_timespec(t, ts);
return ts;
}
static time_point from_timespec(const struct timespec& ts) {
return time_point(std::chrono::seconds(ts.tv_sec) +
std::chrono::nanoseconds(ts.tv_nsec));
}
static void to_ceph_timespec(const time_point& t,
struct ceph_timespec& ts);
static struct ceph_timespec to_ceph_timespec(const time_point& t);
static time_point from_ceph_timespec(const struct ceph_timespec& ts);
static void to_timeval(const time_point& t, struct timeval& tv) {
tv.tv_sec = to_time_t(t);
tv.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>(
t.time_since_epoch() % std::chrono::seconds(1)).count();
}
static struct timeval to_timeval(const time_point& t) {
struct timeval tv;
to_timeval(t, tv);
return tv;
}
static time_point from_timeval(const struct timeval& tv) {
return time_point(std::chrono::seconds(tv.tv_sec) +
std::chrono::microseconds(tv.tv_usec));
}
static double to_double(const time_point& t) {
return std::chrono::duration<double>(t.time_since_epoch()).count();
}
static time_point from_double(const double d) {
return time_point(std::chrono::duration_cast<duration>(
std::chrono::duration<double>(d)));
}
};
// High-resolution monotonic clock
class mono_clock {
public:
typedef timespan duration;
typedef duration::rep rep;
typedef duration::period period;
typedef std::chrono::time_point<mono_clock> time_point;
static constexpr const bool is_steady = true;
static time_point now() noexcept {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return time_point(std::chrono::seconds(ts.tv_sec) +
std::chrono::nanoseconds(ts.tv_nsec));
}
static bool is_zero(const time_point& t) {
return (t == time_point::min());
}
static time_point zero() {
return time_point::min();
}
};
// Low-resolution but, I would hope or there's no point, faster
// monotonic clock
class coarse_mono_clock {
public:
typedef timespan duration;
typedef duration::rep rep;
typedef duration::period period;
typedef std::chrono::time_point<coarse_mono_clock> time_point;
static constexpr const bool is_steady = true;
static time_point now() noexcept {
struct timespec ts;
#if defined(CLOCK_MONOTONIC_COARSE)
// Linux systems have _COARSE clocks.
clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
#elif defined(CLOCK_MONOTONIC_FAST)
// BSD systems have _FAST clocks.
clock_gettime(CLOCK_MONOTONIC_FAST, &ts);
#else
// And if we find neither, you may wish to consult your system's
// documentation.
#warning Falling back to CLOCK_MONOTONIC, may be slow.
clock_gettime(CLOCK_MONOTONIC, &ts);
#endif
return time_point(std::chrono::seconds(ts.tv_sec) +
std::chrono::nanoseconds(ts.tv_nsec));
}
static bool is_zero(const time_point& t) {
return (t == time_point::min());
}
static time_point zero() {
return time_point::min();
}
};
namespace time_detail {
// So that our subtractions produce negative spans rather than
// arithmetic underflow.
template<typename Rep1, typename Period1, typename Rep2,
typename Period2>
inline auto difference(std::chrono::duration<Rep1, Period1> minuend,
std::chrono::duration<Rep2, Period2> subtrahend)
-> typename std::common_type<
std::chrono::duration<typename std::make_signed<Rep1>::type,
Period1>,
std::chrono::duration<typename std::make_signed<Rep2>::type,
Period2> >::type {
// Foo.
using srep =
typename std::common_type<
std::chrono::duration<typename std::make_signed<Rep1>::type,
Period1>,
std::chrono::duration<typename std::make_signed<Rep2>::type,
Period2> >::type;
return srep(srep(minuend).count() - srep(subtrahend).count());
}
template<typename Clock, typename Duration1, typename Duration2>
inline auto difference(
typename std::chrono::time_point<Clock, Duration1> minuend,
typename std::chrono::time_point<Clock, Duration2> subtrahend)
-> typename std::common_type<
std::chrono::duration<typename std::make_signed<
typename Duration1::rep>::type,
typename Duration1::period>,
std::chrono::duration<typename std::make_signed<
typename Duration2::rep>::type,
typename Duration2::period> >::type {
return difference(minuend.time_since_epoch(),
subtrahend.time_since_epoch());
}
}
// Please note that the coarse clocks are disjoint. You cannot
// subtract a real_clock timepoint from a coarse_real_clock
// timepoint as, from C++'s perspective, they are disjoint types.
// This is not necessarily bad. If I sample a mono_clock and then a
// coarse_mono_clock, the coarse_mono_clock's time could potentially
// be previous to the mono_clock's time (just due to differing
// resolution) which would be Incorrect.
// This is not horrible, though, since you can use an idiom like
// mono_clock::timepoint(coarsepoint.time_since_epoch()) to unwrap
// and rewrap if you know what you're doing.
// Actual wall-clock times
typedef real_clock::time_point real_time;
typedef coarse_real_clock::time_point coarse_real_time;
// Monotonic times should never be serialized or communicated
// between machines, since they are incomparable. Thus we also don't
// make any provision for converting between
// std::chrono::steady_clock time and ceph::mono_clock time.
typedef mono_clock::time_point mono_time;
typedef coarse_mono_clock::time_point coarse_mono_time;
template<typename Rep1, typename Ratio1, typename Rep2, typename Ratio2>
auto floor(const std::chrono::duration<Rep1, Ratio1>& duration,
const std::chrono::duration<Rep2, Ratio2>& precision) ->
typename std::common_type<std::chrono::duration<Rep1, Ratio1>,
std::chrono::duration<Rep2, Ratio2> >::type {
return duration - (duration % precision);
}
template<typename Rep1, typename Ratio1, typename Rep2, typename Ratio2>
auto ceil(const std::chrono::duration<Rep1, Ratio1>& duration,
const std::chrono::duration<Rep2, Ratio2>& precision) ->
typename std::common_type<std::chrono::duration<Rep1, Ratio1>,
std::chrono::duration<Rep2, Ratio2> >::type {
auto tmod = duration % precision;
return duration - tmod + (tmod > tmod.zero() ? 1 : 0) * precision;
}
template<typename Clock, typename Duration, typename Rep, typename Ratio>
auto floor(const std::chrono::time_point<Clock, Duration>& timepoint,
const std::chrono::duration<Rep, Ratio>& precision) ->
std::chrono::time_point<Clock,
typename std::common_type<
Duration, std::chrono::duration<Rep, Ratio>
>::type> {
return std::chrono::time_point<
Clock, typename std::common_type<
Duration, std::chrono::duration<Rep, Ratio> >::type>(
floor(timepoint.time_since_epoch(), precision));
}
template<typename Clock, typename Duration, typename Rep, typename Ratio>
auto ceil(const std::chrono::time_point<Clock, Duration>& timepoint,
const std::chrono::duration<Rep, Ratio>& precision) ->
std::chrono::time_point<Clock,
typename std::common_type<
Duration,
std::chrono::duration<Rep, Ratio> >::type> {
return std::chrono::time_point<
Clock, typename std::common_type<
Duration, std::chrono::duration<Rep, Ratio> >::type>(
ceil(timepoint.time_since_epoch(), precision));
}
inline timespan make_timespan(const double d) {
return std::chrono::duration_cast<timespan>(
std::chrono::duration<double>(d));
}
inline std::optional<timespan> maybe_timespan(const double d) {
return d ? std::make_optional(make_timespan(d)) : std::nullopt;
}
template<typename Clock,
typename std::enable_if<!Clock::is_steady>::type* = nullptr>
std::ostream& operator<<(std::ostream& m,
const std::chrono::time_point<Clock>& t);
template<typename Clock,
typename std::enable_if<Clock::is_steady>::type* = nullptr>
std::ostream& operator<<(std::ostream& m,
const std::chrono::time_point<Clock>& t);
// The way std::chrono handles the return type of subtraction is not
// wonderful. The difference of two unsigned types SHOULD be signed.
inline signedspan operator -(real_time minuend,
real_time subtrahend) {
return time_detail::difference(minuend, subtrahend);
}
inline signedspan operator -(coarse_real_time minuend,
coarse_real_time subtrahend) {
return time_detail::difference(minuend, subtrahend);
}
inline signedspan operator -(mono_time minuend,
mono_time subtrahend) {
return time_detail::difference(minuend, subtrahend);
}
inline signedspan operator -(coarse_mono_time minuend,
coarse_mono_time subtrahend) {
return time_detail::difference(minuend, subtrahend);
}
// We could add specializations of time_point - duration and
// time_point + duration to assert on overflow, but I don't think we
// should.
inline timespan abs(signedspan z) {
return z > signedspan::zero() ?
std::chrono::duration_cast<timespan>(z) :
timespan(-z.count());
}
inline timespan to_timespan(signedspan z) {
if (z < signedspan::zero()) {
//ceph_assert(z >= signedspan::zero());
// There is a kernel bug that seems to be triggering this assert. We've
// seen it in:
// centos 8.1: 4.18.0-147.el8.x86_64
// debian 10.3: 4.19.0-8-amd64
// debian 10.1: 4.19.67-2+deb10u1
// ubuntu 18.04
// see bugs:
// https://tracker.ceph.com/issues/43365
// https://tracker.ceph.com/issues/44078
z = signedspan::zero();
}
return std::chrono::duration_cast<timespan>(z);
}
std::string timespan_str(timespan t);
std::string exact_timespan_str(timespan t);
std::chrono::seconds parse_timespan(const std::string& s);
// detects presence of Clock::to_timespec() and from_timespec()
template <typename Clock, typename = std::void_t<>>
struct converts_to_timespec : std::false_type {};
template <typename Clock>
struct converts_to_timespec<Clock, std::void_t<decltype(
Clock::from_timespec(Clock::to_timespec(
std::declval<typename Clock::time_point>()))
)>> : std::true_type {};
template <typename Clock>
constexpr bool converts_to_timespec_v = converts_to_timespec<Clock>::value;
template<typename Rep, typename T>
static Rep to_seconds(T t) {
return std::chrono::duration_cast<
std::chrono::duration<Rep>>(t).count();
}
template<typename Rep, typename T>
static Rep to_microseconds(T t) {
return std::chrono::duration_cast<
std::chrono::duration<
Rep,
std::micro>>(t).count();
}
} // namespace ceph
namespace std {
template<typename Rep, typename Period>
ostream& operator<<(ostream& m, const chrono::duration<Rep, Period>& t);
}
#if FMT_VERSION >= 90000
template<typename Clock>
struct fmt::formatter<std::chrono::time_point<Clock>> : fmt::ostream_formatter {};
#endif
#endif // COMMON_CEPH_TIME_H
| 18,525 | 32.200717 | 90 | h |
null | ceph-main/src/common/ceph_timer.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 COMMON_CEPH_TIMER_H
#define COMMON_CEPH_TIMER_H
#include <cassert>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
#include <boost/intrusive/set.hpp>
#include "include/function2.hpp"
#include "include/compat.h"
#include "common/detail/construct_suspended.h"
namespace bi = boost::intrusive;
namespace ceph {
// Compared to the SafeTimer this does fewer allocations (you
// don't have to allocate a new Context every time you
// want to cue the next tick.)
//
// It also does not share a lock with the caller. If you call
// cancel event, it either cancels the event (and returns true) or
// you missed it. If this does not work for you, you can set up a
// flag and mutex of your own.
//
// You get to pick your clock. I like mono_clock, since I usually
// want to wait FOR a given duration. real_clock is worthwhile if
// you want to wait UNTIL a specific moment of wallclock time. If
// you want you can set up a timer that executes a function after
// you use up ten seconds of CPU time.
template<typename TC>
class timer {
using sh = bi::set_member_hook<bi::link_mode<bi::normal_link>>;
struct event {
typename TC::time_point t = typename TC::time_point::min();
std::uint64_t id = 0;
fu2::unique_function<void()> f;
sh schedule_link;
sh event_link;
event() = default;
event(typename TC::time_point t, std::uint64_t id,
fu2::unique_function<void()> f) : t(t), id(id), f(std::move(f)) {}
event(const event&) = delete;
event& operator =(const event&) = delete;
event(event&&) = delete;
event& operator =(event&&) = delete;
bool operator <(const event& e) const noexcept {
return t == e.t ? id < e.id : t < e.t;
}
};
struct id_key {
using type = std::uint64_t;
const type& operator ()(const event& e) const noexcept {
return e.id;
}
};
bi::set<event, bi::member_hook<event, sh, &event::schedule_link>,
bi::constant_time_size<false>> schedule;
bi::set<event, bi::member_hook<event, sh, &event::event_link>,
bi::constant_time_size<false>,
bi::key_of_value<id_key>> events;
std::mutex lock;
std::condition_variable cond;
event* running = nullptr;
std::uint64_t next_id = 0;
bool suspended;
std::thread thread;
void timer_thread() {
std::unique_lock l(lock);
while (!suspended) {
auto now = TC::now();
while (!schedule.empty()) {
auto p = schedule.begin();
// Should we wait for the future?
if (p->t > now)
break;
auto& e = *p;
schedule.erase(e);
events.erase(e.id);
// Since we have only one thread it is impossible to have more
// than one running event
running = &e;
l.unlock();
p->f();
l.lock();
if (running) {
running = nullptr;
delete &e;
} // Otherwise the event requeued itself
}
if (suspended)
break;
if (schedule.empty()) {
cond.wait(l);
} else {
// Since wait_until takes its parameter by reference, passing
// the time /in the event/ is unsafe, as it might be canceled
// while we wait.
const auto t = schedule.begin()->t;
cond.wait_until(l, t);
}
}
}
public:
timer() : suspended(false) {
thread = std::thread(&timer::timer_thread, this);
ceph_pthread_setname(thread.native_handle(), "ceph_timer");
}
// Create a suspended timer, jobs will be executed in order when
// it is resumed.
timer(construct_suspended_t) : suspended(true) {}
timer(const timer&) = delete;
timer& operator =(const timer&) = delete;
~timer() {
suspend();
cancel_all_events();
}
// Suspend operation of the timer (and let its thread die).
void suspend() {
std::unique_lock l(lock);
if (suspended)
return;
suspended = true;
cond.notify_one();
l.unlock();
thread.join();
}
// Resume operation of the timer. (Must have been previously
// suspended.)
void resume() {
std::unique_lock l(lock);
if (!suspended)
return;
suspended = false;
assert(!thread.joinable());
thread = std::thread(&timer::timer_thread, this);
}
// Schedule an event in the relative future
template<typename Callable, typename... Args>
std::uint64_t add_event(typename TC::duration duration,
Callable&& f, Args&&... args) {
return add_event(TC::now() + duration,
std::forward<Callable>(f),
std::forward<Args>(args)...);
}
// Schedule an event in the absolute future
template<typename Callable, typename... Args>
std::uint64_t add_event(typename TC::time_point when,
Callable&& f, Args&&... args) {
std::lock_guard l(lock);
auto e = std::make_unique<event>(when, ++next_id,
std::bind(std::forward<Callable>(f),
std::forward<Args>(args)...));
auto id = e->id;
auto i = schedule.insert(*e);
events.insert(*(e.release()));
/* If the event we have just inserted comes before everything
* else, we need to adjust our timeout. */
if (i.first == schedule.begin())
cond.notify_one();
// Previously each event was a context, identified by a
// pointer, and each context to be called only once. Since you
// can queue the same function pointer, member function,
// lambda, or functor up multiple times, identifying things by
// function for the purposes of cancellation is no longer
// suitable. Thus:
return id;
}
// Adjust the timeout of a currently-scheduled event (relative)
bool adjust_event(std::uint64_t id, typename TC::duration duration) {
return adjust_event(id, TC::now() + duration);
}
// Adjust the timeout of a currently-scheduled event (absolute)
bool adjust_event(std::uint64_t id, typename TC::time_point when) {
std::lock_guard l(lock);
auto it = events.find(id);
if (it == events.end())
return false;
auto& e = *it;
schedule.erase(e);
e.t = when;
schedule.insert(e);
return true;
}
// Cancel an event. If the event has already come and gone (or you
// never submitted it) you will receive false. Otherwise you will
// receive true and it is guaranteed the event will not execute.
bool cancel_event(const std::uint64_t id) {
std::lock_guard l(lock);
auto p = events.find(id);
if (p == events.end()) {
return false;
}
auto& e = *p;
events.erase(e.id);
schedule.erase(e);
delete &e;
return true;
}
// Reschedules a currently running event in the relative
// future. Must be called only from an event executed by this
// timer. If you have a function that can be called either from
// this timer or some other way, it is your responsibility to make
// sure it can tell the difference only does not call
// reschedule_me in the non-timer case.
//
// Returns an event id. If you had an event_id from the first
// scheduling, replace it with this return value.
std::uint64_t reschedule_me(typename TC::duration duration) {
return reschedule_me(TC::now() + duration);
}
// Reschedules a currently running event in the absolute
// future. Must be called only from an event executed by this
// timer. if you have a function that can be called either from
// this timer or some other way, it is your responsibility to make
// sure it can tell the difference only does not call
// reschedule_me in the non-timer case.
//
// Returns an event id. If you had an event_id from the first
// scheduling, replace it with this return value.
std::uint64_t reschedule_me(typename TC::time_point when) {
assert(std::this_thread::get_id() == thread.get_id());
std::lock_guard l(lock);
running->t = when;
std::uint64_t id = ++next_id;
running->id = id;
schedule.insert(*running);
events.insert(*running);
// Hacky, but keeps us from being deleted
running = nullptr;
// Same function, but you get a new ID.
return id;
}
// Remove all events from the queue.
void cancel_all_events() {
std::lock_guard l(lock);
while (!events.empty()) {
auto p = events.begin();
event& e = *p;
schedule.erase(e);
events.erase(e.id);
delete &e;
}
}
}; // timer
} // namespace ceph
#endif
| 8,643 | 26.616613 | 71 | h |
null | ceph-main/src/common/cmdparse.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "include/common_fwd.h"
#include "common/cmdparse.h"
#include "common/Formatter.h"
#include "common/debug.h"
#include "common/strtol.h"
#include "json_spirit/json_spirit.h"
using std::is_same_v;
using std::ostringstream;
using std::string;
using std::stringstream;
using std::string_view;
using std::vector;
using namespace std::literals;
/**
* Given a cmddesc like "foo baz name=bar,type=CephString",
* return the prefix "foo baz".
*/
namespace ceph::common {
std::string cmddesc_get_prefix(const std::string_view &cmddesc)
{
string tmp(cmddesc); // FIXME: stringstream ctor can't take string_view :(
stringstream ss(tmp);
std::string word;
std::ostringstream result;
bool first = true;
while (std::getline(ss, word, ' ')) {
if (word.find_first_of(",=") != string::npos) {
break;
}
if (!first) {
result << " ";
}
result << word;
first = false;
}
return result.str();
}
using arg_desc_t = std::map<std::string_view, std::string_view>;
// Snarf up all the key=val,key=val pairs, put 'em in a dict.
arg_desc_t cmddesc_get_args(const string_view cmddesc)
{
arg_desc_t arg_desc;
for_each_substr(cmddesc, ",", [&](auto kv) {
// key=value; key by itself implies value is bool true
// name="name" means arg dict will be titled 'name'
auto equal = kv.find('=');
if (equal == kv.npos) {
// it should be the command
return;
}
auto key = kv.substr(0, equal);
auto val = kv.substr(equal + 1);
arg_desc[key] = val;
});
return arg_desc;
}
std::string cmddesc_get_prenautilus_compat(const std::string &cmddesc)
{
std::vector<std::string> out;
stringstream ss(cmddesc);
std::string word;
bool changed = false;
while (std::getline(ss, word, ' ')) {
// if no , or =, must be a plain word to put out
if (word.find_first_of(",=") == string::npos) {
out.push_back(word);
continue;
}
auto desckv = cmddesc_get_args(word);
auto j = desckv.find("type");
if (j != desckv.end() && j->second == "CephBool") {
// Instruct legacy clients or mons to send --foo-bar string in place
// of a 'true'/'false' value
std::ostringstream oss;
oss << "--" << desckv["name"];
std::string val = oss.str();
std::replace(val.begin(), val.end(), '_', '-');
desckv["type"] = "CephChoices";
desckv["strings"] = val;
std::ostringstream fss;
for (auto k = desckv.begin(); k != desckv.end(); ++k) {
if (k != desckv.begin()) {
fss << ",";
}
fss << k->first << "=" << k->second;
}
out.push_back(fss.str());
changed = true;
} else {
out.push_back(word);
}
}
if (!changed) {
return cmddesc;
}
std::string o;
for (auto i = out.begin(); i != out.end(); ++i) {
if (i != out.begin()) {
o += " ";
}
o += *i;
}
return o;
}
/**
* Read a command description list out of cmd, and dump it to f.
* A signature description is a set of space-separated words;
* see MonCommands.h for more info.
*/
void
dump_cmd_to_json(Formatter *f, uint64_t features, const string& cmd)
{
// put whole command signature in an already-opened container
// elements are: "name", meaning "the typeless name that means a literal"
// an object {} with key:value pairs representing an argument
stringstream ss(cmd);
std::string word;
bool positional = true;
while (std::getline(ss, word, ' ')) {
if (word == "--") {
positional = false;
continue;
}
// if no , or =, must be a plain word to put out
if (word.find_first_of(",=") == string::npos) {
f->dump_string("arg", word);
continue;
}
// accumulate descriptor keywords in desckv
auto desckv = cmddesc_get_args(word);
// name the individual desc object based on the name key
f->open_object_section(desckv["name"]);
// Compatibility for pre-nautilus clients that don't know about CephBool
std::string val;
if (!HAVE_FEATURE(features, SERVER_NAUTILUS)) {
auto i = desckv.find("type");
if (i != desckv.end() && i->second == "CephBool") {
// Instruct legacy clients to send --foo-bar string in place
// of a 'true'/'false' value
std::ostringstream oss;
oss << "--" << desckv["name"];
val = oss.str();
std::replace(val.begin(), val.end(), '_', '-');
desckv["type"] = "CephChoices";
desckv["strings"] = val;
}
}
// dump all the keys including name into the array
if (!positional) {
desckv["positional"] = "false";
}
for (auto [key, value] : desckv) {
if (key == "positional") {
if (!HAVE_FEATURE(features, SERVER_QUINCY)) {
continue;
}
f->dump_bool(key, value == "true" || value == "True");
} else if (key == "req" && HAVE_FEATURE(features, SERVER_QUINCY)) {
f->dump_bool(key, value == "true" || value == "True");
} else {
f->dump_string(key, value);
}
}
f->close_section(); // attribute object for individual desc
}
}
void
dump_cmd_and_help_to_json(Formatter *jf,
uint64_t features,
const string& secname,
const string& cmdsig,
const string& helptext)
{
jf->open_object_section(secname);
jf->open_array_section("sig");
dump_cmd_to_json(jf, features, cmdsig);
jf->close_section(); // sig array
jf->dump_string("help", helptext);
jf->close_section(); // cmd
}
void
dump_cmddesc_to_json(Formatter *jf,
uint64_t features,
const string& secname,
const string& cmdsig,
const string& helptext,
const string& module,
const string& perm,
uint64_t flags)
{
jf->open_object_section(secname);
jf->open_array_section("sig");
dump_cmd_to_json(jf, features, cmdsig);
jf->close_section(); // sig array
jf->dump_string("help", helptext);
jf->dump_string("module", module);
jf->dump_string("perm", perm);
jf->dump_int("flags", flags);
jf->close_section(); // cmd
}
void cmdmap_dump(const cmdmap_t &cmdmap, Formatter *f)
{
ceph_assert(f != nullptr);
class dump_visitor : public boost::static_visitor<void>
{
Formatter *f;
std::string const &key;
public:
dump_visitor(Formatter *f_, std::string const &key_)
: f(f_), key(key_)
{
}
void operator()(const std::string &operand) const
{
f->dump_string(key, operand);
}
void operator()(const bool &operand) const
{
f->dump_bool(key, operand);
}
void operator()(const int64_t &operand) const
{
f->dump_int(key, operand);
}
void operator()(const double &operand) const
{
f->dump_float(key, operand);
}
void operator()(const std::vector<std::string> &operand) const
{
f->open_array_section(key);
for (const auto& i : operand) {
f->dump_string("item", i);
}
f->close_section();
}
void operator()(const std::vector<int64_t> &operand) const
{
f->open_array_section(key);
for (const auto i : operand) {
f->dump_int("item", i);
}
f->close_section();
}
void operator()(const std::vector<double> &operand) const
{
f->open_array_section(key);
for (const auto i : operand) {
f->dump_float("item", i);
}
f->close_section();
}
};
//f->open_object_section("cmdmap");
for (const auto &i : cmdmap) {
boost::apply_visitor(dump_visitor(f, i.first), i.second);
}
//f->close_section();
}
/** Parse JSON in vector cmd into a map from field to map of values
* (use mValue/mObject)
* 'cmd' should not disappear over lifetime of map
* 'mapp' points to the caller's map
* 'ss' captures any errors during JSON parsing; if function returns
* false, ss is valid */
bool
cmdmap_from_json(const vector<string>& cmd, cmdmap_t *mapp, std::ostream& ss)
{
json_spirit::mValue v;
string fullcmd;
// First, join all cmd strings
for (auto& c : cmd)
fullcmd += c;
try {
if (!json_spirit::read(fullcmd, v))
throw std::runtime_error("unparseable JSON " + fullcmd);
if (v.type() != json_spirit::obj_type)
throw std::runtime_error("not JSON object " + fullcmd);
// allocate new mObject (map) to return
// make sure all contents are simple types (not arrays or objects)
json_spirit::mObject o = v.get_obj();
for (auto it = o.begin(); it != o.end(); ++it) {
// ok, marshal it into our string->cmd_vartype map, or throw an
// exception if it's not a simple datatype. This is kind of
// annoying, since json_spirit has a boost::variant inside it
// already, but it's not public. Oh well.
switch (it->second.type()) {
case json_spirit::obj_type:
default:
throw std::runtime_error("JSON array/object not allowed " + fullcmd);
break;
case json_spirit::array_type:
{
// array is a vector of values. Unpack it to a vector
// of strings, doubles, or int64_t, the only types we handle.
const vector<json_spirit::mValue>& spvals = it->second.get_array();
if (spvals.empty()) {
// if an empty array is acceptable, the caller should always check for
// vector<string> if the expected value of "vector<int64_t>" in the
// cmdmap is missing.
(*mapp)[it->first] = vector<string>();
} else if (spvals.front().type() == json_spirit::str_type) {
vector<string> outv;
for (const auto& sv : spvals) {
if (sv.type() != json_spirit::str_type) {
throw std::runtime_error("Can't handle arrays of multiple types");
}
outv.push_back(sv.get_str());
}
(*mapp)[it->first] = std::move(outv);
} else if (spvals.front().type() == json_spirit::int_type) {
vector<int64_t> outv;
for (const auto& sv : spvals) {
if (spvals.front().type() != json_spirit::int_type) {
throw std::runtime_error("Can't handle arrays of multiple types");
}
outv.push_back(sv.get_int64());
}
(*mapp)[it->first] = std::move(outv);
} else if (spvals.front().type() == json_spirit::real_type) {
vector<double> outv;
for (const auto& sv : spvals) {
if (spvals.front().type() != json_spirit::real_type) {
throw std::runtime_error("Can't handle arrays of multiple types");
}
outv.push_back(sv.get_real());
}
(*mapp)[it->first] = std::move(outv);
} else {
throw std::runtime_error("Can't handle arrays of types other than "
"int, string, or double");
}
}
break;
case json_spirit::str_type:
(*mapp)[it->first] = it->second.get_str();
break;
case json_spirit::bool_type:
(*mapp)[it->first] = it->second.get_bool();
break;
case json_spirit::int_type:
(*mapp)[it->first] = it->second.get_int64();
break;
case json_spirit::real_type:
(*mapp)[it->first] = it->second.get_real();
break;
}
}
return true;
} catch (const std::runtime_error &e) {
ss << e.what();
return false;
}
}
class stringify_visitor : public boost::static_visitor<string>
{
public:
template <typename T>
string operator()(T &operand) const
{
ostringstream oss;
oss << operand;
return oss.str();
}
};
string
cmd_vartype_stringify(const cmd_vartype &v)
{
return boost::apply_visitor(stringify_visitor(), v);
}
void
handle_bad_get(CephContext *cct, const string& k, const char *tname)
{
ostringstream errstr;
int status;
const char *typestr = abi::__cxa_demangle(tname, 0, 0, &status);
if (status != 0)
typestr = tname;
errstr << "bad boost::get: key " << k << " is not type " << typestr;
lderr(cct) << errstr.str() << dendl;
ostringstream oss;
oss << ClibBackTrace(1);
lderr(cct) << oss.str() << dendl;
if (status == 0)
free((char *)typestr);
}
long parse_pos_long(const char *s, std::ostream *pss)
{
if (*s == '-' || *s == '+') {
if (pss)
*pss << "expected numerical value, got: " << s;
return -EINVAL;
}
string err;
long r = strict_strtol(s, 10, &err);
if ((r == 0) && !err.empty()) {
if (pss)
*pss << err;
return -1;
}
if (r < 0) {
if (pss)
*pss << "unable to parse positive integer '" << s << "'";
return -1;
}
return r;
}
int parse_osd_id(const char *s, std::ostream *pss)
{
// osd.NNN?
if (strncmp(s, "osd.", 4) == 0) {
s += 4;
}
// NNN?
ostringstream ss;
long id = parse_pos_long(s, &ss);
if (id < 0) {
*pss << ss.str();
return id;
}
if (id > 0xffff) {
*pss << "osd id " << id << " is too large";
return -ERANGE;
}
return id;
}
namespace {
template <typename Func>
bool find_first_in(std::string_view s, const char *delims, Func&& f)
{
auto pos = s.find_first_not_of(delims);
while (pos != s.npos) {
s.remove_prefix(pos);
auto end = s.find_first_of(delims);
if (f(s.substr(0, end))) {
return true;
}
pos = s.find_first_not_of(delims, end);
}
return false;
}
template<typename T>
T str_to_num(const std::string& s)
{
if constexpr (is_same_v<T, int>) {
return std::stoi(s);
} else if constexpr (is_same_v<T, long>) {
return std::stol(s);
} else if constexpr (is_same_v<T, long long>) {
return std::stoll(s);
} else if constexpr (is_same_v<T, double>) {
return std::stod(s);
}
}
template<typename T>
bool arg_in_range(T value, const arg_desc_t& desc, std::ostream& os) {
auto range = desc.find("range");
if (range == desc.end()) {
return true;
}
auto min_max = get_str_list(string(range->second), "|");
auto min = str_to_num<T>(min_max.front());
auto max = std::numeric_limits<T>::max();
if (min_max.size() > 1) {
max = str_to_num<T>(min_max.back());
}
if (value < min || value > max) {
os << "'" << value << "' out of range: " << min_max;
return false;
}
return true;
}
bool validate_str_arg(std::string_view value,
std::string_view type,
const arg_desc_t& desc,
std::ostream& os)
{
if (type == "CephIPAddr") {
entity_addr_t addr;
if (addr.parse(value)) {
return true;
} else {
os << "failed to parse addr '" << value << "', should be ip:[port]";
return false;
}
} else if (type == "CephChoices") {
auto choices = desc.find("strings");
ceph_assert(choices != end(desc));
auto strings = choices->second;
if (find_first_in(strings, "|", [=](auto choice) {
return (value == choice);
})) {
return true;
} else {
os << "'" << value << "' not belong to '" << strings << "'";
return false;
}
} else {
// CephString or other types like CephPgid
return true;
}
}
bool validate_bool(const cmdmap_t& cmdmap,
const arg_desc_t& desc,
const std::string_view name,
const std::string_view type,
std::ostream& os)
{
bool v;
try {
if (!cmd_getval(cmdmap, name, v)) {
if (auto req = desc.find("req");
req != end(desc) && req->second == "false") {
return true;
} else {
os << "missing required parameter: '" << name << "'";
return false;
}
}
return true;
} catch (const bad_cmd_get& e) {
return false;
}
}
template<bool is_vector,
typename T,
typename Value = std::conditional_t<is_vector,
vector<T>,
T>>
bool validate_arg(const cmdmap_t& cmdmap,
const arg_desc_t& desc,
const std::string_view name,
const std::string_view type,
std::ostream& os)
{
Value v;
try {
if (!cmd_getval(cmdmap, name, v)) {
if constexpr (is_vector) {
// an empty list is acceptable.
return true;
} else {
if (auto req = desc.find("req");
req != end(desc) && req->second == "false") {
return true;
} else {
os << "missing required parameter: '" << name << "'";
return false;
}
}
}
} catch (const bad_cmd_get& e) {
return false;
}
auto validate = [&](const T& value) {
if constexpr (is_same_v<std::string, T>) {
return validate_str_arg(value, type, desc, os);
} else if constexpr (is_same_v<int64_t, T> ||
is_same_v<double, T>) {
return arg_in_range(value, desc, os);
}
};
if constexpr(is_vector) {
return find_if_not(begin(v), end(v), validate) == end(v);
} else {
return validate(v);
}
}
} // anonymous namespace
bool validate_cmd(const std::string& desc,
const cmdmap_t& cmdmap,
std::ostream& os)
{
return !find_first_in(desc, " ", [&](auto desc) {
auto arg_desc = cmddesc_get_args(desc);
if (arg_desc.empty()) {
return false;
}
ceph_assert(arg_desc.count("name"));
ceph_assert(arg_desc.count("type"));
auto name = arg_desc["name"];
auto type = arg_desc["type"];
if (arg_desc.count("n")) {
if (type == "CephInt") {
return !validate_arg<true, int64_t>(cmdmap, arg_desc,
name, type, os);
} else if (type == "CephFloat") {
return !validate_arg<true, double>(cmdmap, arg_desc,
name, type, os);
} else {
return !validate_arg<true, string>(cmdmap, arg_desc,
name, type, os);
}
} else {
if (type == "CephInt") {
return !validate_arg<false, int64_t>(cmdmap, arg_desc,
name, type, os);
} else if (type == "CephFloat") {
return !validate_arg<false, double>(cmdmap, arg_desc,
name, type, os);
} else if (type == "CephBool") {
return !validate_bool(cmdmap, arg_desc,
name, type, os);
} else {
return !validate_arg<false, string>(cmdmap, arg_desc,
name, type, os);
}
}
});
}
bool cmd_getval(const cmdmap_t& cmdmap,
std::string_view k, bool& val)
{
/*
* Specialized getval for booleans. CephBool didn't exist before Nautilus,
* so earlier clients are sent a CephChoices argdesc instead, and will
* send us a "--foo-bar" value string for boolean arguments.
*/
auto found = cmdmap.find(k);
if (found == cmdmap.end()) {
return false;
}
try {
val = boost::get<bool>(found->second);
return true;
} catch (boost::bad_get&) {
try {
std::string expected{"--"};
expected += k;
std::replace(expected.begin(), expected.end(), '_', '-');
std::string v_str = boost::get<std::string>(found->second);
if (v_str == expected) {
val = true;
return true;
} else {
throw bad_cmd_get(k, cmdmap);
}
} catch (boost::bad_get&) {
throw bad_cmd_get(k, cmdmap);
}
}
}
bool cmd_getval_compat_cephbool(
const cmdmap_t& cmdmap,
const std::string& k, bool& val)
{
try {
return cmd_getval(cmdmap, k, val);
} catch (bad_cmd_get& e) {
// try as legacy/compat CephChoices
std::string t;
if (!cmd_getval(cmdmap, k, t)) {
return false;
}
std::string expected = "--"s + k;
std::replace(expected.begin(), expected.end(), '_', '-');
val = (t == expected);
return true;
}
}
}
| 19,223 | 25.013532 | 77 | cc |
null | ceph-main/src/common/cmdparse.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_COMMON_CMDPARSE_H
#define CEPH_COMMON_CMDPARSE_H
#include <vector>
#include <stdexcept>
#include <optional>
#include <ostream>
#include <boost/variant.hpp>
#include "include/ceph_assert.h" // boost clobbers this
#include "include/common_fwd.h"
#include "common/Formatter.h"
#include "common/BackTrace.h"
typedef boost::variant<std::string,
bool,
int64_t,
double,
std::vector<std::string>,
std::vector<int64_t>,
std::vector<double>> cmd_vartype;
typedef std::map<std::string, cmd_vartype, std::less<>> cmdmap_t;
namespace ceph::common {
std::string cmddesc_get_prefix(const std::string_view &cmddesc);
std::string cmddesc_get_prenautilus_compat(const std::string &cmddesc);
void dump_cmd_to_json(ceph::Formatter *f, uint64_t features,
const std::string& cmd);
void dump_cmd_and_help_to_json(ceph::Formatter *f,
uint64_t features,
const std::string& secname,
const std::string& cmd,
const std::string& helptext);
void dump_cmddesc_to_json(ceph::Formatter *jf,
uint64_t features,
const std::string& secname,
const std::string& cmdsig,
const std::string& helptext,
const std::string& module,
const std::string& perm,
uint64_t flags);
bool cmdmap_from_json(const std::vector<std::string>& cmd, cmdmap_t *mapp,
std::ostream& ss);
void cmdmap_dump(const cmdmap_t &cmdmap, ceph::Formatter *f);
void handle_bad_get(CephContext *cct, const std::string& k, const char *name);
std::string cmd_vartype_stringify(const cmd_vartype& v);
struct bad_cmd_get : public std::exception {
std::string desc;
bad_cmd_get(std::string_view f, const cmdmap_t& cmdmap) {
desc += "bad or missing field '";
desc += f;
desc += "'";
}
const char *what() const throw() override {
return desc.c_str();
}
};
bool cmd_getval(const cmdmap_t& cmdmap,
std::string_view k, bool& val);
bool cmd_getval_compat_cephbool(
const cmdmap_t& cmdmap,
const std::string& k, bool& val);
template <typename T>
bool cmd_getval(const cmdmap_t& cmdmap,
std::string_view k, T& val)
{
auto found = cmdmap.find(k);
if (found == cmdmap.end()) {
return false;
}
try {
val = boost::get<T>(found->second);
return true;
} catch (boost::bad_get&) {
throw bad_cmd_get(k, cmdmap);
}
}
template <typename T>
std::optional<T> cmd_getval(const cmdmap_t& cmdmap,
std::string_view k)
{
T ret;
if (const bool found = cmd_getval(cmdmap, k, ret); found) {
return std::make_optional(std::move(ret));
} else {
return std::nullopt;
}
}
// with default
template <typename T, typename V>
T cmd_getval_or(const cmdmap_t& cmdmap, std::string_view k,
const V& defval)
{
auto found = cmdmap.find(k);
if (found == cmdmap.end()) {
return T(defval);
}
try {
return boost::get<T>(cmdmap.find(k)->second);
} catch (boost::bad_get&) {
throw bad_cmd_get(k, cmdmap);
}
}
template <typename T>
void
cmd_putval(CephContext *cct, cmdmap_t& cmdmap, std::string_view k, const T& val)
{
cmdmap.insert_or_assign(std::string{k}, val);
}
bool validate_cmd(const std::string& desc,
const cmdmap_t& cmdmap,
std::ostream& os);
extern int parse_osd_id(const char *s, std::ostream *pss);
extern long parse_pos_long(const char *s, std::ostream *pss = NULL);
}
#endif
| 3,517 | 26.271318 | 80 | h |
null | ceph-main/src/common/code_environment.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/code_environment.h"
#include <iostream>
#include "acconfig.h"
#ifdef HAVE_PTHREAD_GETNAME_NP
#include <pthread.h>
#endif
#include <string.h>
code_environment_t g_code_env = CODE_ENVIRONMENT_UTILITY;
extern "C" const char *code_environment_to_str(enum code_environment_t e)
{
switch (e) {
case CODE_ENVIRONMENT_UTILITY:
return "CODE_ENVIRONMENT_UTILITY";
case CODE_ENVIRONMENT_DAEMON:
return "CODE_ENVIRONMENT_DAEMON";
case CODE_ENVIRONMENT_LIBRARY:
return "CODE_ENVIRONMENT_LIBRARY";
default:
return NULL;
}
}
std::ostream &operator<<(std::ostream &oss, const enum code_environment_t e)
{
oss << code_environment_to_str(e);
return oss;
}
#if defined(HAVE_PTHREAD_GETNAME_NP) && !defined(_WIN32)
int get_process_name(char *buf, int len)
{
if (len <= 16) {
// The man page discourages using pthread_getname_np() with a buffer shorter
// than 16 bytes. With a 16-byte buffer, it might not be null-terminated.
return -ENAMETOOLONG;
}
// FIPS zeroization audit 20191115: this memset is not security related.
memset(buf, 0, len);
return pthread_getname_np(pthread_self(), buf, len);
}
#elif defined(HAVE_GETPROGNAME)
int get_process_name(char *buf, int len)
{
if (len <= 0) {
return -EINVAL;
}
const char *progname = getprogname();
if (progname == nullptr || *progname == '\0') {
return -ENOSYS;
}
strncpy(buf, progname, len - 1);
buf[len - 1] = '\0';
return 0;
}
#elif defined(_WIN32)
int get_process_name(char *buf, int len)
{
if (len <= 0) {
return -EINVAL;
}
char full_path[MAX_PATH];
int length = GetModuleFileNameA(nullptr, full_path, sizeof(full_path));
if (length <= 0)
return -ENOSYS;
char* start = strrchr(full_path, '\\');
if (!start)
return -ENOSYS;
start++;
char* end = strstr(start, ".exe");
if (!end)
return -ENOSYS;
if (len <= end - start) {
return -ENAMETOOLONG;
}
memcpy(buf, start, end - start);
buf[end - start] = '\0';
return 0;
}
#else
int get_process_name(char *buf, int len)
{
return -ENOSYS;
}
#endif
std::string get_process_name_cpp()
{
char buf[32];
if (get_process_name(buf, sizeof(buf))) {
return "(unknown)";
}
return std::string(buf);
}
| 2,668 | 20.015748 | 80 | cc |
null | ceph-main/src/common/code_environment.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_CODE_ENVIRONMENT_H
#define CEPH_COMMON_CODE_ENVIRONMENT_H
enum code_environment_t {
CODE_ENVIRONMENT_UTILITY = 0,
CODE_ENVIRONMENT_DAEMON = 1,
CODE_ENVIRONMENT_LIBRARY = 2,
CODE_ENVIRONMENT_UTILITY_NODOUT = 3,
};
#ifdef __cplusplus
#include <iosfwd>
#include <string>
extern "C" code_environment_t g_code_env;
extern "C" const char *code_environment_to_str(enum code_environment_t e);
std::ostream &operator<<(std::ostream &oss, const enum code_environment_t e);
extern "C" int get_process_name(char *buf, int len);
std::string get_process_name_cpp();
#else
extern code_environment_t g_code_env;
const char *code_environment_to_str(const enum code_environment_t e);
extern int get_process_name(char *buf, int len);
#endif
#endif
| 1,173 | 25.681818 | 77 | h |
null | ceph-main/src/common/cohort_lru.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Copyright (C) 2015 CohortFS, LLC.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef COHORT_LRU_H
#define COHORT_LRU_H
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/slist.hpp>
#include "common/likely.h"
#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 64 /* XXX arch-specific define */
#endif
#define CACHE_PAD(_n) char __pad ## _n [CACHE_LINE_SIZE]
namespace cohort {
namespace lru {
namespace bi = boost::intrusive;
/* public flag values */
constexpr uint32_t FLAG_NONE = 0x0000;
constexpr uint32_t FLAG_INITIAL = 0x0001;
constexpr uint32_t FLAG_RECYCLE = 0x0002;
enum class Edge : std::uint8_t
{
MRU = 0,
LRU
};
typedef bi::link_mode<bi::safe_link> link_mode;
class ObjectFactory; // Forward declaration
class Object
{
private:
uint32_t lru_flags;
std::atomic<uint32_t> lru_refcnt;
std::atomic<uint32_t> lru_adj;
bi::list_member_hook< link_mode > lru_hook;
typedef bi::list<Object,
bi::member_hook<
Object, bi::list_member_hook< link_mode >,
&Object::lru_hook >,
bi::constant_time_size<true>> Queue;
bi::slist_member_hook< link_mode > q2_hook;
typedef bi::slist<Object,
bi::member_hook<
Object, bi::slist_member_hook< link_mode >,
&Object::q2_hook >,
bi::constant_time_size<true>> Queue2;
public:
Object() : lru_flags(FLAG_NONE), lru_refcnt(0), lru_adj(0) {}
uint32_t get_refcnt() const { return lru_refcnt; }
virtual bool reclaim(const ObjectFactory* newobj_fac) = 0;
virtual ~Object() {}
private:
template <typename LK>
friend class LRU;
template <typename T, typename TTree, typename CLT, typename CEQ,
typename K, typename LK>
friend class TreeX;
};
/* allocator & recycler interface (create or re-use LRU objects) */
class ObjectFactory
{
public:
virtual Object* alloc(void) = 0;
virtual void recycle(Object*) = 0;
virtual ~ObjectFactory() {};
};
template <typename LK>
class LRU
{
private:
struct Lane {
LK lock;
Object::Queue q;
// Object::Queue pinned; /* placeholder for possible expansion */
CACHE_PAD(0);
Lane() {}
};
Lane *qlane;
int n_lanes;
std::atomic<uint32_t> evict_lane;
const uint32_t lane_hiwat;
static constexpr uint32_t lru_adj_modulus = 5;
static constexpr uint32_t SENTINEL_REFCNT = 1;
/* internal flag values */
static constexpr uint32_t FLAG_INLRU = 0x0001;
static constexpr uint32_t FLAG_PINNED = 0x0002; // possible future use
static constexpr uint32_t FLAG_EVICTING = 0x0004;
Lane& lane_of(void* addr) {
return qlane[(uint64_t)(addr) % n_lanes];
}
uint32_t next_evict_lane() {
return (evict_lane++ % n_lanes);
}
bool can_reclaim(Object* o) {
return ((o->lru_refcnt == SENTINEL_REFCNT) &&
(!(o->lru_flags & FLAG_EVICTING)));
}
Object* evict_block(const ObjectFactory* newobj_fac) {
uint32_t lane_ix = next_evict_lane();
for (int ix = 0; ix < n_lanes; ++ix,
lane_ix = next_evict_lane()) {
Lane& lane = qlane[lane_ix];
std::unique_lock lane_lock{lane.lock};
/* if object at LRU has refcnt==1, it may be reclaimable */
Object* o = &(lane.q.back());
if (can_reclaim(o)) {
++(o->lru_refcnt);
o->lru_flags |= FLAG_EVICTING;
lane_lock.unlock();
if (o->reclaim(newobj_fac)) {
lane_lock.lock();
--(o->lru_refcnt);
/* assertions that o state has not changed across
* relock */
ceph_assert(o->lru_refcnt == SENTINEL_REFCNT);
ceph_assert(o->lru_flags & FLAG_INLRU);
Object::Queue::iterator it =
Object::Queue::s_iterator_to(*o);
lane.q.erase(it);
return o;
} else {
--(o->lru_refcnt);
o->lru_flags &= ~FLAG_EVICTING;
/* unlock in next block */
}
} /* can_reclaim(o) */
} /* each lane */
return nullptr;
} /* evict_block */
public:
LRU(int lanes, uint32_t _hiwat)
: n_lanes(lanes), evict_lane(0), lane_hiwat(_hiwat)
{
ceph_assert(n_lanes > 0);
qlane = new Lane[n_lanes];
}
~LRU() { delete[] qlane; }
bool ref(Object* o, uint32_t flags) {
++(o->lru_refcnt);
if (flags & FLAG_INITIAL) {
if ((++(o->lru_adj) % lru_adj_modulus) == 0) {
Lane& lane = lane_of(o);
lane.lock.lock();
/* move to MRU */
Object::Queue::iterator it =
Object::Queue::s_iterator_to(*o);
lane.q.erase(it);
lane.q.push_front(*o);
lane.lock.unlock();
} /* adj */
} /* initial ref */
return true;
} /* ref */
void unref(Object* o, uint32_t flags) {
uint32_t refcnt = --(o->lru_refcnt);
Object* tdo = nullptr;
if (unlikely(refcnt == 0)) {
Lane& lane = lane_of(o);
lane.lock.lock();
refcnt = o->lru_refcnt.load();
if (unlikely(refcnt == 0)) {
Object::Queue::iterator it =
Object::Queue::s_iterator_to(*o);
lane.q.erase(it);
tdo = o;
}
lane.lock.unlock();
} else if (unlikely(refcnt == SENTINEL_REFCNT)) {
Lane& lane = lane_of(o);
lane.lock.lock();
refcnt = o->lru_refcnt.load();
if (likely(refcnt == SENTINEL_REFCNT)) {
/* move to LRU */
Object::Queue::iterator it =
Object::Queue::s_iterator_to(*o);
lane.q.erase(it);
/* hiwat check */
if (lane.q.size() > lane_hiwat) {
tdo = o;
} else {
lane.q.push_back(*o);
}
}
lane.lock.unlock();
}
/* unref out-of-line && !LOCKED */
if (tdo)
delete tdo;
} /* unref */
Object* insert(ObjectFactory* fac, Edge edge, uint32_t& flags) {
/* use supplied functor to re-use an evicted object, or
* allocate a new one of the descendant type */
Object* o = evict_block(fac);
if (o) {
fac->recycle(o); /* recycle existing object */
flags |= FLAG_RECYCLE;
}
else
o = fac->alloc(); /* get a new one */
o->lru_flags = FLAG_INLRU;
Lane& lane = lane_of(o);
lane.lock.lock();
switch (edge) {
case Edge::MRU:
lane.q.push_front(*o);
break;
case Edge::LRU:
lane.q.push_back(*o);
break;
default:
ceph_abort();
break;
}
if (flags & FLAG_INITIAL)
o->lru_refcnt += 2; /* sentinel ref + initial */
else
++(o->lru_refcnt); /* sentinel */
lane.lock.unlock();
return o;
} /* insert */
};
template <typename T, typename TTree, typename CLT, typename CEQ,
typename K, typename LK>
class TreeX
{
public:
static constexpr uint32_t FLAG_NONE = 0x0000;
static constexpr uint32_t FLAG_LOCK = 0x0001;
static constexpr uint32_t FLAG_UNLOCK = 0x0002;
static constexpr uint32_t FLAG_UNLOCK_ON_MISS = 0x0004;
typedef T value_type;
typedef TTree container_type;
typedef typename TTree::iterator iterator;
typedef std::pair<iterator, bool> check_result;
typedef typename TTree::insert_commit_data insert_commit_data;
int n_part;
int csz;
typedef std::unique_lock<LK> unique_lock;
struct Partition {
LK lock;
TTree tr;
T** cache;
int csz;
CACHE_PAD(0);
Partition() : tr(), cache(nullptr), csz(0) {}
~Partition() {
if (csz)
::operator delete(cache);
}
};
struct Latch {
Partition* p;
LK* lock;
insert_commit_data commit_data{};
Latch() : p(nullptr), lock(nullptr) {}
};
Partition& partition_of_scalar(uint64_t x) {
return part[x % n_part];
}
Partition& get(uint8_t x) {
return part[x];
}
Partition*& get() {
return part;
}
void lock() {
std::for_each(locks.begin(), locks.end(),
[](LK* lk){ lk->lock(); });
}
void unlock() {
std::for_each(locks.begin(), locks.end(),
[](LK* lk){ lk->unlock(); });
}
TreeX(int n_part=1, int csz=127) : n_part(n_part), csz(csz) {
ceph_assert(n_part > 0);
part = new Partition[n_part];
for (int ix = 0; ix < n_part; ++ix) {
Partition& p = part[ix];
if (csz) {
p.csz = csz;
p.cache = (T**) ::operator new(csz * sizeof(T*));
// FIPS zeroization audit 20191115: this memset is not security related.
memset(p.cache, 0, csz * sizeof(T*));
}
locks.push_back(&p.lock);
}
}
~TreeX() {
delete[] part;
}
T* find(uint64_t hk, const K& k, uint32_t flags) {
T* v;
Latch lat;
uint32_t slot = 0;
lat.p = &(partition_of_scalar(hk));
if (flags & FLAG_LOCK) {
lat.lock = &lat.p->lock;
lat.lock->lock();
}
if (csz) { /* template specialize? */
slot = hk % csz;
v = lat.p->cache[slot];
if (v) {
if (CEQ()(*v, k)) {
if (flags & FLAG_LOCK)
lat.lock->unlock();
return v;
}
v = nullptr;
}
} else {
v = nullptr;
}
iterator it = lat.p->tr.find(k, CLT());
if (it != lat.p->tr.end()){
v = &(*(it));
if (csz) {
/* fill cache slot at hk */
lat.p->cache[slot] = v;
}
}
if (flags & FLAG_LOCK)
lat.lock->unlock();
return v;
} /* find */
T* find_latch(uint64_t hk, const K& k, Latch& lat,
uint32_t flags) {
uint32_t slot = 0;
T* v;
lat.p = &(partition_of_scalar(hk));
lat.lock = &lat.p->lock;
if (flags & FLAG_LOCK)
lat.lock->lock();
if (csz) { /* template specialize? */
slot = hk % csz;
v = lat.p->cache[slot];
if (v) {
if (CEQ()(*v, k)) {
if ((flags & FLAG_LOCK) && (flags & FLAG_UNLOCK))
lat.lock->unlock();
return v;
}
v = nullptr;
}
} else {
v = nullptr;
}
check_result r = lat.p->tr.insert_unique_check(
k, CLT(), lat.commit_data);
if (! r.second /* !insertable (i.e., !found) */) {
v = &(*(r.first));
if (csz) {
/* fill cache slot at hk */
lat.p->cache[slot] = v;
}
}
if ((flags & FLAG_LOCK) && (flags & FLAG_UNLOCK))
lat.lock->unlock();
return v;
} /* find_latch */
bool is_same_partition(uint64_t lhs, uint64_t rhs) {
return ((lhs % n_part) == (rhs % n_part));
}
void insert_latched(T* v, Latch& lat, uint32_t flags) {
(void) lat.p->tr.insert_unique_commit(*v, lat.commit_data);
if (flags & FLAG_UNLOCK)
lat.lock->unlock();
} /* insert_latched */
void insert(uint64_t hk, T* v, uint32_t flags) {
Partition& p = partition_of_scalar(hk);
if (flags & FLAG_LOCK)
p.lock.lock();
p.tr.insert_unique(*v);
if (flags & FLAG_LOCK)
p.lock.unlock();
} /* insert */
void remove(uint64_t hk, T* v, uint32_t flags) {
Partition& p = partition_of_scalar(hk);
iterator it = TTree::s_iterator_to(*v);
if (flags & FLAG_LOCK)
p.lock.lock();
p.tr.erase(it);
if (csz) { /* template specialize? */
uint32_t slot = hk % csz;
T* v2 = p.cache[slot];
/* we are intrusive, just compare addresses */
if (v == v2)
p.cache[slot] = nullptr;
}
if (flags & FLAG_LOCK)
p.lock.unlock();
} /* remove */
void drain(std::function<void(T*)> uref,
uint32_t flags = FLAG_NONE) {
/* clear a table, call supplied function on
* each element found (e.g., returns sentinel
* references) */
Object::Queue2 drain_q;
for (int t_ix = 0; t_ix < n_part; ++t_ix) {
Partition& p = part[t_ix];
if (flags & FLAG_LOCK) /* LOCKED */
p.lock.lock();
while (p.tr.size() > 0) {
iterator it = p.tr.begin();
T* v = &(*it);
p.tr.erase(it);
drain_q.push_front(*v);
}
if (flags & FLAG_LOCK) /* we locked it, !LOCKED */
p.lock.unlock();
} /* each partition */
/* unref out-of-line && !LOCKED */
while (drain_q.size() > 0) {
Object::Queue2::iterator it = drain_q.begin();
T* v = static_cast<T*>(&(*it));
drain_q.erase(it); /* must precede uref(v) in safe_link mode */
uref(v);
}
} /* drain */
private:
Partition *part;
std::vector<LK*> locks;
};
} /* namespace LRU */
} /* namespace cohort */
#endif /* COHORT_LRU_H */
| 12,135 | 23.320641 | 77 | h |
null | ceph-main/src/common/common_init.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) 2010-2011 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/compat.h"
#include "common/common_init.h"
#include "common/admin_socket.h"
#include "common/ceph_argparse.h"
#include "common/ceph_context.h"
#include "common/config.h"
#include "common/dout.h"
#include "common/hostname.h"
#include "common/strtol.h"
#include "common/valgrind.h"
#include "common/zipkin_trace.h"
#define dout_subsys ceph_subsys_
#ifndef WITH_SEASTAR
CephContext *common_preinit(const CephInitParameters &iparams,
enum code_environment_t code_env, int flags)
{
// set code environment
ANNOTATE_BENIGN_RACE_SIZED(&g_code_env, sizeof(g_code_env), "g_code_env");
g_code_env = code_env;
// Create a configuration object
CephContext *cct = new CephContext(iparams.module_type, code_env, flags);
auto& conf = cct->_conf;
// add config observers here
// Set up our entity name.
conf->name = iparams.name;
// different default keyring locations for osd and mds. this is
// for backward compatibility. moving forward, we want all keyrings
// in these locations. the mon already forces $mon_data/keyring.
if (conf->name.is_mds()) {
conf.set_val_default("keyring", "$mds_data/keyring");
} else if (conf->name.is_osd()) {
conf.set_val_default("keyring", "$osd_data/keyring");
}
if ((flags & CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS)) {
// make this unique despite multiple instances by the same name.
conf.set_val_default("admin_socket",
"$run_dir/$cluster-$name.$pid.$cctid.asok");
}
if (code_env == CODE_ENVIRONMENT_LIBRARY ||
code_env == CODE_ENVIRONMENT_UTILITY_NODOUT) {
conf.set_val_default("log_to_stderr", "false");
conf.set_val_default("err_to_stderr", "false");
conf.set_val_default("log_flush_on_exit", "false");
}
conf.set_val("no_config_file", iparams.no_config_file ? "true" : "false");
if (conf->host.empty()) {
conf.set_val("host", ceph_get_short_hostname());
}
return cct;
}
#endif // #ifndef WITH_SEASTAR
void complain_about_parse_error(CephContext *cct,
const std::string& parse_error)
{
if (parse_error.empty())
return;
lderr(cct) << "Errors while parsing config file!" << dendl;
lderr(cct) << parse_error << dendl;
}
#ifndef WITH_SEASTAR
/* Please be sure that this can safely be called multiple times by the
* same application. */
void common_init_finish(CephContext *cct)
{
// only do this once per cct
if (cct->_finished) {
return;
}
cct->_finished = true;
cct->init_crypto();
ZTracer::ztrace_init();
if (!cct->_log->is_started()) {
cct->_log->start();
}
int flags = cct->get_init_flags();
if (!(flags & CINIT_FLAG_NO_DAEMON_ACTIONS))
cct->start_service_thread();
if ((flags & CINIT_FLAG_DEFER_DROP_PRIVILEGES) &&
(cct->get_set_uid() || cct->get_set_gid())) {
cct->get_admin_socket()->chown(cct->get_set_uid(), cct->get_set_gid());
}
const auto& conf = cct->_conf;
if (!conf->admin_socket.empty() && !conf->admin_socket_mode.empty()) {
int ret = 0;
std::string err;
ret = strict_strtol(conf->admin_socket_mode.c_str(), 8, &err);
if (err.empty()) {
if (!(ret & (~ACCESSPERMS))) {
cct->get_admin_socket()->chmod(static_cast<mode_t>(ret));
} else {
lderr(cct) << "Invalid octal permissions string: "
<< conf->admin_socket_mode << dendl;
}
} else {
lderr(cct) << "Invalid octal string: " << err << dendl;
}
}
}
#endif // #ifndef WITH_SEASTAR
| 3,850 | 27.738806 | 76 | cc |
null | ceph-main/src/common/common_init.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-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_INIT_H
#define CEPH_COMMON_INIT_H
#include <deque>
#include "include/common_fwd.h"
#include "common/code_environment.h"
enum common_init_flags_t {
// Set up defaults that make sense for an unprivileged daemon
CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS = 0x1,
// By default, don't read a configuration file OR contact mons
CINIT_FLAG_NO_DEFAULT_CONFIG_FILE = 0x2,
// Don't close stderr (in daemonize)
CINIT_FLAG_NO_CLOSE_STDERR = 0x4,
// don't do anything daemonish, like create /var/run/ceph, or print a banner
CINIT_FLAG_NO_DAEMON_ACTIONS = 0x8,
// don't drop privileges
CINIT_FLAG_DEFER_DROP_PRIVILEGES = 0x10,
// don't contact mons for config
CINIT_FLAG_NO_MON_CONFIG = 0x20,
// don't expose default cct perf counters
CINIT_FLAG_NO_CCT_PERF_COUNTERS = 0x40,
};
#ifndef WITH_SEASTAR
class CephInitParameters;
/*
* NOTE: If you are writing a Ceph daemon, ignore this function and call
* global_init instead. It will call common_preinit for you.
*
* common_preinit creates the CephContext.
*
* After this function gives you a CephContext, you need to set up the
* Ceph configuration, which lives inside the CephContext as md_config_t.
* The initial settings are not very useful because they do not reflect what
* the user asked for.
*
* This is usually done by something like this:
* cct->_conf.parse_env();
* cct->_conf.apply_changes();
*
* Your library may also supply functions to read a configuration file.
*/
CephContext *common_preinit(const CephInitParameters &iparams,
enum code_environment_t code_env, int flags);
#endif // #ifndef WITH_SEASTAR
/* Print out some parse error. */
void complain_about_parse_error(CephContext *cct,
const std::string& parse_error);
/* This function is called after you have done your last
* fork. When you make this call, the system will initialize everything that
* cannot be initialized before a fork.
*
* This includes things like starting threads, initializing libraries that
* can't handle forking, and so forth.
*
* If you are writing a Ceph library, you can call this pretty much any time.
* We do not allow our library users to fork and continue using the Ceph
* libraries. The most obvious reason for this is that the threads started by
* the Ceph libraries would be destroyed by a fork().
*/
void common_init_finish(CephContext *cct);
#endif
| 2,802 | 30.494382 | 78 | h |
null | ceph-main/src/common/compat.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) 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.
*
*/
#include <cstdio>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include "acconfig.h"
#ifdef HAVE_MEMSET_S
# define __STDC_WANT_LIB_EXT1__ 1
#endif
#include <string.h>
#include <thread>
#ifndef _WIN32
#include <sys/mount.h>
#else
#include <stdlib.h>
#endif
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/vfs.h>
#endif
#include "include/compat.h"
#include "include/sock_compat.h"
#include "common/safe_io.h"
// The type-value for a ZFS FS in fstatfs.
#define FS_ZFS_TYPE 0xde
// On FreeBSD, ZFS fallocate always fails since it is considered impossible to
// reserve space on a COW filesystem. posix_fallocate() returns EINVAL
// Linux in this case already emulates the reservation in glibc
// In which case it is allocated manually, and still that is not a real guarantee
// that a full buffer is allocated on disk, since it could be compressed.
// To prevent this the written buffer needs to be loaded with random data.
int manual_fallocate(int fd, off_t offset, off_t len) {
int r = lseek(fd, offset, SEEK_SET);
if (r == -1)
return errno;
char data[1024*128];
// TODO: compressing filesystems would require random data
// FIPS zeroization audit 20191115: this memset is not security related.
memset(data, 0x42, sizeof(data));
for (off_t off = 0; off < len; off += sizeof(data)) {
if (off + static_cast<off_t>(sizeof(data)) > len)
r = safe_write(fd, data, len - off);
else
r = safe_write(fd, data, sizeof(data));
if (r == -1) {
return errno;
}
}
return 0;
}
int on_zfs(int basedir_fd) {
#ifndef _WIN32
struct statfs basefs;
(void)fstatfs(basedir_fd, &basefs);
return (basefs.f_type == FS_ZFS_TYPE);
#else
return 0;
#endif
}
int ceph_posix_fallocate(int fd, off_t offset, off_t len) {
// Return 0 if oke, otherwise errno > 0
#ifdef HAVE_POSIX_FALLOCATE
if (on_zfs(fd)) {
return manual_fallocate(fd, offset, len);
} else {
return posix_fallocate(fd, offset, len);
}
#elif defined(__APPLE__)
fstore_t store;
store.fst_flags = F_ALLOCATECONTIG;
store.fst_posmode = F_PEOFPOSMODE;
store.fst_offset = offset;
store.fst_length = len;
int ret = fcntl(fd, F_PREALLOCATE, &store);
if (ret == -1) {
ret = errno;
}
return ret;
#else
return manual_fallocate(fd, offset, len);
#endif
}
int pipe_cloexec(int pipefd[2], int flags)
{
#if defined(HAVE_PIPE2)
return pipe2(pipefd, O_CLOEXEC | flags);
#else
if (pipe(pipefd) == -1)
return -1;
#ifndef _WIN32
/*
* The old-fashioned, race-condition prone way that we have to fall
* back on if pipe2 does not exist.
*/
if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) < 0) {
goto fail;
}
if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) < 0) {
goto fail;
}
#endif
return 0;
fail:
int save_errno = errno;
VOID_TEMP_FAILURE_RETRY(close(pipefd[0]));
VOID_TEMP_FAILURE_RETRY(close(pipefd[1]));
return (errno = save_errno, -1);
#endif
}
int socket_cloexec(int domain, int type, int protocol)
{
#ifdef SOCK_CLOEXEC
return socket(domain, type|SOCK_CLOEXEC, protocol);
#else
int fd = socket(domain, type, protocol);
if (fd == -1)
return -1;
#ifndef _WIN32
if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
goto fail;
#endif
return fd;
fail:
int save_errno = errno;
VOID_TEMP_FAILURE_RETRY(close(fd));
return (errno = save_errno, -1);
#endif
}
int socketpair_cloexec(int domain, int type, int protocol, int sv[2])
{
#ifdef SOCK_CLOEXEC
return socketpair(domain, type|SOCK_CLOEXEC, protocol, sv);
#elif _WIN32
/* TODO */
return -ENOTSUP;
#else
int rc = socketpair(domain, type, protocol, sv);
if (rc == -1)
return -1;
#ifndef _WIN32
if (fcntl(sv[0], F_SETFD, FD_CLOEXEC) < 0)
goto fail;
if (fcntl(sv[1], F_SETFD, FD_CLOEXEC) < 0)
goto fail;
#endif
return 0;
fail:
int save_errno = errno;
VOID_TEMP_FAILURE_RETRY(close(sv[0]));
VOID_TEMP_FAILURE_RETRY(close(sv[1]));
return (errno = save_errno, -1);
#endif
}
int accept_cloexec(int sockfd, struct sockaddr* addr, socklen_t* addrlen)
{
#ifdef HAVE_ACCEPT4
return accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
#else
int fd = accept(sockfd, addr, addrlen);
if (fd == -1)
return -1;
#ifndef _WIN32
if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
goto fail;
#endif
return fd;
fail:
int save_errno = errno;
VOID_TEMP_FAILURE_RETRY(close(fd));
return (errno = save_errno, -1);
#endif
}
#if defined(__FreeBSD__)
int sched_setaffinity(pid_t pid, size_t cpusetsize,
cpu_set_t *mask)
{
return 0;
}
#endif
char *ceph_strerror_r(int errnum, char *buf, size_t buflen)
{
#ifdef _WIN32
strerror_s(buf, buflen, errnum);
return buf;
#elif defined(STRERROR_R_CHAR_P)
return strerror_r(errnum, buf, buflen);
#else
if (strerror_r(errnum, buf, buflen)) {
snprintf(buf, buflen, "Unknown error %d", errnum);
}
return buf;
#endif
}
int ceph_memzero_s(void *dest, size_t destsz, size_t count) {
#ifdef HAVE_MEMSET_S
return memset_s(dest, destsz, 0, count);
#elif defined(_WIN32)
SecureZeroMemory(dest, count);
#else
explicit_bzero(dest, count);
#endif
return 0;
}
#ifdef _WIN32
#include <iomanip>
#include <ctime>
// chown is not available on Windows. Plus, changing file owners is not
// a common practice on Windows.
int chown(const char *path, uid_t owner, gid_t group) {
return 0;
}
int fchown(int fd, uid_t owner, gid_t group) {
return 0;
}
int lchown(const char *path, uid_t owner, gid_t group) {
return 0;
}
int posix_memalign(void **memptr, size_t alignment, size_t size) {
*memptr = _aligned_malloc(size, alignment);
return *memptr ? 0 : errno;
}
char *strptime(const char *s, const char *format, struct tm *tm) {
std::istringstream input(s);
input.imbue(std::locale(setlocale(LC_ALL, nullptr)));
input >> std::get_time(tm, format);
if (input.fail()) {
return nullptr;
}
return (char*)(s + input.tellg());
}
int pipe(int pipefd[2]) {
// We'll use the same pipe size as Linux (64kb).
return _pipe(pipefd, 0x10000, O_NOINHERIT);
}
// lrand48 is not available on Windows. We'll generate a pseudo-random
// value in the 0 - 2^31 range by calling rand twice.
long int lrand48(void) {
long int val;
val = (long int) rand();
val <<= 16;
val += (long int) rand();
return val;
}
int random() {
return rand();
}
int fsync(int fd) {
HANDLE handle = (HANDLE*)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return -1;
if (!FlushFileBuffers(handle))
return -1;
return 0;
}
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset) {
DWORD bytes_written = 0;
HANDLE handle = (HANDLE*)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return -1;
OVERLAPPED overlapped = { 0 };
ULARGE_INTEGER offsetUnion;
offsetUnion.QuadPart = offset;
overlapped.Offset = offsetUnion.LowPart;
overlapped.OffsetHigh = offsetUnion.HighPart;
if (!WriteFile(handle, buf, count, &bytes_written, &overlapped))
// we may consider mapping error codes, although that may
// not be exhaustive.
return -1;
return bytes_written;
}
ssize_t pread(int fd, void *buf, size_t count, off_t offset) {
DWORD bytes_read = 0;
HANDLE handle = (HANDLE*)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return -1;
OVERLAPPED overlapped = { 0 };
ULARGE_INTEGER offsetUnion;
offsetUnion.QuadPart = offset;
overlapped.Offset = offsetUnion.LowPart;
overlapped.OffsetHigh = offsetUnion.HighPart;
if (!ReadFile(handle, buf, count, &bytes_read, &overlapped)) {
if (GetLastError() != ERROR_HANDLE_EOF)
return -1;
}
return bytes_read;
}
ssize_t preadv(int fd, const struct iovec *iov, int iov_cnt) {
ssize_t read = 0;
for (int i = 0; i < iov_cnt; i++) {
int r = ::read(fd, iov[i].iov_base, iov[i].iov_len);
if (r < 0)
return r;
read += r;
if (r < iov[i].iov_len)
break;
}
return read;
}
ssize_t writev(int fd, const struct iovec *iov, int iov_cnt) {
ssize_t written = 0;
for (int i = 0; i < iov_cnt; i++) {
int r = ::write(fd, iov[i].iov_base, iov[i].iov_len);
if (r < 0)
return r;
written += r;
if (r < iov[i].iov_len)
break;
}
return written;
}
int &alloc_tls() {
static __thread int tlsvar;
tlsvar++;
return tlsvar;
}
void apply_tls_workaround() {
// Workaround for the following Mingw bugs:
// https://sourceforge.net/p/mingw-w64/bugs/727/
// https://sourceforge.net/p/mingw-w64/bugs/527/
// https://sourceforge.net/p/mingw-w64/bugs/445/
// https://gcc.gnu.org/bugzilla/attachment.cgi?id=41382
pthread_key_t key;
pthread_key_create(&key, nullptr);
// Use a TLS slot for emutls
alloc_tls();
// Free up a slot that can now be used for c++ destructors
pthread_key_delete(key);
}
CEPH_CONSTRUCTOR(ceph_windows_init) {
// This will run at startup time before invoking main().
WSADATA wsaData;
int error;
#ifdef __MINGW32__
apply_tls_workaround();
#endif
error = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (error != 0) {
fprintf(stderr, "WSAStartup failed: %d", WSAGetLastError());
exit(error);
}
}
int _win_socketpair(int socks[2])
{
union {
struct sockaddr_in inaddr;
struct sockaddr addr;
} a;
SOCKET listener;
int e;
socklen_t addrlen = sizeof(a.inaddr);
int reuse = 1;
if (socks == 0) {
WSASetLastError(WSAEINVAL);
return -1;
}
listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listener == INVALID_SOCKET) {
return -1;
}
memset(&a, 0, sizeof(a));
a.inaddr.sin_family = AF_INET;
a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.inaddr.sin_port = 0;
socks[0] = socks[1] = -1;
SOCKET s[2] = { INVALID_SOCKET, INVALID_SOCKET };
do {
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,
(char*) &reuse, (socklen_t) sizeof(reuse)) == -1)
break;
if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
break;
if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR)
break;
if (listen(listener, 1) == SOCKET_ERROR)
break;
s[0] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s[0] == INVALID_SOCKET)
break;
if (connect(s[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
break;
s[1] = accept(listener, NULL, NULL);
if (s[1] == INVALID_SOCKET)
break;
closesocket(listener);
// The Windows socket API is mostly compatible with the Berkeley
// API, with a few exceptions. The Windows socket functions use
// SOCKET instead of int. The issue is that on x64 systems,
// SOCKET uses 64b while int uses 32b. There's been much debate
// whether casting a Windows socket to an int is safe or not.
// Worth noting that Windows kernel objects use 32b. For now,
// we're just adding a check.
//
// Ideally, we should update ceph to use the right type but this
// can be quite difficult, especially considering that there are
// a significant number of functions that accept both sockets and
// file descriptors.
if (s[0] >> 32 || s[1] >> 32) {
WSASetLastError(WSAENAMETOOLONG);
break;
}
socks[0] = s[0];
socks[1] = s[1];
return 0;
} while (0);
e = WSAGetLastError();
closesocket(listener);
closesocket(s[0]);
closesocket(s[1]);
WSASetLastError(e);
return -1;
}
int win_socketpair(int socks[2]) {
int r = 0;
for (int i = 0; i < 15; i++) {
r = _win_socketpair(socks);
if (r && WSAGetLastError() == WSAEADDRINUSE) {
sleep(2);
continue;
}
else {
break;
}
}
return r;
}
unsigned get_page_size() {
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
return system_info.dwPageSize;
}
int setenv(const char *name, const char *value, int overwrite) {
if (!overwrite && getenv(name)) {
return 0;
}
return _putenv_s(name, value);
}
ssize_t get_self_exe_path(char* path, int buff_length) {
return GetModuleFileName(NULL, path, buff_length - 1);
}
int geteuid()
{
return 0;
}
int getegid()
{
return 0;
}
int getuid()
{
return 0;
}
int getgid()
{
return 0;
}
#else
unsigned get_page_size() {
return sysconf(_SC_PAGESIZE);
}
ssize_t get_self_exe_path(char* path, int buff_length) {
return readlink("/proc/self/exe", path,
sizeof(buff_length) - 1);
}
#endif /* _WIN32 */
| 12,911 | 21.732394 | 81 | cc |
null | ceph-main/src/common/compiler_extensions.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_COMPILER_EXTENSIONS_H
#define CEPH_COMPILER_EXTENSIONS_H
/* We should be able to take advantage of nice nonstandard features of gcc
* and other compilers, but still maintain portability.
*/
#ifdef __GNUC__
// GCC
#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
// some other compiler - just make it a no-op
#define WARN_UNUSED_RESULT
#endif
#endif
| 796 | 24.709677 | 74 | h |
null | ceph-main/src/common/condition_variable_debug.cc | #include "condition_variable_debug.h"
#include "common/mutex_debug.h"
namespace ceph {
condition_variable_debug::condition_variable_debug()
: waiter_mutex{nullptr}
{
int r = pthread_cond_init(&cond, nullptr);
if (r) {
throw std::system_error(r, std::generic_category());
}
}
condition_variable_debug::~condition_variable_debug()
{
pthread_cond_destroy(&cond);
}
void condition_variable_debug::wait(std::unique_lock<mutex_debug>& lock)
{
// make sure this cond is used with one mutex only
ceph_assert(waiter_mutex == nullptr ||
waiter_mutex == lock.mutex());
waiter_mutex = lock.mutex();
ceph_assert(waiter_mutex->is_locked());
waiter_mutex->_pre_unlock();
if (int r = pthread_cond_wait(&cond, waiter_mutex->native_handle());
r != 0) {
throw std::system_error(r, std::generic_category());
}
waiter_mutex->_post_lock();
}
void condition_variable_debug::notify_one()
{
// make sure signaler is holding the waiter's lock.
ceph_assert(waiter_mutex == nullptr ||
waiter_mutex->is_locked());
if (int r = pthread_cond_signal(&cond); r != 0) {
throw std::system_error(r, std::generic_category());
}
}
void condition_variable_debug::notify_all(bool sloppy)
{
if (!sloppy) {
// make sure signaler is holding the waiter's lock.
ceph_assert(waiter_mutex == NULL ||
waiter_mutex->is_locked());
}
if (int r = pthread_cond_broadcast(&cond); r != 0 && !sloppy) {
throw std::system_error(r, std::generic_category());
}
}
std::cv_status condition_variable_debug::_wait_until(mutex_debug* mutex,
timespec* ts)
{
// make sure this cond is used with one mutex only
ceph_assert(waiter_mutex == nullptr ||
waiter_mutex == mutex);
waiter_mutex = mutex;
ceph_assert(waiter_mutex->is_locked());
waiter_mutex->_pre_unlock();
int r = pthread_cond_timedwait(&cond, waiter_mutex->native_handle(), ts);
waiter_mutex->_post_lock();
switch (r) {
case 0:
return std::cv_status::no_timeout;
case ETIMEDOUT:
return std::cv_status::timeout;
default:
throw std::system_error(r, std::generic_category());
}
}
} // namespace ceph
| 2,202 | 26.5375 | 75 | cc |
null | ceph-main/src/common/condition_variable_debug.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <condition_variable>
#include <ctime>
#include <pthread.h>
#include "common/ceph_time.h"
namespace ceph {
namespace mutex_debug_detail {
template<bool> class mutex_debug_impl;
}
class condition_variable_debug {
using mutex_debug = mutex_debug_detail::mutex_debug_impl<false>;
pthread_cond_t cond;
mutex_debug* waiter_mutex;
condition_variable_debug&
operator=(const condition_variable_debug&) = delete;
condition_variable_debug(const condition_variable_debug&) = delete;
public:
condition_variable_debug();
~condition_variable_debug();
void wait(std::unique_lock<mutex_debug>& lock);
template<class Predicate>
void wait(std::unique_lock<mutex_debug>& lock, Predicate pred) {
while (!pred()) {
wait(lock);
}
}
template<class Clock, class Duration>
std::cv_status wait_until(
std::unique_lock<mutex_debug>& lock,
const std::chrono::time_point<Clock, Duration>& when) {
if constexpr (Clock::is_steady) {
// convert from mono_clock to real_clock
auto real_when = ceph::real_clock::now();
const auto delta = when - Clock::now();
real_when += std::chrono::ceil<typename Clock::duration>(delta);
timespec ts = ceph::real_clock::to_timespec(real_when);
return _wait_until(lock.mutex(), &ts);
} else {
timespec ts = Clock::to_timespec(when);
return _wait_until(lock.mutex(), &ts);
}
}
template<class Rep, class Period>
std::cv_status wait_for(
std::unique_lock<mutex_debug>& lock,
const std::chrono::duration<Rep, Period>& awhile) {
ceph::real_time when{ceph::real_clock::now()};
when += awhile;
timespec ts = ceph::real_clock::to_timespec(when);
return _wait_until(lock.mutex(), &ts);
}
template<class Rep, class Period, class Pred>
bool wait_for(
std::unique_lock<mutex_debug>& lock,
const std::chrono::duration<Rep, Period>& awhile,
Pred pred) {
ceph::real_time when{ceph::real_clock::now()};
when += awhile;
timespec ts = ceph::real_clock::to_timespec(when);
while (!pred()) {
if ( _wait_until(lock.mutex(), &ts) == std::cv_status::timeout) {
return pred();
}
}
return true;
}
void notify_one();
void notify_all(bool sloppy = false);
private:
std::cv_status _wait_until(mutex_debug* mutex, timespec* ts);
};
} // namespace ceph
| 2,464 | 28.345238 | 71 | h |
null | ceph-main/src/common/fd.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2012 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.
*
*/
#ifndef CEPH_COMMON_FD_H
#define CEPH_COMMON_FD_H
#include "include/common_fwd.h"
void dump_open_fds(CephContext *cct);
#endif
| 534 | 22.26087 | 70 | h |
null | ceph-main/src/common/config.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 <filesystem>
#include "common/ceph_argparse.h"
#include "common/common_init.h"
#include "common/config.h"
#include "common/config_obs.h"
#include "include/str_list.h"
#include "include/stringify.h"
#include "osd/osd_types.h"
#include "common/errno.h"
#include "common/hostname.h"
#include "common/dout.h"
/* Don't use standard Ceph logging in this file.
* We can't use logging until it's initialized, and a lot of the necessary
* initialization happens here.
*/
#undef dout
#undef pdout
#undef derr
#undef generic_dout
// set set_mon_vals()
#define dout_subsys ceph_subsys_monc
namespace fs = std::filesystem;
using std::cerr;
using std::cout;
using std::map;
using std::less;
using std::list;
using std::ostream;
using std::ostringstream;
using std::pair;
using std::string;
using std::string_view;
using std::vector;
using ceph::bufferlist;
using ceph::decode;
using ceph::encode;
using ceph::Formatter;
static const char *CEPH_CONF_FILE_DEFAULT = "$data_dir/config,/etc/ceph/$cluster.conf,$home/.ceph/$cluster.conf,$cluster.conf"
#if defined(__FreeBSD__)
",/usr/local/etc/ceph/$cluster.conf"
#elif defined(_WIN32)
",$programdata/ceph/$cluster.conf"
#endif
;
#define _STR(x) #x
#define STRINGIFY(x) _STR(x)
const char *ceph_conf_level_name(int level)
{
switch (level) {
case CONF_DEFAULT: return "default"; // built-in default
case CONF_MON: return "mon"; // monitor config database
case CONF_ENV: return "env"; // process environment (CEPH_ARGS)
case CONF_FILE: return "file"; // ceph.conf file
case CONF_CMDLINE: return "cmdline"; // process command line args
case CONF_OVERRIDE: return "override"; // injectargs or 'config set' at runtime
case CONF_FINAL: return "final";
default: return "???";
}
}
int ceph_resolve_file_search(const std::string& filename_list,
std::string& result)
{
list<string> ls;
get_str_list(filename_list, ";,", ls);
int ret = -ENOENT;
list<string>::iterator iter;
for (iter = ls.begin(); iter != ls.end(); ++iter) {
int fd = ::open(iter->c_str(), O_RDONLY|O_CLOEXEC);
if (fd < 0) {
ret = -errno;
continue;
}
close(fd);
result = *iter;
return 0;
}
return ret;
}
static int conf_stringify(const Option::value_t& v, string *out)
{
if (v == Option::value_t{}) {
return -ENOENT;
}
*out = Option::to_str(v);
return 0;
}
md_config_t::md_config_t(ConfigValues& values,
const ConfigTracker& tracker,
bool is_daemon)
: is_daemon(is_daemon)
{
// Load the compile-time list of Option into
// a map so that we can resolve keys quickly.
for (const auto &i : ceph_options) {
if (schema.count(i.name)) {
// We may be instantiated pre-logging so send
std::cerr << "Duplicate config key in schema: '" << i.name << "'"
<< std::endl;
ceph_abort();
}
schema.emplace(i.name, i);
}
// Define the debug_* options as well.
subsys_options.reserve(values.subsys.get_num());
for (unsigned i = 0; i < values.subsys.get_num(); ++i) {
string name = string("debug_") + values.subsys.get_name(i);
subsys_options.push_back(
Option(name, Option::TYPE_STR, Option::LEVEL_ADVANCED));
Option& opt = subsys_options.back();
opt.set_default(stringify(values.subsys.get_log_level(i)) + "/" +
stringify(values.subsys.get_gather_level(i)));
string desc = string("Debug level for ") + values.subsys.get_name(i);
opt.set_description(desc.c_str());
opt.set_flag(Option::FLAG_RUNTIME);
opt.set_long_description("The value takes the form 'N' or 'N/M' where N and M are values between 0 and 99. N is the debug level to log (all values below this are included), and M is the level to gather and buffer in memory. In the event of a crash, the most recent items <= M are dumped to the log file.");
opt.set_subsys(i);
opt.set_validator([](std::string *value, std::string *error_message) {
int m, n;
int r = sscanf(value->c_str(), "%d/%d", &m, &n);
if (r >= 1) {
if (m < 0 || m > 99) {
*error_message = "value must be in range [0, 99]";
return -ERANGE;
}
if (r == 2) {
if (n < 0 || n > 99) {
*error_message = "value must be in range [0, 99]";
return -ERANGE;
}
} else {
// normalize to M/N
n = m;
*value = stringify(m) + "/" + stringify(n);
}
} else {
*error_message = "value must take the form N or N/M, where N and M are integers";
return -EINVAL;
}
return 0;
});
}
for (auto& opt : subsys_options) {
schema.emplace(opt.name, opt);
}
// Populate list of legacy_values according to the OPTION() definitions
// Note that this is just setting up our map of name->member ptr. The
// default values etc will get loaded in along with new-style data,
// as all loads write to both the values map, and the legacy
// members if present.
legacy_values = {
#define OPTION(name, type) \
{STRINGIFY(name), &ConfigValues::name},
#define SAFE_OPTION(name, type) OPTION(name, type)
#include "options/legacy_config_opts.h"
#undef OPTION
#undef SAFE_OPTION
};
validate_schema();
// Validate default values from the schema
for (const auto &i : schema) {
const Option &opt = i.second;
if (opt.type == Option::TYPE_STR) {
bool has_daemon_default = (opt.daemon_value != Option::value_t{});
Option::value_t default_val;
if (is_daemon && has_daemon_default) {
default_val = opt.daemon_value;
} else {
default_val = opt.value;
}
// We call pre_validate as a sanity check, but also to get any
// side effect (value modification) from the validator.
auto* def_str = std::get_if<std::string>(&default_val);
std::string val = *def_str;
std::string err;
if (opt.pre_validate(&val, &err) != 0) {
std::cerr << "Default value " << opt.name << "=" << *def_str << " is "
"invalid: " << err << std::endl;
// This is the compiled-in default that is failing its own option's
// validation, so this is super-invalid and should never make it
// past a pull request: crash out.
ceph_abort();
}
if (val != *def_str) {
// if the validator normalizes the string into a different form than
// what was compiled in, use that.
set_val_default(values, tracker, opt.name, val);
}
}
}
// Copy out values (defaults) into any legacy (C struct member) fields
update_legacy_vals(values);
}
md_config_t::~md_config_t()
{
}
/**
* Sanity check schema. Assert out on failures, to ensure any bad changes
* cannot possibly pass any testing and make it into a release.
*/
void md_config_t::validate_schema()
{
for (const auto &i : schema) {
const auto &opt = i.second;
for (const auto &see_also_key : opt.see_also) {
if (schema.count(see_also_key) == 0) {
std::cerr << "Non-existent see-also key '" << see_also_key
<< "' on option '" << opt.name << "'" << std::endl;
ceph_abort();
}
}
}
for (const auto &i : legacy_values) {
if (schema.count(i.first) == 0) {
std::cerr << "Schema is missing legacy field '" << i.first << "'"
<< std::endl;
ceph_abort();
}
}
}
const Option *md_config_t::find_option(const std::string_view name) const
{
auto p = schema.find(name);
if (p != schema.end()) {
return &p->second;
}
return nullptr;
}
void md_config_t::set_val_default(ConfigValues& values,
const ConfigTracker& tracker,
const string_view name, const std::string& val)
{
const Option *o = find_option(name);
ceph_assert(o);
string err;
int r = _set_val(values, tracker, val, *o, CONF_DEFAULT, &err);
ceph_assert(r >= 0);
}
int md_config_t::set_mon_vals(CephContext *cct,
ConfigValues& values,
const ConfigTracker& tracker,
const map<string,string,less<>>& kv,
config_callback config_cb)
{
ignored_mon_values.clear();
if (!config_cb) {
ldout(cct, 4) << __func__ << " no callback set" << dendl;
}
for (auto& i : kv) {
if (config_cb) {
if (config_cb(i.first, i.second)) {
ldout(cct, 4) << __func__ << " callback consumed " << i.first << dendl;
continue;
}
ldout(cct, 4) << __func__ << " callback ignored " << i.first << dendl;
}
const Option *o = find_option(i.first);
if (!o) {
ldout(cct,10) << __func__ << " " << i.first << " = " << i.second
<< " (unrecognized option)" << dendl;
continue;
}
if (o->has_flag(Option::FLAG_NO_MON_UPDATE)) {
ignored_mon_values.emplace(i);
continue;
}
std::string err;
int r = _set_val(values, tracker, i.second, *o, CONF_MON, &err);
if (r < 0) {
ldout(cct, 4) << __func__ << " failed to set " << i.first << " = "
<< i.second << ": " << err << dendl;
ignored_mon_values.emplace(i);
} else if (r == ConfigValues::SET_NO_CHANGE ||
r == ConfigValues::SET_NO_EFFECT) {
ldout(cct,20) << __func__ << " " << i.first << " = " << i.second
<< " (no change)" << dendl;
} else if (r == ConfigValues::SET_HAVE_EFFECT) {
ldout(cct,10) << __func__ << " " << i.first << " = " << i.second << dendl;
} else {
ceph_abort();
}
}
values.for_each([&] (auto name, auto configs) {
auto config = configs.find(CONF_MON);
if (config == configs.end()) {
return;
}
if (kv.find(name) != kv.end()) {
return;
}
ldout(cct,10) << __func__ << " " << name
<< " cleared (was " << Option::to_str(config->second) << ")"
<< dendl;
values.rm_val(name, CONF_MON);
// if this is a debug option, it needs to propagate to teh subsys;
// this isn't covered by update_legacy_vals() below. similarly,
// we want to trigger a config notification for these items.
const Option *o = find_option(name);
_refresh(values, *o);
});
values_bl.clear();
update_legacy_vals(values);
return 0;
}
int md_config_t::parse_config_files(ConfigValues& values,
const ConfigTracker& tracker,
const char *conf_files_str,
std::ostream *warnings,
int flags)
{
if (safe_to_start_threads)
return -ENOSYS;
if (values.cluster.empty() && !conf_files_str) {
values.cluster = get_cluster_name(nullptr);
}
// open new conf
for (auto& fn : get_conffile_paths(values, conf_files_str, warnings, flags)) {
bufferlist bl;
std::string error;
if (bl.read_file(fn.c_str(), &error)) {
parse_error = error;
continue;
}
ostringstream oss;
int ret = parse_buffer(values, tracker, bl.c_str(), bl.length(), &oss);
if (ret == 0) {
parse_error.clear();
conf_path = fn;
break;
}
parse_error = oss.str();
if (ret != -ENOENT) {
return ret;
}
}
// it must have been all ENOENTs, that's the only way we got here
if (conf_path.empty()) {
return -ENOENT;
}
if (values.cluster.empty()) {
values.cluster = get_cluster_name(conf_path.c_str());
}
update_legacy_vals(values);
return 0;
}
int
md_config_t::parse_buffer(ConfigValues& values,
const ConfigTracker& tracker,
const char* buf, size_t len,
std::ostream* warnings)
{
if (!cf.parse_buffer(string_view{buf, len}, warnings)) {
return -EINVAL;
}
const auto my_sections = get_my_sections(values);
for (const auto &i : schema) {
const auto &opt = i.second;
std::string val;
if (_get_val_from_conf_file(my_sections, opt.name, val)) {
continue;
}
std::string error_message;
if (_set_val(values, tracker, val, opt, CONF_FILE, &error_message) < 0) {
if (warnings != nullptr) {
*warnings << "parse error setting " << std::quoted(opt.name)
<< " to " << std::quoted(val);
if (!error_message.empty()) {
*warnings << " (" << error_message << ")";
}
*warnings << '\n';
}
}
}
cf.check_old_style_section_names({"mds", "mon", "osd"}, cerr);
return 0;
}
std::list<std::string>
md_config_t::get_conffile_paths(const ConfigValues& values,
const char *conf_files_str,
std::ostream *warnings,
int flags) const
{
if (!conf_files_str) {
const char *c = getenv("CEPH_CONF");
if (c) {
conf_files_str = c;
} else {
if (flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE)
return {};
conf_files_str = CEPH_CONF_FILE_DEFAULT;
}
}
std::list<std::string> paths;
get_str_list(conf_files_str, ";,", paths);
for (auto i = paths.begin(); i != paths.end(); ) {
string& path = *i;
if (path.find("$data_dir") != path.npos &&
data_dir_option.empty()) {
// useless $data_dir item, skip
i = paths.erase(i);
} else {
early_expand_meta(values, path, warnings);
++i;
}
}
return paths;
}
std::string md_config_t::get_cluster_name(const char* conffile)
{
if (conffile) {
// If cluster name is not set yet, use the prefix of the
// basename of configuration file as cluster name.
if (fs::path path{conffile}; path.extension() == ".conf") {
return path.stem().string();
} else {
// If the configuration file does not follow $cluster.conf
// convention, we do the last try and assign the cluster to
// 'ceph'.
return "ceph";
}
} else {
// set the cluster name to 'ceph' when configuration file is not specified.
return "ceph";
}
}
void md_config_t::parse_env(unsigned entity_type,
ConfigValues& values,
const ConfigTracker& tracker,
const char *args_var)
{
if (safe_to_start_threads)
return;
if (!args_var) {
args_var = "CEPH_ARGS";
}
if (auto s = getenv("CEPH_KEYRING"); s) {
string err;
_set_val(values, tracker, s, *find_option("keyring"), CONF_ENV, &err);
}
if (auto dir = getenv("CEPH_LIB"); dir) {
for (auto name : { "erasure_code_dir", "plugin_dir", "osd_class_dir" }) {
std::string err;
const Option *o = find_option(name);
ceph_assert(o);
_set_val(values, tracker, dir, *o, CONF_ENV, &err);
}
}
// Apply pod memory limits:
//
// There are two types of resource requests: `limits` and `requests`.
//
// - Requests: Used by the K8s scheduler to determine on which nodes to
// schedule the pods. This helps spread the pods to different nodes. This
// value should be conservative in order to make sure all the pods are
// schedulable. This corresponds to POD_MEMORY_REQUEST (set by the Rook
// CRD) and is the target memory utilization we try to maintain for daemons
// that respect it.
//
// If POD_MEMORY_REQUEST is present, we use it as the target.
//
// - Limits: At runtime, the container runtime (and Linux) will use the
// limits to see if the pod is using too many resources. In that case, the
// pod will be killed/restarted automatically if the pod goes over the limit.
// This should be higher than what is specified for requests (potentially
// much higher). This corresponds to the cgroup memory limit that will
// trigger the Linux OOM killer.
//
// If POD_MEMORY_LIMIT is present, we use it as the /default/ value for
// the target, which means it will only apply if the *_memory_target option
// isn't set via some other path (e.g., POD_MEMORY_REQUEST, or the cluster
// config, or whatever.)
//
// Here are the documented best practices:
// https://kubernetes.io/docs/tasks/configure-pod-container/assign-cpu-resource/#motivation-for-cpu-requests-and-limits
//
// When the operator creates the CephCluster CR, it will need to generate the
// desired requests and limits. As long as we are conservative in our choice
// for requests and generous with the limits we should be in a good place to
// get started.
//
// The support in Rook is already there for applying the limits as seen in
// these links.
//
// Rook docs on the resource requests and limits:
// https://rook.io/docs/rook/v1.0/ceph-cluster-crd.html#cluster-wide-resources-configuration-settings
// Example CR settings:
// https://github.com/rook/rook/blob/6d2ef936698593036185aabcb00d1d74f9c7bfc1/cluster/examples/kubernetes/ceph/cluster.yaml#L90
//
uint64_t pod_limit = 0, pod_request = 0;
if (auto pod_lim = getenv("POD_MEMORY_LIMIT"); pod_lim) {
string err;
uint64_t v = atoll(pod_lim);
if (v) {
switch (entity_type) {
case CEPH_ENTITY_TYPE_OSD:
{
double cgroup_ratio = get_val<double>(
values, "osd_memory_target_cgroup_limit_ratio");
if (cgroup_ratio > 0.0) {
pod_limit = v * cgroup_ratio;
// set osd_memory_target *default* based on cgroup limit, so that
// it can be overridden by any explicit settings elsewhere.
set_val_default(values, tracker,
"osd_memory_target", stringify(pod_limit));
}
}
}
}
}
if (auto pod_req = getenv("POD_MEMORY_REQUEST"); pod_req) {
if (uint64_t v = atoll(pod_req); v) {
pod_request = v;
}
}
if (pod_request && pod_limit) {
// If both LIMIT and REQUEST are set, ensure that we use the
// min of request and limit*ratio. This is important
// because k8s set set LIMIT == REQUEST if only LIMIT is
// specified, and we want to apply the ratio in that case,
// even though REQUEST is present.
pod_request = std::min<uint64_t>(pod_request, pod_limit);
}
if (pod_request) {
string err;
switch (entity_type) {
case CEPH_ENTITY_TYPE_OSD:
_set_val(values, tracker, stringify(pod_request),
*find_option("osd_memory_target"),
CONF_ENV, &err);
break;
}
}
if (getenv(args_var)) {
vector<const char *> env_args;
env_to_vec(env_args, args_var);
parse_argv(values, tracker, env_args, CONF_ENV);
}
}
void md_config_t::show_config(const ConfigValues& values,
std::ostream& out) const
{
_show_config(values, &out, nullptr);
}
void md_config_t::show_config(const ConfigValues& values,
Formatter *f) const
{
_show_config(values, nullptr, f);
}
void md_config_t::config_options(Formatter *f) const
{
f->open_array_section("options");
for (const auto& i: schema) {
f->dump_object("option", i.second);
}
f->close_section();
}
void md_config_t::_show_config(const ConfigValues& values,
std::ostream *out, Formatter *f) const
{
if (out) {
*out << "name = " << values.name << std::endl;
*out << "cluster = " << values.cluster << std::endl;
}
if (f) {
f->dump_string("name", stringify(values.name));
f->dump_string("cluster", values.cluster);
}
for (const auto& i: schema) {
const Option &opt = i.second;
string val;
conf_stringify(_get_val(values, opt), &val);
if (out) {
*out << opt.name << " = " << val << std::endl;
}
if (f) {
f->dump_string(opt.name.c_str(), val);
}
}
}
int md_config_t::parse_argv(ConfigValues& values,
const ConfigTracker& tracker,
std::vector<const char*>& args, int level)
{
if (safe_to_start_threads) {
return -ENOSYS;
}
// In this function, don't change any parts of the configuration directly.
// Instead, use set_val to set them. This will allow us to send the proper
// observer notifications later.
std::string val;
for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
if (strcmp(*i, "--") == 0) {
/* Normally we would use ceph_argparse_double_dash. However, in this
* function we *don't* want to remove the double dash, because later
* argument parses will still need to see it. */
break;
}
else if (ceph_argparse_flag(args, i, "--show_conf", (char*)NULL)) {
cerr << cf << std::endl;
_exit(0);
}
else if (ceph_argparse_flag(args, i, "--show_config", (char*)NULL)) {
do_show_config = true;
}
else if (ceph_argparse_witharg(args, i, &val, "--show_config_value", (char*)NULL)) {
do_show_config_value = val;
}
else if (ceph_argparse_flag(args, i, "--no-mon-config", (char*)NULL)) {
values.no_mon_config = true;
}
else if (ceph_argparse_flag(args, i, "--mon-config", (char*)NULL)) {
values.no_mon_config = false;
}
else if (ceph_argparse_flag(args, i, "--foreground", "-f", (char*)NULL)) {
set_val_or_die(values, tracker, "daemonize", "false");
}
else if (ceph_argparse_flag(args, i, "-d", (char*)NULL)) {
set_val_or_die(values, tracker, "fuse_debug", "true");
set_val_or_die(values, tracker, "daemonize", "false");
set_val_or_die(values, tracker, "log_file", "");
set_val_or_die(values, tracker, "log_to_stderr", "true");
set_val_or_die(values, tracker, "err_to_stderr", "true");
set_val_or_die(values, tracker, "log_to_syslog", "false");
}
// Some stuff that we wanted to give universal single-character options for
// Careful: you can burn through the alphabet pretty quickly by adding
// to this list.
else if (ceph_argparse_witharg(args, i, &val, "--monmap", "-M", (char*)NULL)) {
set_val_or_die(values, tracker, "monmap", val.c_str());
}
else if (ceph_argparse_witharg(args, i, &val, "--mon_host", "-m", (char*)NULL)) {
set_val_or_die(values, tracker, "mon_host", val.c_str());
}
else if (ceph_argparse_witharg(args, i, &val, "--bind", (char*)NULL)) {
set_val_or_die(values, tracker, "public_addr", val.c_str());
}
else if (ceph_argparse_witharg(args, i, &val, "--keyfile", "-K", (char*)NULL)) {
bufferlist bl;
string err;
int r;
if (val == "-") {
r = bl.read_fd(STDIN_FILENO, 1024);
} else {
r = bl.read_file(val.c_str(), &err);
}
if (r >= 0) {
string k(bl.c_str(), bl.length());
set_val_or_die(values, tracker, "key", k.c_str());
}
}
else if (ceph_argparse_witharg(args, i, &val, "--keyring", "-k", (char*)NULL)) {
set_val_or_die(values, tracker, "keyring", val.c_str());
}
else if (ceph_argparse_witharg(args, i, &val, "--client_mountpoint", "-r", (char*)NULL)) {
set_val_or_die(values, tracker, "client_mountpoint", val.c_str());
}
else {
int r = parse_option(values, tracker, args, i, NULL, level);
if (r < 0) {
return r;
}
}
}
// meta expands could have modified anything. Copy it all out again.
update_legacy_vals(values);
return 0;
}
void md_config_t::do_argv_commands(const ConfigValues& values) const
{
if (do_show_config) {
_show_config(values, &cout, NULL);
_exit(0);
}
if (do_show_config_value.size()) {
string val;
int r = conf_stringify(_get_val(values, do_show_config_value, 0, &cerr),
&val);
if (r < 0) {
if (r == -ENOENT)
std::cerr << "failed to get config option '"
<< do_show_config_value << "': option not found" << std::endl;
else
std::cerr << "failed to get config option '"
<< do_show_config_value << "': " << cpp_strerror(r)
<< std::endl;
_exit(1);
}
std::cout << val << std::endl;
_exit(0);
}
}
int md_config_t::parse_option(ConfigValues& values,
const ConfigTracker& tracker,
std::vector<const char*>& args,
std::vector<const char*>::iterator& i,
ostream *oss,
int level)
{
int ret = 0;
size_t o = 0;
std::string val;
std::string option_name;
std::string error_message;
o = 0;
for (const auto& opt_iter: schema) {
const Option &opt = opt_iter.second;
ostringstream err;
std::string as_option("--");
as_option += opt.name;
option_name = opt.name;
if (ceph_argparse_witharg(
args, i, &val, err,
string(string("--default-") + opt.name).c_str(), (char*)NULL)) {
if (!err.str().empty()) {
error_message = err.str();
ret = -EINVAL;
break;
}
ret = _set_val(values, tracker, val, opt, CONF_DEFAULT, &error_message);
break;
} else if (opt.type == Option::TYPE_BOOL) {
int res;
if (ceph_argparse_binary_flag(args, i, &res, oss, as_option.c_str(),
(char*)NULL)) {
if (res == 0)
ret = _set_val(values, tracker, "false", opt, level, &error_message);
else if (res == 1)
ret = _set_val(values, tracker, "true", opt, level, &error_message);
else
ret = res;
break;
} else {
std::string no("--no-");
no += opt.name;
if (ceph_argparse_flag(args, i, no.c_str(), (char*)NULL)) {
ret = _set_val(values, tracker, "false", opt, level, &error_message);
break;
}
}
} else if (ceph_argparse_witharg(args, i, &val, err,
as_option.c_str(), (char*)NULL)) {
if (!err.str().empty()) {
error_message = err.str();
ret = -EINVAL;
break;
}
ret = _set_val(values, tracker, val, opt, level, &error_message);
break;
}
++o;
}
if (ret < 0 || !error_message.empty()) {
ceph_assert(!option_name.empty());
if (oss) {
*oss << "Parse error setting " << option_name << " to '"
<< val << "' using injectargs";
if (!error_message.empty()) {
*oss << " (" << error_message << ")";
}
*oss << ".\n";
} else {
cerr << "parse error setting '" << option_name << "' to '"
<< val << "'";
if (!error_message.empty()) {
cerr << " (" << error_message << ")";
}
cerr << "\n" << std::endl;
}
}
if (o == schema.size()) {
// ignore
++i;
}
return ret >= 0 ? 0 : ret;
}
int md_config_t::parse_injectargs(ConfigValues& values,
const ConfigTracker& tracker,
std::vector<const char*>& args,
std::ostream *oss)
{
int ret = 0;
for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
int r = parse_option(values, tracker, args, i, oss, CONF_OVERRIDE);
if (r < 0)
ret = r;
}
return ret;
}
void md_config_t::set_safe_to_start_threads()
{
safe_to_start_threads = true;
}
void md_config_t::_clear_safe_to_start_threads()
{
safe_to_start_threads = false;
}
int md_config_t::injectargs(ConfigValues& values,
const ConfigTracker& tracker,
const std::string& s, std::ostream *oss)
{
int ret;
char b[s.length()+1];
strcpy(b, s.c_str());
std::vector<const char*> nargs;
char *p = b;
while (*p) {
nargs.push_back(p);
while (*p && *p != ' ') p++;
if (!*p)
break;
*p++ = 0;
while (*p && *p == ' ') p++;
}
ret = parse_injectargs(values, tracker, nargs, oss);
if (!nargs.empty()) {
*oss << " failed to parse arguments: ";
std::string prefix;
for (std::vector<const char*>::const_iterator i = nargs.begin();
i != nargs.end(); ++i) {
*oss << prefix << *i;
prefix = ",";
}
*oss << "\n";
ret = -EINVAL;
}
update_legacy_vals(values);
return ret;
}
void md_config_t::set_val_or_die(ConfigValues& values,
const ConfigTracker& tracker,
const std::string_view key,
const std::string &val)
{
std::stringstream err;
int ret = set_val(values, tracker, key, val, &err);
if (ret != 0) {
std::cerr << "set_val_or_die(" << key << "): " << err.str();
}
ceph_assert(ret == 0);
}
int md_config_t::set_val(ConfigValues& values,
const ConfigTracker& tracker,
const std::string_view key, const char *val,
std::stringstream *err_ss)
{
if (key.empty()) {
if (err_ss) *err_ss << "No key specified";
return -EINVAL;
}
if (!val) {
return -EINVAL;
}
std::string v(val);
string k(ConfFile::normalize_key_name(key));
const auto &opt_iter = schema.find(k);
if (opt_iter != schema.end()) {
const Option &opt = opt_iter->second;
std::string error_message;
int r = _set_val(values, tracker, v, opt, CONF_OVERRIDE, &error_message);
if (r >= 0) {
if (err_ss) *err_ss << "Set " << opt.name << " to " << v;
r = 0;
} else {
if (err_ss) *err_ss << error_message;
}
return r;
}
if (err_ss) *err_ss << "Configuration option not found: '" << key << "'";
return -ENOENT;
}
int md_config_t::rm_val(ConfigValues& values, const std::string_view key)
{
return _rm_val(values, key, CONF_OVERRIDE);
}
void md_config_t::get_defaults_bl(const ConfigValues& values,
bufferlist *bl)
{
if (defaults_bl.length() == 0) {
uint32_t n = 0;
bufferlist bl;
for (const auto &i : schema) {
++n;
encode(i.second.name, bl);
auto [value, found] = values.get_value(i.second.name, CONF_DEFAULT);
if (found) {
encode(Option::to_str(value), bl);
} else {
string val;
conf_stringify(_get_val_default(i.second), &val);
encode(val, bl);
}
}
encode(n, defaults_bl);
defaults_bl.claim_append(bl);
}
*bl = defaults_bl;
}
void md_config_t::get_config_bl(
const ConfigValues& values,
uint64_t have_version,
bufferlist *bl,
uint64_t *got_version)
{
if (values_bl.length() == 0) {
uint32_t n = 0;
bufferlist bl;
values.for_each([&](auto& name, auto& configs) {
if (name == "fsid" ||
name == "host") {
return;
}
++n;
encode(name, bl);
encode((uint32_t)configs.size(), bl);
for (auto& j : configs) {
encode(j.first, bl);
encode(Option::to_str(j.second), bl);
}
});
// make sure overridden items appear, and include the default value
for (auto& i : ignored_mon_values) {
if (values.contains(i.first)) {
continue;
}
if (i.first == "fsid" ||
i.first == "host") {
continue;
}
const Option *opt = find_option(i.first);
if (!opt) {
continue;
}
++n;
encode(i.first, bl);
encode((uint32_t)1, bl);
encode((int32_t)CONF_DEFAULT, bl);
string val;
conf_stringify(_get_val_default(*opt), &val);
encode(val, bl);
}
encode(n, values_bl);
values_bl.claim_append(bl);
encode(ignored_mon_values, values_bl);
++values_bl_version;
}
if (have_version != values_bl_version) {
*bl = values_bl;
*got_version = values_bl_version;
}
}
std::optional<std::string> md_config_t::get_val_default(std::string_view key)
{
std::string val;
const Option *opt = find_option(key);
if (opt && (conf_stringify(_get_val_default(*opt), &val) == 0)) {
return std::make_optional(std::move(val));
}
return std::nullopt;
}
int md_config_t::get_val(const ConfigValues& values,
const std::string_view key, char **buf, int len) const
{
string k(ConfFile::normalize_key_name(key));
return _get_val_cstr(values, k, buf, len);
}
int md_config_t::get_val(
const ConfigValues& values,
const std::string_view key,
std::string *val) const
{
return conf_stringify(get_val_generic(values, key), val);
}
Option::value_t md_config_t::get_val_generic(
const ConfigValues& values,
const std::string_view key) const
{
return _get_val(values, key);
}
Option::value_t md_config_t::_get_val(
const ConfigValues& values,
const std::string_view key,
expand_stack_t *stack,
std::ostream *err) const
{
if (key.empty()) {
return {};
}
// In key names, leading and trailing whitespace are not significant.
string k(ConfFile::normalize_key_name(key));
const Option *o = find_option(k);
if (!o) {
// not a valid config option
return {};
}
return _get_val(values, *o, stack, err);
}
Option::value_t md_config_t::_get_val(
const ConfigValues& values,
const Option& o,
expand_stack_t *stack,
std::ostream *err) const
{
expand_stack_t a_stack;
if (!stack) {
stack = &a_stack;
}
return _expand_meta(values,
_get_val_nometa(values, o),
&o, stack, err);
}
Option::value_t md_config_t::_get_val_nometa(const ConfigValues& values,
const Option& o) const
{
if (auto [value, found] = values.get_value(o.name, -1); found) {
return value;
} else {
return _get_val_default(o);
}
}
const Option::value_t& md_config_t::_get_val_default(const Option& o) const
{
bool has_daemon_default = (o.daemon_value != Option::value_t{});
if (is_daemon && has_daemon_default) {
return o.daemon_value;
} else {
return o.value;
}
}
void md_config_t::early_expand_meta(
const ConfigValues& values,
std::string &val,
std::ostream *err) const
{
expand_stack_t stack;
Option::value_t v = _expand_meta(values,
Option::value_t(val),
nullptr, &stack, err);
conf_stringify(v, &val);
}
bool md_config_t::finalize_reexpand_meta(ConfigValues& values,
const ConfigTracker& tracker)
{
std::vector<std::string> reexpands;
reexpands.swap(may_reexpand_meta);
for (auto& name : reexpands) {
// always refresh the options if they are in the may_reexpand_meta
// map, because the options may have already been expanded with old
// meta.
const auto &opt_iter = schema.find(name);
ceph_assert(opt_iter != schema.end());
const Option &opt = opt_iter->second;
_refresh(values, opt);
}
return !may_reexpand_meta.empty();
}
Option::value_t md_config_t::_expand_meta(
const ConfigValues& values,
const Option::value_t& in,
const Option *o,
expand_stack_t *stack,
std::ostream *err) const
{
//cout << __func__ << " in '" << in << "' stack " << stack << std::endl;
if (!stack) {
return in;
}
const auto str = std::get_if<std::string>(&in);
if (!str) {
// strings only!
return in;
}
auto pos = str->find('$');
if (pos == std::string::npos) {
// no substitutions!
return in;
}
if (o) {
stack->push_back(make_pair(o, &in));
}
string out;
decltype(pos) last_pos = 0;
while (pos != std::string::npos) {
ceph_assert((*str)[pos] == '$');
if (pos > last_pos) {
out += str->substr(last_pos, pos - last_pos);
}
// try to parse the variable name into var, either \$\{(.+)\} or
// \$[a-z\_]+
const char *valid_chars = "abcdefghijklmnopqrstuvwxyz_";
string var;
size_t endpos = 0;
if ((*str)[pos+1] == '{') {
// ...${foo_bar}...
endpos = str->find_first_not_of(valid_chars, pos + 2);
if (endpos != std::string::npos &&
(*str)[endpos] == '}') {
var = str->substr(pos + 2, endpos - pos - 2);
endpos++;
}
} else {
// ...$foo...
endpos = str->find_first_not_of(valid_chars, pos + 1);
if (endpos != std::string::npos)
var = str->substr(pos + 1, endpos - pos - 1);
else
var = str->substr(pos + 1);
}
last_pos = endpos;
if (!var.size()) {
out += '$';
} else {
//cout << " found var " << var << std::endl;
// special metavariable?
if (var == "type") {
out += values.name.get_type_name();
} else if (var == "cluster") {
out += values.cluster;
} else if (var == "name") {
out += values.name.to_cstr();
} else if (var == "host") {
if (values.host == "") {
out += ceph_get_short_hostname();
} else {
out += values.host;
}
} else if (var == "num") {
out += values.name.get_id().c_str();
} else if (var == "id") {
out += values.name.get_id();
} else if (var == "pid") {
char *_pid = getenv("PID");
if (_pid) {
out += _pid;
} else {
out += stringify(getpid());
}
if (o) {
may_reexpand_meta.push_back(o->name);
}
} else if (var == "cctid") {
out += stringify((unsigned long long)this);
} else if (var == "home") {
const char *home = getenv("HOME");
out = home ? std::string(home) : std::string();
} else if (var == "programdata") {
const char *home = getenv("ProgramData");
out = home ? std::string(home) : std::string();
}else {
if (var == "data_dir") {
var = data_dir_option;
}
const Option *o = find_option(var);
if (!o) {
out += str->substr(pos, endpos - pos);
} else {
auto match = std::find_if(
stack->begin(), stack->end(),
[o](pair<const Option *,const Option::value_t*>& item) {
return item.first == o;
});
if (match != stack->end()) {
// substitution loop; break the cycle
if (err) {
*err << "variable expansion loop at " << var << "="
<< Option::to_str(*match->second) << "\n"
<< "expansion stack:\n";
for (auto i = stack->rbegin(); i != stack->rend(); ++i) {
*err << i->first->name << "="
<< Option::to_str(*i->second) << "\n";
}
}
return Option::value_t(std::string("$") + o->name);
} else {
// recursively evaluate!
string n;
conf_stringify(_get_val(values, *o, stack, err), &n);
out += n;
}
}
}
}
pos = str->find('$', last_pos);
}
if (last_pos != std::string::npos) {
out += str->substr(last_pos);
}
if (o) {
stack->pop_back();
}
return Option::value_t(out);
}
int md_config_t::_get_val_cstr(
const ConfigValues& values,
const std::string& key, char **buf, int len) const
{
if (key.empty())
return -EINVAL;
string val;
if (conf_stringify(_get_val(values, key), &val) == 0) {
int l = val.length() + 1;
if (len == -1) {
*buf = (char*)malloc(l);
if (!*buf)
return -ENOMEM;
strncpy(*buf, val.c_str(), l);
return 0;
}
snprintf(*buf, len, "%s", val.c_str());
return (l > len) ? -ENAMETOOLONG : 0;
}
// couldn't find a configuration option with key 'k'
return -ENOENT;
}
void md_config_t::get_all_keys(std::vector<std::string> *keys) const {
const std::string negative_flag_prefix("no_");
keys->clear();
keys->reserve(schema.size());
for (const auto &i: schema) {
const Option &opt = i.second;
keys->push_back(opt.name);
if (opt.type == Option::TYPE_BOOL) {
keys->push_back(negative_flag_prefix + opt.name);
}
}
}
/* The order of the sections here is important. The first section in the
* vector is the "highest priority" section; if we find it there, we'll stop
* looking. The lowest priority section is the one we look in only if all
* others had nothing. This should always be the global section.
*/
std::vector <std::string>
md_config_t::get_my_sections(const ConfigValues& values) const
{
return {values.name.to_str(),
values.name.get_type_name().data(),
"global"};
}
// Return a list of all sections
int md_config_t::get_all_sections(std::vector <std::string> §ions) const
{
for (auto [section_name, section] : cf) {
sections.push_back(section_name);
std::ignore = section;
}
return 0;
}
int md_config_t::get_val_from_conf_file(
const ConfigValues& values,
const std::vector <std::string> §ions,
const std::string_view key,
std::string &out,
bool emeta) const
{
int r = _get_val_from_conf_file(sections, key, out);
if (r < 0) {
return r;
}
if (emeta) {
expand_stack_t stack;
auto v = _expand_meta(values, Option::value_t(out), nullptr, &stack, nullptr);
conf_stringify(v, &out);
}
return 0;
}
int md_config_t::_get_val_from_conf_file(
const std::vector <std::string> §ions,
const std::string_view key,
std::string &out) const
{
for (auto &s : sections) {
int ret = cf.read(s, key, out);
if (ret == 0) {
return 0;
} else if (ret != -ENOENT) {
return ret;
}
}
return -ENOENT;
}
int md_config_t::_set_val(
ConfigValues& values,
const ConfigTracker& observers,
const std::string &raw_val,
const Option &opt,
int level,
std::string *error_message)
{
Option::value_t new_value;
ceph_assert(error_message);
int r = opt.parse_value(raw_val, &new_value, error_message);
if (r < 0) {
return r;
}
// unsafe runtime change?
if (!opt.can_update_at_runtime() &&
safe_to_start_threads &&
!observers.is_tracking(opt.name)) {
// accept value if it is not actually a change
if (new_value != _get_val_nometa(values, opt)) {
*error_message = string("Configuration option '") + opt.name +
"' may not be modified at runtime";
return -EPERM;
}
}
// Apply the value to its entry in the `values` map
auto result = values.set_value(opt.name, std::move(new_value), level);
switch (result) {
case ConfigValues::SET_NO_CHANGE:
break;
case ConfigValues::SET_NO_EFFECT:
values_bl.clear();
break;
case ConfigValues::SET_HAVE_EFFECT:
values_bl.clear();
_refresh(values, opt);
break;
}
return result;
}
void md_config_t::_refresh(ConfigValues& values, const Option& opt)
{
// Apply the value to its legacy field, if it has one
auto legacy_ptr_iter = legacy_values.find(std::string(opt.name));
if (legacy_ptr_iter != legacy_values.end()) {
update_legacy_val(values, opt, legacy_ptr_iter->second);
}
// Was this a debug_* option update?
if (opt.subsys >= 0) {
string actual_val;
conf_stringify(_get_val(values, opt), &actual_val);
values.set_logging(opt.subsys, actual_val.c_str());
} else {
// normal option, advertise the change.
values.changed.insert(opt.name);
}
}
int md_config_t::_rm_val(ConfigValues& values,
const std::string_view key,
int level)
{
if (schema.count(key) == 0) {
return -EINVAL;
}
auto ret = values.rm_val(std::string{key}, level);
if (ret < 0) {
return ret;
}
if (ret == ConfigValues::SET_HAVE_EFFECT) {
_refresh(values, *find_option(key));
}
values_bl.clear();
return 0;
}
namespace {
template<typename Size>
struct get_size_visitor
{
get_size_visitor() {}
template<typename T>
Size operator()(const T&) const {
return -1;
}
Size operator()(const Option::size_t& sz) const {
return static_cast<Size>(sz.value);
}
Size operator()(const Size& v) const {
return v;
}
};
/**
* Handles assigning from a variant-of-types to a variant-of-pointers-to-types
*/
class assign_visitor
{
ConfigValues *conf;
Option::value_t val;
public:
assign_visitor(ConfigValues *conf_, Option::value_t val_)
: conf(conf_), val(val_)
{}
template <typename T>
void operator()(T ConfigValues::* ptr) const
{
T *member = const_cast<T *>(&(conf->*(ptr)));
*member = std::get<T>(val);
}
void operator()(uint64_t ConfigValues::* ptr) const
{
using T = uint64_t;
auto member = const_cast<T*>(&(conf->*(ptr)));
*member = std::visit(get_size_visitor<T>{}, val);
}
void operator()(int64_t ConfigValues::* ptr) const
{
using T = int64_t;
auto member = const_cast<T*>(&(conf->*(ptr)));
*member = std::visit(get_size_visitor<T>{}, val);
}
};
} // anonymous namespace
void md_config_t::update_legacy_vals(ConfigValues& values)
{
for (const auto &i : legacy_values) {
const auto &name = i.first;
const auto &option = schema.at(name);
auto ptr = i.second;
update_legacy_val(values, option, ptr);
}
}
void md_config_t::update_legacy_val(ConfigValues& values,
const Option &opt,
md_config_t::member_ptr_t member_ptr)
{
Option::value_t v = _get_val(values, opt);
std::visit(assign_visitor(&values, v), member_ptr);
}
static void dump(Formatter *f, int level, Option::value_t in)
{
if (const auto v = std::get_if<bool>(&in)) {
f->dump_bool(ceph_conf_level_name(level), *v);
} else if (const auto v = std::get_if<int64_t>(&in)) {
f->dump_int(ceph_conf_level_name(level), *v);
} else if (const auto v = std::get_if<uint64_t>(&in)) {
f->dump_unsigned(ceph_conf_level_name(level), *v);
} else if (const auto v = std::get_if<double>(&in)) {
f->dump_float(ceph_conf_level_name(level), *v);
} else {
f->dump_stream(ceph_conf_level_name(level)) << Option::to_str(in);
}
}
void md_config_t::diff(
const ConfigValues& values,
Formatter *f,
string name) const
{
values.for_each([this, f, &values] (auto& name, auto& configs) {
if (configs.empty()) {
return;
}
f->open_object_section(std::string{name}.c_str());
const Option *o = find_option(name);
if (configs.size() &&
configs.begin()->first != CONF_DEFAULT) {
// show compiled-in default only if an override default wasn't provided
dump(f, CONF_DEFAULT, _get_val_default(*o));
}
for (auto& j : configs) {
dump(f, j.first, j.second);
}
dump(f, CONF_FINAL, _get_val(values, *o));
f->close_section();
});
}
void md_config_t::complain_about_parse_error(CephContext *cct)
{
::complain_about_parse_error(cct, parse_error);
}
| 44,610 | 27.270596 | 312 | cc |
null | ceph-main/src/common/config.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_CONFIG_H
#define CEPH_CONFIG_H
#include <map>
#include <variant>
#include <boost/container/small_vector.hpp>
#include "common/ConfUtils.h"
#include "common/code_environment.h"
#include "log/SubsystemMap.h"
#include "common/options.h"
#include "common/subsys_types.h"
#include "common/config_tracker.h"
#include "common/config_values.h"
#include "include/common_fwd.h"
enum {
CONF_DEFAULT,
CONF_MON,
CONF_FILE,
CONF_ENV,
CONF_CMDLINE,
CONF_OVERRIDE,
CONF_FINAL
};
extern const char *ceph_conf_level_name(int level);
/** This class represents the current Ceph configuration.
*
* For Ceph daemons, this is the daemon configuration. Log levels, caching
* settings, btrfs settings, and so forth can all be found here. For libcephfs
* and librados users, this is the configuration associated with their context.
*
* For information about how this class is loaded from a configuration file,
* see common/ConfUtils.
*
* ACCESS
*
* There are 3 ways to read the ceph context-- the old way and two new ways.
* In the old way, code would simply read the public variables of the
* configuration, without taking a lock. In the new way #1, code registers a
* configuration observer which receives callbacks when a value changes. These
* callbacks take place under the md_config_t lock. Alternatively one can use
* get_val(const char *name) method to safely get a copy of the value.
*
* To prevent serious problems resulting from thread-safety issues, we disallow
* changing std::string configuration values after
* md_config_t::safe_to_start_threads becomes true. You can still
* change integer or floating point values, and the option declared with
* SAFE_OPTION macro. Notice the latter options can not be read directly
* (conf->foo), one should use either observers or get_val() method
* (conf->get_val("foo")).
*
* FIXME: really we shouldn't allow changing integer or floating point values
* while another thread is reading them, either.
*/
struct md_config_t {
public:
typedef std::variant<int64_t ConfigValues::*,
uint64_t ConfigValues::*,
std::string ConfigValues::*,
double ConfigValues::*,
bool ConfigValues::*,
entity_addr_t ConfigValues::*,
entity_addrvec_t ConfigValues::*,
uuid_d ConfigValues::*> member_ptr_t;
// For use when intercepting configuration updates
typedef std::function<bool(
const std::string &k, const std::string &v)> config_callback;
/// true if we are a daemon (as per CephContext::code_env)
const bool is_daemon;
/*
* Mapping from legacy config option names to class members
*/
std::map<std::string_view, member_ptr_t> legacy_values;
/**
* The configuration schema, in the form of Option objects describing
* possible settings.
*/
std::map<std::string_view, const Option&> schema;
/// values from mon that we failed to set
std::map<std::string,std::string> ignored_mon_values;
/// original raw values saved that may need to re-expand at certain time
mutable std::vector<std::string> may_reexpand_meta;
/// encoded, cached copy of of values + ignored_mon_values
ceph::bufferlist values_bl;
/// version for values_bl; increments each time there is a change
uint64_t values_bl_version = 0;
/// encoded copy of defaults (map<string,string>)
ceph::bufferlist defaults_bl;
// Create a new md_config_t structure.
explicit md_config_t(ConfigValues& values,
const ConfigTracker& tracker,
bool is_daemon=false);
~md_config_t();
// Parse a config file
int parse_config_files(ConfigValues& values, const ConfigTracker& tracker,
const char *conf_files,
std::ostream *warnings, int flags);
int parse_buffer(ConfigValues& values, const ConfigTracker& tracker,
const char* buf, size_t len,
std::ostream *warnings);
void update_legacy_vals(ConfigValues& values);
// Absorb config settings from the environment
void parse_env(unsigned entity_type,
ConfigValues& values, const ConfigTracker& tracker,
const char *env_var = "CEPH_ARGS");
// Absorb config settings from argv
int parse_argv(ConfigValues& values, const ConfigTracker& tracker,
std::vector<const char*>& args, int level=CONF_CMDLINE);
// do any commands we got from argv (--show-config, --show-config-val)
void do_argv_commands(const ConfigValues& values) const;
bool _internal_field(const std::string& k);
void set_safe_to_start_threads();
void _clear_safe_to_start_threads(); // this is only used by the unit test
/// Look up an option in the schema
const Option *find_option(const std::string_view name) const;
/// Set a default value
void set_val_default(ConfigValues& values,
const ConfigTracker& tracker,
const std::string_view key, const std::string &val);
/// Set a values from mon
int set_mon_vals(CephContext *cct,
ConfigValues& values,
const ConfigTracker& tracker,
const std::map<std::string,std::string, std::less<>>& kv,
config_callback config_cb);
// Called by the Ceph daemons to make configuration changes at runtime
int injectargs(ConfigValues& values,
const ConfigTracker& tracker,
const std::string &s,
std::ostream *oss);
// Set a configuration value, or crash
// Metavariables will be expanded.
void set_val_or_die(ConfigValues& values, const ConfigTracker& tracker,
const std::string_view key, const std::string &val);
// Set a configuration value.
// Metavariables will be expanded.
int set_val(ConfigValues& values, const ConfigTracker& tracker,
const std::string_view key, const char *val,
std::stringstream *err_ss=nullptr);
int set_val(ConfigValues& values, const ConfigTracker& tracker,
const std::string_view key, const std::string& s,
std::stringstream *err_ss=nullptr) {
return set_val(values, tracker, key, s.c_str(), err_ss);
}
/// clear override value
int rm_val(ConfigValues& values, const std::string_view key);
/// get encoded map<string,map<int32_t,string>> of entire config
void get_config_bl(const ConfigValues& values,
uint64_t have_version,
ceph::buffer::list *bl,
uint64_t *got_version);
/// get encoded map<string,string> of compiled-in defaults
void get_defaults_bl(const ConfigValues& values, ceph::buffer::list *bl);
/// Get the default value of a configuration option
std::optional<std::string> get_val_default(std::string_view key);
// Get a configuration value.
// No metavariables will be returned (they will have already been expanded)
int get_val(const ConfigValues& values, const std::string_view key, char **buf, int len) const;
int get_val(const ConfigValues& values, const std::string_view key, std::string *val) const;
template<typename T> const T get_val(const ConfigValues& values, const std::string_view key) const;
template<typename T, typename Callback, typename...Args>
auto with_val(const ConfigValues& values, const std::string_view key,
Callback&& cb, Args&&... args) const ->
std::result_of_t<Callback(const T&, Args...)> {
return std::forward<Callback>(cb)(
std::get<T>(this->get_val_generic(values, key)),
std::forward<Args>(args)...);
}
void get_all_keys(std::vector<std::string> *keys) const;
// Return a list of all the sections that the current entity is a member of.
std::vector<std::string> get_my_sections(const ConfigValues& values) const;
// Return a list of all sections
int get_all_sections(std::vector <std::string> §ions) const;
// Get a value from the configuration file that we read earlier.
// Metavariables will be expanded if emeta is true.
int get_val_from_conf_file(const ConfigValues& values,
const std::vector <std::string> §ions,
const std::string_view key, std::string &out, bool emeta) const;
/// dump all config values to a stream
void show_config(const ConfigValues& values, std::ostream& out) const;
/// dump all config values to a formatter
void show_config(const ConfigValues& values, ceph::Formatter *f) const;
/// dump all config settings to a formatter
void config_options(ceph::Formatter *f) const;
/// dump config diff from default, conf, mon, etc.
void diff(const ConfigValues& values,
ceph::Formatter *f,
std::string name = {}) const;
/// print/log warnings/errors from parsing the config
void complain_about_parse_error(CephContext *cct);
private:
// we use this to avoid variable expansion loops
typedef boost::container::small_vector<std::pair<const Option*,
const Option::value_t*>,
4> expand_stack_t;
void validate_schema();
void validate_default_settings();
Option::value_t get_val_generic(const ConfigValues& values,
const std::string_view key) const;
int _get_val_cstr(const ConfigValues& values,
const std::string& key, char **buf, int len) const;
Option::value_t _get_val(const ConfigValues& values,
const std::string_view key,
expand_stack_t *stack=0,
std::ostream *err=0) const;
Option::value_t _get_val(const ConfigValues& values,
const Option& o,
expand_stack_t *stack=0,
std::ostream *err=0) const;
const Option::value_t& _get_val_default(const Option& o) const;
Option::value_t _get_val_nometa(const ConfigValues& values,
const Option& o) const;
int _rm_val(ConfigValues& values, const std::string_view key, int level);
void _refresh(ConfigValues& values, const Option& opt);
void _show_config(const ConfigValues& values,
std::ostream *out, ceph::Formatter *f) const;
int _get_val_from_conf_file(const std::vector<std::string> §ions,
const std::string_view key, std::string &out) const;
int parse_option(ConfigValues& values,
const ConfigTracker& tracker,
std::vector<const char*>& args,
std::vector<const char*>::iterator& i,
std::ostream *oss,
int level);
int parse_injectargs(ConfigValues& values,
const ConfigTracker& tracker,
std::vector<const char*>& args,
std::ostream *oss);
// @returns negative number for an error, otherwise a
// @c ConfigValues::set_value_result_t is returned.
int _set_val(
ConfigValues& values,
const ConfigTracker& tracker,
const std::string &val,
const Option &opt,
int level, // CONF_*
std::string *error_message);
template <typename T>
void assign_member(member_ptr_t ptr, const Option::value_t &val);
void update_legacy_val(ConfigValues& values,
const Option &opt,
member_ptr_t member);
Option::value_t _expand_meta(
const ConfigValues& values,
const Option::value_t& in,
const Option *o,
expand_stack_t *stack,
std::ostream *err) const;
public: // for global_init
void early_expand_meta(const ConfigValues& values,
std::string &val,
std::ostream *oss) const;
// for those want to reexpand special meta, e.g, $pid
bool finalize_reexpand_meta(ConfigValues& values,
const ConfigTracker& tracker);
std::list<std::string> get_conffile_paths(const ConfigValues& values,
const char *conf_files,
std::ostream *warnings,
int flags) const;
const std::string& get_conf_path() const {
return conf_path;
}
private:
static std::string get_cluster_name(const char* conffile_path);
// The configuration file we read, or NULL if we haven't read one.
ConfFile cf;
std::string conf_path;
public:
std::string parse_error;
private:
// This will be set to true when it is safe to start threads.
// Once it is true, it will never change.
bool safe_to_start_threads = false;
bool do_show_config = false;
std::string do_show_config_value;
std::vector<Option> subsys_options;
public:
std::string data_dir_option; ///< data_dir config option, if any
public:
unsigned get_osd_pool_default_min_size(const ConfigValues& values,
uint8_t size) const {
uint8_t min_size = get_val<uint64_t>(values, "osd_pool_default_min_size");
return min_size ? std::min(min_size, size) : (size - size / 2);
}
friend class test_md_config_t;
};
template<typename T>
const T md_config_t::get_val(const ConfigValues& values,
const std::string_view key) const {
return std::get<T>(this->get_val_generic(values, key));
}
inline std::ostream& operator<<(std::ostream& o, const std::monostate&) {
return o << "INVALID_CONFIG_VALUE";
}
int ceph_resolve_file_search(const std::string& filename_list,
std::string& result);
#endif
| 13,123 | 33.997333 | 101 | h |
null | ceph-main/src/common/config_cacher.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_CONFIG_CACHER_H
#define CEPH_CONFIG_CACHER_H
#include "common/config_obs.h"
#include "common/config.h"
template <typename ValueT>
class md_config_cacher_t : public md_config_obs_t {
ConfigProxy& conf;
const char* const option_name;
std::atomic<ValueT> value_cache;
const char** get_tracked_conf_keys() const override {
const static char* keys[] = { option_name, nullptr };
return keys;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set<std::string>& changed) override {
if (changed.count(option_name)) {
value_cache.store(conf.get_val<ValueT>(option_name));
}
}
public:
md_config_cacher_t(ConfigProxy& conf,
const char* const option_name)
: conf(conf),
option_name(option_name) {
conf.add_observer(this);
std::atomic_init(&value_cache,
conf.get_val<ValueT>(option_name));
}
~md_config_cacher_t() {
conf.remove_observer(this);
}
operator ValueT() const {
return value_cache.load();
}
};
#endif // CEPH_CONFIG_CACHER_H
| 1,523 | 24.4 | 74 | h |
null | ceph-main/src/common/config_fwd.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#pragma once
#include "include/common_fwd.h"
namespace TOPNSPC::common {
class ConfigProxy;
}
using TOPNSPC::common::ConfigProxy;
| 205 | 19.6 | 70 | h |
null | ceph-main/src/common/config_obs.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_CONFIG_OBS_H
#define CEPH_CONFIG_OBS_H
#include <set>
#include <string>
#include "common/config_fwd.h"
namespace ceph {
/** @brief Base class for configuration observers.
* Use this as a base class for your object if it has to respond to configuration changes,
* for example by updating some values or modifying its behavior.
* Subscribe for configuration changes by calling the md_config_t::add_observer() method
* and unsubscribe using md_config_t::remove_observer().
*/
template<class ConfigProxy>
class md_config_obs_impl {
public:
virtual ~md_config_obs_impl() {}
/** @brief Get a table of strings specifying the configuration keys in which the object is interested.
* This is called when the object is subscribed to configuration changes with add_observer().
* The returned table should not be freed until the observer is removed with remove_observer().
* Note that it is not possible to change the set of tracked keys without re-subscribing. */
virtual const char** get_tracked_conf_keys() const = 0;
/// React to a configuration change.
virtual void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) = 0;
/// Unused for now
virtual void handle_subsys_change(const ConfigProxy& conf,
const std::set<int>& changed) { }
};
}
using md_config_obs_t = ceph::md_config_obs_impl<ConfigProxy>;
#endif
| 1,819 | 34.686275 | 104 | h |
null | ceph-main/src/common/config_obs_mgr.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#pragma once
#include <map>
#include <set>
#include <string>
#include "common/config_tracker.h"
class ConfigValues;
// @c ObserverMgr manages a set of config observers which are interested in
// the changes of settings at runtime.
template<class ConfigObs>
class ObserverMgr : public ConfigTracker {
// Maps configuration options to the observer listening for them.
using obs_map_t = std::multimap<std::string, ConfigObs*>;
obs_map_t observers;
public:
typedef std::map<ConfigObs*, std::set<std::string>> rev_obs_map;
typedef std::function<void(ConfigObs*, const std::string&)> config_gather_cb;
// Adds a new observer to this configuration. You can do this at any time,
// but it will only receive notifications for the changes that happen after
// you attach it, obviously.
//
// Most developers will probably attach their observers after global_init,
// but before anyone can call injectargs.
//
// The caller is responsible for allocating observers.
void add_observer(ConfigObs* observer);
// Remove an observer from this configuration.
// This doesn't delete the observer! If you allocated it with new(),
// you need to delete it yourself.
// This function will assert if you try to delete an observer that isn't
// there.
void remove_observer(ConfigObs* observer);
// invoke callback for every observers tracking keys
void for_each_observer(config_gather_cb callback);
// invoke callback for observers keys tracking the provided change set
template<class ConfigProxyT>
void for_each_change(const std::set<std::string>& changes,
ConfigProxyT& proxy,
config_gather_cb callback, std::ostream *oss);
bool is_tracking(const std::string& name) const override;
};
// we could put the implementations in a .cc file, and only instantiate the
// used template specializations explicitly, but that forces us to involve
// unused headers and libraries at compile-time. for instance, for instantiate,
// to instantiate ObserverMgr for seastar, we will need to include seastar
// headers to get the necessary types in place, but that would force us to link
// the non-seastar binaries against seastar libraries. so, to avoid pulling
// in unused dependencies at the expense of increasing compiling time, we put
// the implementation in the header file.
template<class ConfigObs>
void ObserverMgr<ConfigObs>::add_observer(ConfigObs* observer)
{
const char **keys = observer->get_tracked_conf_keys();
for (const char ** k = keys; *k; ++k) {
observers.emplace(*k, observer);
}
}
template<class ConfigObs>
void ObserverMgr<ConfigObs>::remove_observer(ConfigObs* observer)
{
[[maybe_unused]] bool found_obs = false;
for (auto o = observers.begin(); o != observers.end(); ) {
if (o->second == observer) {
observers.erase(o++);
found_obs = true;
} else {
++o;
}
}
ceph_assert(found_obs);
}
template<class ConfigObs>
void ObserverMgr<ConfigObs>::for_each_observer(config_gather_cb callback)
{
for (const auto& [key, obs] : observers) {
callback(obs, key);
}
}
template<class ConfigObs>
template<class ConfigProxyT>
void ObserverMgr<ConfigObs>::for_each_change(const std::set<std::string>& changes,
ConfigProxyT& proxy,
config_gather_cb callback, std::ostream *oss)
{
// create the reverse observer mapping, mapping observers to the set of
// changed keys that they'll get.
std::string val;
for (auto& key : changes) {
auto [first, last] = observers.equal_range(key);
if ((oss) && !proxy.get_val(key, &val)) {
(*oss) << key << " = '" << val << "' ";
if (first == last) {
(*oss) << "(not observed, change may require restart) ";
}
}
for (auto r = first; r != last; ++r) {
callback(r->second, key);
}
}
}
template<class ConfigObs>
bool ObserverMgr<ConfigObs>::is_tracking(const std::string& name) const
{
return observers.count(name) > 0;
}
| 4,114 | 33.579832 | 90 | h |
null | ceph-main/src/common/config_proxy.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#pragma once
#include <type_traits>
#include "common/config.h"
#include "common/config_obs.h"
#include "common/config_obs_mgr.h"
#include "common/ceph_mutex.h"
// @c ConfigProxy is a facade of multiple config related classes. it exposes
// the legacy settings with arrow operator, and the new-style config with its
// member methods.
namespace ceph::common {
class ConfigProxy {
/**
* The current values of all settings described by the schema
*/
ConfigValues values;
using md_config_obs_t = ceph::md_config_obs_impl<ConfigProxy>;
ObserverMgr<md_config_obs_t> obs_mgr;
md_config_t config;
/** A lock that protects the md_config_t internals. It is
* recursive, for simplicity.
* It is best if this lock comes first in the lock hierarchy. We will
* hold this lock when calling configuration observers. */
mutable ceph::recursive_mutex lock =
ceph::make_recursive_mutex("ConfigProxy::lock");
class CallGate {
private:
uint32_t call_count = 0;
ceph::mutex lock;
ceph::condition_variable cond;
public:
CallGate()
: lock(ceph::make_mutex("call::gate::lock")) {
}
void enter() {
std::lock_guard<ceph::mutex> locker(lock);
++call_count;
}
void leave() {
std::lock_guard<ceph::mutex> locker(lock);
ceph_assert(call_count > 0);
if (--call_count == 0) {
cond.notify_all();
}
}
void close() {
std::unique_lock<ceph::mutex> locker(lock);
while (call_count != 0) {
cond.wait(locker);
}
}
};
void call_gate_enter(md_config_obs_t *obs) {
auto p = obs_call_gate.find(obs);
ceph_assert(p != obs_call_gate.end());
p->second->enter();
}
void call_gate_leave(md_config_obs_t *obs) {
auto p = obs_call_gate.find(obs);
ceph_assert(p != obs_call_gate.end());
p->second->leave();
}
void call_gate_close(md_config_obs_t *obs) {
auto p = obs_call_gate.find(obs);
ceph_assert(p != obs_call_gate.end());
p->second->close();
}
using rev_obs_map_t = ObserverMgr<md_config_obs_t>::rev_obs_map;
typedef std::unique_ptr<CallGate> CallGateRef;
std::map<md_config_obs_t*, CallGateRef> obs_call_gate;
void call_observers(std::unique_lock<ceph::recursive_mutex>& locker,
rev_obs_map_t& rev_obs) {
// observers are notified outside of lock
locker.unlock();
for (auto& [obs, keys] : rev_obs) {
obs->handle_conf_change(*this, keys);
}
locker.lock();
for (auto& rev_ob : rev_obs) {
call_gate_leave(rev_ob.first);
}
}
void map_observer_changes(md_config_obs_t *obs, const std::string &key,
rev_obs_map_t *rev_obs) {
ceph_assert(ceph_mutex_is_locked(lock));
auto [it, new_entry] = rev_obs->emplace(obs, std::set<std::string>{});
it->second.emplace(key);
if (new_entry) {
// this needs to be done under lock as once this lock is
// dropped (before calling observers) a remove_observer()
// can sneak in and cause havoc.
call_gate_enter(obs);
}
}
public:
explicit ConfigProxy(bool is_daemon)
: config{values, obs_mgr, is_daemon}
{}
ConfigProxy(const ConfigProxy &config_proxy)
: values(config_proxy.get_config_values()),
config{values, obs_mgr, config_proxy.config.is_daemon}
{}
const ConfigValues* operator->() const noexcept {
return &values;
}
ConfigValues* operator->() noexcept {
return &values;
}
ConfigValues get_config_values() const {
std::lock_guard l{lock};
return values;
}
void set_config_values(const ConfigValues& val) {
#ifndef WITH_SEASTAR
std::lock_guard l{lock};
#endif
values = val;
}
int get_val(const std::string_view key, char** buf, int len) const {
std::lock_guard l{lock};
return config.get_val(values, key, buf, len);
}
int get_val(const std::string_view key, std::string *val) const {
std::lock_guard l{lock};
return config.get_val(values, key, val);
}
template<typename T>
const T get_val(const std::string_view key) const {
std::lock_guard l{lock};
return config.template get_val<T>(values, key);
}
template<typename T, typename Callback, typename...Args>
auto with_val(const std::string_view key, Callback&& cb, Args&&... args) const {
std::lock_guard l{lock};
return config.template with_val<T>(values, key,
std::forward<Callback>(cb),
std::forward<Args>(args)...);
}
void config_options(ceph::Formatter *f) const {
config.config_options(f);
}
const decltype(md_config_t::schema)& get_schema() const {
return config.schema;
}
const Option* get_schema(const std::string_view key) const {
auto found = config.schema.find(key);
if (found == config.schema.end()) {
return nullptr;
} else {
return &found->second;
}
}
const Option *find_option(const std::string& name) const {
return config.find_option(name);
}
void diff(ceph::Formatter *f, const std::string& name = {}) const {
std::lock_guard l{lock};
return config.diff(values, f, name);
}
std::vector<std::string> get_my_sections() const {
std::lock_guard l{lock};
return config.get_my_sections(values);
}
int get_all_sections(std::vector<std::string>& sections) const {
std::lock_guard l{lock};
return config.get_all_sections(sections);
}
int get_val_from_conf_file(const std::vector<std::string>& sections,
const std::string_view key, std::string& out,
bool emeta) const {
std::lock_guard l{lock};
return config.get_val_from_conf_file(values,
sections, key, out, emeta);
}
unsigned get_osd_pool_default_min_size(uint8_t size) const {
return config.get_osd_pool_default_min_size(values, size);
}
void early_expand_meta(std::string &val,
std::ostream *oss) const {
std::lock_guard l{lock};
return config.early_expand_meta(values, val, oss);
}
// for those want to reexpand special meta, e.g, $pid
void finalize_reexpand_meta() {
std::unique_lock locker(lock);
rev_obs_map_t rev_obs;
if (config.finalize_reexpand_meta(values, obs_mgr)) {
_gather_changes(values.changed, &rev_obs, nullptr);
}
call_observers(locker, rev_obs);
}
void add_observer(md_config_obs_t* obs) {
std::lock_guard l(lock);
obs_mgr.add_observer(obs);
obs_call_gate.emplace(obs, std::make_unique<CallGate>());
}
void remove_observer(md_config_obs_t* obs) {
std::lock_guard l(lock);
call_gate_close(obs);
obs_call_gate.erase(obs);
obs_mgr.remove_observer(obs);
}
void call_all_observers() {
std::unique_lock locker(lock);
rev_obs_map_t rev_obs;
obs_mgr.for_each_observer(
[this, &rev_obs](md_config_obs_t *obs, const std::string &key) {
map_observer_changes(obs, key, &rev_obs);
});
call_observers(locker, rev_obs);
}
void set_safe_to_start_threads() {
config.set_safe_to_start_threads();
}
void _clear_safe_to_start_threads() {
config._clear_safe_to_start_threads();
}
void show_config(std::ostream& out) {
std::lock_guard l{lock};
config.show_config(values, out);
}
void show_config(ceph::Formatter *f) {
std::lock_guard l{lock};
config.show_config(values, f);
}
void config_options(ceph::Formatter *f) {
std::lock_guard l{lock};
config.config_options(f);
}
int rm_val(const std::string_view key) {
std::lock_guard l{lock};
return config.rm_val(values, key);
}
// Expand all metavariables. Make any pending observer callbacks.
void apply_changes(std::ostream* oss) {
std::unique_lock locker(lock);
rev_obs_map_t rev_obs;
// apply changes until the cluster name is assigned
if (!values.cluster.empty()) {
// meta expands could have modified anything. Copy it all out again.
_gather_changes(values.changed, &rev_obs, oss);
}
call_observers(locker, rev_obs);
}
void _gather_changes(std::set<std::string> &changes,
rev_obs_map_t *rev_obs, std::ostream* oss) {
obs_mgr.for_each_change(
changes, *this,
[this, rev_obs](md_config_obs_t *obs, const std::string &key) {
map_observer_changes(obs, key, rev_obs);
}, oss);
changes.clear();
}
int set_val(const std::string_view key, const std::string& s,
std::stringstream* err_ss=nullptr) {
std::lock_guard l{lock};
return config.set_val(values, obs_mgr, key, s, err_ss);
}
void set_val_default(const std::string_view key, const std::string& val) {
std::lock_guard l{lock};
config.set_val_default(values, obs_mgr, key, val);
}
void set_val_or_die(const std::string_view key, const std::string& val) {
std::lock_guard l{lock};
config.set_val_or_die(values, obs_mgr, key, val);
}
int set_mon_vals(CephContext *cct,
const std::map<std::string,std::string,std::less<>>& kv,
md_config_t::config_callback config_cb) {
std::unique_lock locker(lock);
int ret = config.set_mon_vals(cct, values, obs_mgr, kv, config_cb);
rev_obs_map_t rev_obs;
_gather_changes(values.changed, &rev_obs, nullptr);
call_observers(locker, rev_obs);
return ret;
}
int injectargs(const std::string &s, std::ostream *oss) {
std::unique_lock locker(lock);
int ret = config.injectargs(values, obs_mgr, s, oss);
rev_obs_map_t rev_obs;
_gather_changes(values.changed, &rev_obs, oss);
call_observers(locker, rev_obs);
return ret;
}
void parse_env(unsigned entity_type,
const char *env_var = "CEPH_ARGS") {
std::lock_guard l{lock};
config.parse_env(entity_type, values, obs_mgr, env_var);
}
int parse_argv(std::vector<const char*>& args, int level=CONF_CMDLINE) {
std::lock_guard l{lock};
return config.parse_argv(values, obs_mgr, args, level);
}
int parse_config_files(const char *conf_files,
std::ostream *warnings, int flags) {
std::lock_guard l{lock};
return config.parse_config_files(values, obs_mgr,
conf_files, warnings, flags);
}
bool has_parse_error() const {
return !config.parse_error.empty();
}
std::string get_parse_error() {
return config.parse_error;
}
void complain_about_parse_error(CephContext *cct) {
return config.complain_about_parse_error(cct);
}
void do_argv_commands() const {
std::lock_guard l{lock};
config.do_argv_commands(values);
}
void get_config_bl(uint64_t have_version,
ceph::buffer::list *bl,
uint64_t *got_version) {
std::lock_guard l{lock};
config.get_config_bl(values, have_version, bl, got_version);
}
void get_defaults_bl(ceph::buffer::list *bl) {
std::lock_guard l{lock};
config.get_defaults_bl(values, bl);
}
const std::string& get_conf_path() const {
return config.get_conf_path();
}
std::optional<std::string> get_val_default(std::string_view key) {
return config.get_val_default(key);
}
};
}
| 11,013 | 30.201133 | 82 | h |
null | ceph-main/src/common/config_tracker.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#pragma once
#include <string>
// @ConfigTracker is queried to see if any added observers is tracking one or
// more changed settings.
//
// this class is introduced in hope to decouple @c md_config_t from any instantiated
// class of @c ObserverMgr, as what the former wants is but @c is_tracking(), and to
// make ObserverMgr a template parameter of md_config_t's methods just complicates
// the dependencies between header files, and slows down the compiling.
class ConfigTracker {
public:
virtual ~ConfigTracker() = default;
virtual bool is_tracking(const std::string& name) const = 0;
};
| 671 | 34.368421 | 84 | h |
null | ceph-main/src/common/config_values.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#include "config_values.h"
#include "config.h"
#if WITH_SEASTAR
#include "crimson/common/log.h"
#endif
ConfigValues::set_value_result_t
ConfigValues::set_value(const std::string_view key,
Option::value_t&& new_value,
int level)
{
if (auto p = values.find(key); p != values.end()) {
auto q = p->second.find(level);
if (q != p->second.end()) {
if (new_value == q->second) {
return SET_NO_CHANGE;
}
q->second = std::move(new_value);
} else {
p->second[level] = std::move(new_value);
}
if (p->second.rbegin()->first > level) {
// there was a higher priority value; no effect
return SET_NO_EFFECT;
} else {
return SET_HAVE_EFFECT;
}
} else {
values[key][level] = std::move(new_value);
return SET_HAVE_EFFECT;
}
}
int ConfigValues::rm_val(const std::string_view key, int level)
{
auto i = values.find(key);
if (i == values.end()) {
return -ENOENT;
}
auto j = i->second.find(level);
if (j == i->second.end()) {
return -ENOENT;
}
bool matters = (j->first == i->second.rbegin()->first);
i->second.erase(j);
if (matters) {
return SET_HAVE_EFFECT;
} else {
return SET_NO_EFFECT;
}
}
std::pair<Option::value_t, bool>
ConfigValues::get_value(const std::string_view name, int level) const
{
auto p = values.find(name);
if (p != values.end() && !p->second.empty()) {
// use highest-priority value available (see CONF_*)
if (level < 0) {
return {p->second.rbegin()->second, true};
} else if (auto found = p->second.find(level);
found != p->second.end()) {
return {found->second, true};
}
}
return {Option::value_t{}, false};
}
void ConfigValues::set_logging(int which, const char* val)
{
int log, gather;
int r = sscanf(val, "%d/%d", &log, &gather);
if (r >= 1) {
if (r < 2) {
gather = log;
}
subsys.set_log_level(which, log);
subsys.set_gather_level(which, gather);
#if WITH_SEASTAR
crimson::get_logger(which).set_level(crimson::to_log_level(log));
#endif
}
}
bool ConfigValues::contains(const std::string_view key) const
{
return values.count(key);
}
| 2,281 | 24.076923 | 70 | cc |
null | ceph-main/src/common/config_values.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#pragma once
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <utility>
#include "common/entity_name.h"
#include "common/options.h"
#include "log/SubsystemMap.h"
#include "msg/msg_types.h"
// @c ConfigValues keeps track of mappings from the config names to their values,
// debug logging settings, and some other "unnamed" settings, like entity name of
// the daemon.
class ConfigValues {
using values_t = std::map<std::string_view, std::map<int32_t,Option::value_t>>;
values_t values;
// for populating md_config_impl::legacy_values in ctor
friend struct md_config_t;
public:
EntityName name;
/// cluster name
std::string cluster;
ceph::logging::SubsystemMap subsys;
bool no_mon_config = false;
// Set of configuration options that have changed since the last
// apply_changes
using changed_set_t = std::set<std::string>;
changed_set_t changed;
// This macro block defines C members of the md_config_t struct
// corresponding to the definitions in legacy_config_opts.h.
// These C members are consumed by code that was written before
// the new options.cc infrastructure: all newer code should
// be consume options via explicit get() rather than C members.
#define OPTION_OPT_INT(name) int64_t name;
#define OPTION_OPT_LONGLONG(name) int64_t name;
#define OPTION_OPT_STR(name) std::string name;
#define OPTION_OPT_DOUBLE(name) double name;
#define OPTION_OPT_FLOAT(name) double name;
#define OPTION_OPT_BOOL(name) bool name;
#define OPTION_OPT_ADDR(name) entity_addr_t name;
#define OPTION_OPT_ADDRVEC(name) entity_addrvec_t name;
#define OPTION_OPT_U32(name) uint64_t name;
#define OPTION_OPT_U64(name) uint64_t name;
#define OPTION_OPT_UUID(name) uuid_d name;
#define OPTION_OPT_SIZE(name) uint64_t name;
#define OPTION(name, ty) \
public: \
OPTION_##ty(name)
#define SAFE_OPTION(name, ty) \
protected: \
OPTION_##ty(name)
#include "common/options/legacy_config_opts.h"
#undef OPTION_OPT_INT
#undef OPTION_OPT_LONGLONG
#undef OPTION_OPT_STR
#undef OPTION_OPT_DOUBLE
#undef OPTION_OPT_FLOAT
#undef OPTION_OPT_BOOL
#undef OPTION_OPT_ADDR
#undef OPTION_OPT_ADDRVEC
#undef OPTION_OPT_U32
#undef OPTION_OPT_U64
#undef OPTION_OPT_UUID
#undef OPTION
#undef SAFE_OPTION
public:
enum set_value_result_t {
SET_NO_CHANGE,
SET_NO_EFFECT,
SET_HAVE_EFFECT,
};
/**
* @return true if changed, false otherwise
*/
set_value_result_t set_value(std::string_view key,
Option::value_t&& value,
int level);
int rm_val(const std::string_view key, int level);
void set_logging(int which, const char* val);
/**
* @param level the level of the setting, -1 for the one with the
* highest-priority
*/
std::pair<Option::value_t, bool> get_value(const std::string_view name,
int level) const;
template<typename Func> void for_each(Func&& func) const {
for (const auto& [name,configs] : values) {
func(name, configs);
}
}
bool contains(const std::string_view key) const;
};
| 3,254 | 31.227723 | 81 | h |
null | ceph-main/src/common/containers.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_COMMON_CONTAINERS_H
#define CEPH_COMMON_CONTAINERS_H
#include <cstdint>
#include <type_traits>
namespace ceph::containers {
// tiny_vector – CPU friendly, small_vector-like container for mutexes,
// atomics and other non-movable things.
//
// The purpose of the container is to store arbitrary number of objects
// with absolutely minimal requirements regarding constructibility
// and assignability while minimizing memory indirection.
// There is no obligation for MoveConstructibility, CopyConstructibility,
// MoveAssignability, CopyAssignability nor even DefaultConstructibility
// which allows to handle std::mutexes, std::atomics or any type embedding
// them.
//
// Few requirements translate into tiny interface. The container isn't
// Copy- nor MoveConstructible. Although it does offer random access
// iterator, insertion in the middle is not allowed. The maximum number
// of elements must be known at run-time. This shouldn't be an issue in
// the intended use case: sharding.
//
// For the special case of no internal slots (InternalCapacity eq 0),
// tiny_vector doesn't require moving any elements (changing pointers
// is enough), and thus should be MoveConstructibile.
//
// Alternatives:
// 1. std::vector<boost::optional<ValueT>> initialized with the known
// size and emplace_backed(). boost::optional inside provides
// the DefaultConstructibility. Imposes extra memory indirection.
// 2. boost::container::small_vector + boost::optional always
// requires MoveConstructibility.
// 3. boost::container::static_vector feed via emplace_back().
// Good for performance but enforces upper limit on elements count.
// For sharding this means we can't handle arbitrary number of
// shards (weird configs).
// 4. std::unique_ptr<ValueT>: extra indirection together with memory
// fragmentation.
template<typename Value, std::size_t InternalCapacity = 0>
class tiny_vector {
// NOTE: to avoid false sharing consider aligning to cache line
using storage_unit_t = \
std::aligned_storage_t<sizeof(Value), alignof(Value)>;
std::size_t _size = 0;
storage_unit_t* const data = nullptr;
storage_unit_t internal[InternalCapacity];
public:
typedef std::size_t size_type;
typedef std::add_lvalue_reference_t<Value> reference;
typedef std::add_const_t<reference> const_reference;
typedef std::add_pointer_t<Value> pointer;
// emplacer is the piece of weirdness that comes from handling
// unmovable-and-uncopyable things. The only way to instantiate
// such types I know is to create instances in-place perfectly
// forwarding necessary data to constructor.
// Abstracting that is the exact purpose of emplacer.
//
// The usage scenario is:
// 1. The tiny_vector's ctor is provided with a) maximum number
// of instances and b) a callable taking emplacer.
// 2. The callable can (but isn't obliged to!) use emplacer to
// construct an instance without knowing at which address
// in memory it will be put. Callable is also supplied with
// an unique integer from the range <0, maximum number of
// instances).
// 3. If callable decides to instantiate, it calls ::emplace
// of emplacer passing all arguments required by the type
// hold in tiny_vector.
//
// Example:
// ```
// static constexpr const num_internally_allocated_slots = 32;
// tiny_vector<T, num_internally_allocated_slots> mytinyvec {
// num_of_instances,
// [](const size_t i, auto emplacer) {
// emplacer.emplace(argument_for_T_ctor);
// }
// }
// ```
//
// For the sake of supporting the ceph::make_mutex() family of
// factories, which relies on C++17's guaranteed copy elision,
// the emplacer provides `data()` to retrieve the location for
// constructing the instance with placement-new. This is handy
// as the `emplace()` depends on perfect forwarding, and thus
// interfere with the elision for cases like:
// ```
// emplacer.emplace(ceph::make_mutex("mtx-name"));
// ```
// See: https://stackoverflow.com/a/52498826
class emplacer {
friend class tiny_vector;
tiny_vector* parent;
emplacer(tiny_vector* const parent)
: parent(parent) {
}
public:
void* data() {
void* const ret = &parent->data[parent->_size++];
parent = nullptr;
return ret;
}
template<class... Args>
void emplace(Args&&... args) {
if (parent) {
new (data()) Value(std::forward<Args>(args)...);
}
}
};
template<typename F>
tiny_vector(const std::size_t count, F&& f)
: data(count <= InternalCapacity ? internal
: new storage_unit_t[count]) {
for (std::size_t i = 0; i < count; ++i) {
// caller MAY emplace up to `count` elements but it IS NOT
// obliged to do so. The emplacer guarantees that the limit
// will never be exceeded.
f(i, emplacer(this));
}
}
~tiny_vector() {
for (auto& elem : *this) {
elem.~Value();
}
const auto data_addr = reinterpret_cast<std::uintptr_t>(data);
const auto this_addr = reinterpret_cast<std::uintptr_t>(this);
if (data_addr < this_addr ||
data_addr >= this_addr + sizeof(*this)) {
delete[] data;
}
}
reference operator[](size_type pos) {
return reinterpret_cast<reference>(data[pos]);
}
const_reference operator[](size_type pos) const {
return reinterpret_cast<const_reference>(data[pos]);
}
size_type size() const {
return _size;
}
pointer begin() {
return reinterpret_cast<pointer>(&data[0]);
}
pointer end() {
return reinterpret_cast<pointer>(&data[_size]);
}
const pointer begin() const {
return reinterpret_cast<pointer>(&data[0]);
}
const pointer end() const {
return reinterpret_cast<pointer>(&data[_size]);
}
const pointer cbegin() const {
return reinterpret_cast<pointer>(&data[0]);
}
const pointer cend() const {
return reinterpret_cast<pointer>(&data[_size]);
}
};
} // namespace ceph::containers
#endif // CEPH_COMMON_CONTAINERS_H
| 6,547 | 32.408163 | 74 | h |
null | ceph-main/src/common/convenience.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.
*
*/
#include <mutex>
#include <memory>
#include <optional>
#include <shared_mutex>
#include <type_traits>
#include <utility>
#include <boost/optional.hpp>
#ifndef CEPH_COMMON_CONVENIENCE_H
#define CEPH_COMMON_CONVENIENCE_H
namespace ceph {
// boost::optional is wonderful! Unfortunately it lacks a function for
// the thing you would most obviously want to do with it: apply a
// function to its contents.
// There are two obvious candidates. The first is a function that
// takes a function and an optional value and returns an optional
// value, either holding the return value of the function or holding
// nothing.
//
// I'd considered making more overloads for mutable lvalue
// references, but those are going a bit beyond likely use cases.
//
template<typename T, typename F>
auto maybe_do(const boost::optional<T>& t, F&& f) ->
boost::optional<std::result_of_t<F(const std::decay_t<T>)>>
{
if (t)
return { std::forward<F>(f)(*t) };
else
return boost::none;
}
// The other obvious function takes an optional but returns an
// ‘unwrapped’ value, either the result of evaluating the function or
// a provided alternate value.
//
template<typename T, typename F, typename U>
auto maybe_do_or(const boost::optional<T>& t, F&& f, U&& u) ->
std::result_of_t<F(const std::decay_t<T>)>
{
static_assert(std::is_convertible_v<U, std::result_of_t<F(T)>>,
"Alternate value must be convertible to function return type.");
if (t)
return std::forward<F>(f)(*t);
else
return std::forward<U>(u);
}
// Same thing but for std::optional
template<typename T, typename F>
auto maybe_do(const std::optional<T>& t, F&& f) ->
std::optional<std::result_of_t<F(const std::decay_t<T>)>>
{
if (t)
return { std::forward<F>(f)(*t) };
else
return std::nullopt;
}
// The other obvious function takes an optional but returns an
// ‘unwrapped’ value, either the result of evaluating the function or
// a provided alternate value.
//
template<typename T, typename F, typename U>
auto maybe_do_or(const std::optional<T>& t, F&& f, U&& u) ->
std::result_of_t<F(const std::decay_t<T>)>
{
static_assert(std::is_convertible_v<U, std::result_of_t<F(T)>>,
"Alternate value must be convertible to function return type.");
if (t)
return std::forward<F>(f)(*t);
else
return std::forward<U>(u);
}
namespace _convenience {
template<typename... Ts, typename F, std::size_t... Is>
inline void for_each_helper(const std::tuple<Ts...>& t, const F& f,
std::index_sequence<Is...>) {
(f(std::get<Is>(t)), ..., void());
}
template<typename... Ts, typename F, std::size_t... Is>
inline void for_each_helper(std::tuple<Ts...>& t, const F& f,
std::index_sequence<Is...>) {
(f(std::get<Is>(t)), ..., void());
}
template<typename... Ts, typename F, std::size_t... Is>
inline void for_each_helper(const std::tuple<Ts...>& t, F& f,
std::index_sequence<Is...>) {
(f(std::get<Is>(t)), ..., void());
}
template<typename... Ts, typename F, std::size_t... Is>
inline void for_each_helper(std::tuple<Ts...>& t, F& f,
std::index_sequence<Is...>) {
(f(std::get<Is>(t)), ..., void());
}
}
template<typename... Ts, typename F>
inline void for_each(const std::tuple<Ts...>& t, const F& f) {
_convenience::for_each_helper(t, f, std::index_sequence_for<Ts...>{});
}
template<typename... Ts, typename F>
inline void for_each(std::tuple<Ts...>& t, const F& f) {
_convenience::for_each_helper(t, f, std::index_sequence_for<Ts...>{});
}
template<typename... Ts, typename F>
inline void for_each(const std::tuple<Ts...>& t, F& f) {
_convenience::for_each_helper(t, f, std::index_sequence_for<Ts...>{});
}
template<typename... Ts, typename F>
inline void for_each(std::tuple<Ts...>& t, F& f) {
_convenience::for_each_helper(t, f, std::index_sequence_for<Ts...>{});
}
}
#endif // CEPH_COMMON_CONVENIENCE_H
| 4,276 | 30.448529 | 72 | h |
null | ceph-main/src/common/crc32c.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "include/crc32c.h"
#include "arch/probe.h"
#include "arch/intel.h"
#include "arch/arm.h"
#include "arch/ppc.h"
#include "common/sctp_crc32.h"
#include "common/crc32c_intel_fast.h"
#include "common/crc32c_aarch64.h"
#include "common/crc32c_ppc.h"
/*
* choose best implementation based on the CPU architecture.
*/
ceph_crc32c_func_t ceph_choose_crc32(void)
{
// make sure we've probed cpu features; this might depend on the
// link order of this file relative to arch/probe.cc.
ceph_arch_probe();
// if the CPU supports it, *and* the fast version is compiled in,
// use that.
#if defined(__i386__) || defined(__x86_64__)
if (ceph_arch_intel_sse42 && ceph_crc32c_intel_fast_exists()) {
return ceph_crc32c_intel_fast;
}
#elif defined(__arm__) || defined(__aarch64__)
# if defined(HAVE_ARMV8_CRC)
if (ceph_arch_aarch64_crc32){
return ceph_crc32c_aarch64;
}
# endif
#elif defined(__powerpc__) || defined(__ppc__)
if (ceph_arch_ppc_crc32) {
return ceph_crc32c_ppc;
}
#endif
// default
return ceph_crc32c_sctp;
}
/*
* static global
*
* This is a bit of a no-no for shared libraries, but we don't care.
* It is effectively constant for the executing process as the value
* depends on the CPU architecture.
*
* We initialize it during program init using the magic of C++.
*/
ceph_crc32c_func_t ceph_crc32c_func = ceph_choose_crc32();
/*
* Look: http://crcutil.googlecode.com/files/crc-doc.1.0.pdf
* Here is implementation that goes 1 logical step further,
* it splits calculating CRC into jumps of length 1, 2, 4, 8, ....
* Each jump is performed on single input bit separately, xor-ed after that.
*
* This function is unused. It is here to show how crc_turbo_table was obtained.
*/
void create_turbo_table(uint32_t table[32][32])
{
//crc_turbo_struct table;
for (int bit = 0 ; bit < 32 ; bit++) {
table[0][bit] = ceph_crc32c_sctp(1UL << bit, nullptr, 1);
}
for (int range = 1; range <32 ; range++) {
for (int bit = 0 ; bit < 32 ; bit++) {
uint32_t crc_x = table[range-1][bit];
uint32_t crc_y = 0;
for (int b = 0 ; b < 32 ; b++) {
if ( (crc_x & (1UL << b)) != 0 ) {
crc_y = crc_y ^ table[range-1][b];
}
}
table[range][bit] = crc_y;
}
}
}
static uint32_t crc_turbo_table[32][32] =
{
{0xf26b8303, 0xe13b70f7, 0xc79a971f, 0x8ad958cf, 0x105ec76f, 0x20bd8ede, 0x417b1dbc, 0x82f63b78,
0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080,
0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000,
0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000},
{0x13a29877, 0x274530ee, 0x4e8a61dc, 0x9d14c3b8, 0x3fc5f181, 0x7f8be302, 0xff17c604, 0xfbc3faf9,
0xf26b8303, 0xe13b70f7, 0xc79a971f, 0x8ad958cf, 0x105ec76f, 0x20bd8ede, 0x417b1dbc, 0x82f63b78,
0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080,
0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000},
{0xdd45aab8, 0xbf672381, 0x7b2231f3, 0xf64463e6, 0xe964b13d, 0xd725148b, 0xaba65fe7, 0x52a0c93f,
0xa541927e, 0x4f6f520d, 0x9edea41a, 0x38513ec5, 0x70a27d8a, 0xe144fb14, 0xc76580d9, 0x8b277743,
0x13a29877, 0x274530ee, 0x4e8a61dc, 0x9d14c3b8, 0x3fc5f181, 0x7f8be302, 0xff17c604, 0xfbc3faf9,
0xf26b8303, 0xe13b70f7, 0xc79a971f, 0x8ad958cf, 0x105ec76f, 0x20bd8ede, 0x417b1dbc, 0x82f63b78},
{0x493c7d27, 0x9278fa4e, 0x211d826d, 0x423b04da, 0x847609b4, 0x0d006599, 0x1a00cb32, 0x34019664,
0x68032cc8, 0xd0065990, 0xa5e0c5d1, 0x4e2dfd53, 0x9c5bfaa6, 0x3d5b83bd, 0x7ab7077a, 0xf56e0ef4,
0xef306b19, 0xdb8ca0c3, 0xb2f53777, 0x6006181f, 0xc00c303e, 0x85f4168d, 0x0e045beb, 0x1c08b7d6,
0x38116fac, 0x7022df58, 0xe045beb0, 0xc5670b91, 0x8f2261d3, 0x1ba8b557, 0x37516aae, 0x6ea2d55c},
{0xf20c0dfe, 0xe1f46d0d, 0xc604aceb, 0x89e52f27, 0x162628bf, 0x2c4c517e, 0x5898a2fc, 0xb13145f8,
0x678efd01, 0xcf1dfa02, 0x9bd782f5, 0x3243731b, 0x6486e636, 0xc90dcc6c, 0x97f7ee29, 0x2a03aaa3,
0x54075546, 0xa80eaa8c, 0x55f123e9, 0xabe247d2, 0x5228f955, 0xa451f2aa, 0x4d4f93a5, 0x9a9f274a,
0x30d23865, 0x61a470ca, 0xc348e194, 0x837db5d9, 0x03171d43, 0x062e3a86, 0x0c5c750c, 0x18b8ea18},
{0x3da6d0cb, 0x7b4da196, 0xf69b432c, 0xe8daf0a9, 0xd45997a3, 0xad5f59b7, 0x5f52c59f, 0xbea58b3e,
0x78a7608d, 0xf14ec11a, 0xe771f4c5, 0xcb0f9f7b, 0x93f34807, 0x220ae6ff, 0x4415cdfe, 0x882b9bfc,
0x15bb4109, 0x2b768212, 0x56ed0424, 0xadda0848, 0x5e586661, 0xbcb0ccc2, 0x7c8def75, 0xf91bdeea,
0xf7dbcb25, 0xea5be0bb, 0xd15bb787, 0xa75b19ff, 0x4b5a450f, 0x96b48a1e, 0x288562cd, 0x510ac59a},
{0x740eef02, 0xe81dde04, 0xd5d7caf9, 0xae43e303, 0x596bb0f7, 0xb2d761ee, 0x6042b52d, 0xc0856a5a,
0x84e6a245, 0x0c21327b, 0x184264f6, 0x3084c9ec, 0x610993d8, 0xc21327b0, 0x81ca3991, 0x067805d3,
0x0cf00ba6, 0x19e0174c, 0x33c02e98, 0x67805d30, 0xcf00ba60, 0x9bed0231, 0x32367293, 0x646ce526,
0xc8d9ca4c, 0x945fe269, 0x2d53b223, 0x5aa76446, 0xb54ec88c, 0x6f71e7e9, 0xdee3cfd2, 0xb82be955},
{0x6992cea2, 0xd3259d44, 0xa3a74c79, 0x42a2ee03, 0x8545dc06, 0x0f67cefd, 0x1ecf9dfa, 0x3d9f3bf4,
0x7b3e77e8, 0xf67cefd0, 0xe915a951, 0xd7c72453, 0xaa623e57, 0x51280a5f, 0xa25014be, 0x414c5f8d,
0x8298bf1a, 0x00dd08c5, 0x01ba118a, 0x03742314, 0x06e84628, 0x0dd08c50, 0x1ba118a0, 0x37423140,
0x6e846280, 0xdd08c500, 0xbffdfcf1, 0x7a178f13, 0xf42f1e26, 0xedb24abd, 0xde88e38b, 0xb8fdb1e7},
{0xdcb17aa4, 0xbc8e83b9, 0x7cf17183, 0xf9e2e306, 0xf629b0fd, 0xe9bf170b, 0xd69258e7, 0xa8c8c73f,
0x547df88f, 0xa8fbf11e, 0x541b94cd, 0xa837299a, 0x558225c5, 0xab044b8a, 0x53e4e1e5, 0xa7c9c3ca,
0x4a7ff165, 0x94ffe2ca, 0x2c13b365, 0x582766ca, 0xb04ecd94, 0x6571edd9, 0xcae3dbb2, 0x902bc195,
0x25bbf5db, 0x4b77ebb6, 0x96efd76c, 0x2833d829, 0x5067b052, 0xa0cf60a4, 0x4472b7b9, 0x88e56f72},
{0xbd6f81f8, 0x7f337501, 0xfe66ea02, 0xf921a2f5, 0xf7af331b, 0xeab210c7, 0xd088577f, 0xa4fcd80f,
0x4c15c6ef, 0x982b8dde, 0x35bb6d4d, 0x6b76da9a, 0xd6edb534, 0xa8371c99, 0x55824fc3, 0xab049f86,
0x53e549fd, 0xa7ca93fa, 0x4a795105, 0x94f2a20a, 0x2c0932e5, 0x581265ca, 0xb024cb94, 0x65a5e1d9,
0xcb4bc3b2, 0x937bf195, 0x231b95db, 0x46372bb6, 0x8c6e576c, 0x1d30d829, 0x3a61b052, 0x74c360a4},
{0xfe314258, 0xf98ef241, 0xf6f19273, 0xe80f5217, 0xd5f2d2df, 0xae09d34f, 0x59ffd06f, 0xb3ffa0de,
0x6213374d, 0xc4266e9a, 0x8da0abc5, 0x1ead217b, 0x3d5a42f6, 0x7ab485ec, 0xf5690bd8, 0xef3e6141,
0xdb90b473, 0xb2cd1e17, 0x60764adf, 0xc0ec95be, 0x84355d8d, 0x0d86cdeb, 0x1b0d9bd6, 0x361b37ac,
0x6c366f58, 0xd86cdeb0, 0xb535cb91, 0x6f87e1d3, 0xdf0fc3a6, 0xbbf3f1bd, 0x720b958b, 0xe4172b16},
{0xf7506984, 0xeb4ca5f9, 0xd3753d03, 0xa3060cf7, 0x43e06f1f, 0x87c0de3e, 0x0a6dca8d, 0x14db951a,
0x29b72a34, 0x536e5468, 0xa6dca8d0, 0x48552751, 0x90aa4ea2, 0x24b8ebb5, 0x4971d76a, 0x92e3aed4,
0x202b2b59, 0x405656b2, 0x80acad64, 0x04b52c39, 0x096a5872, 0x12d4b0e4, 0x25a961c8, 0x4b52c390,
0x96a58720, 0x28a778b1, 0x514ef162, 0xa29de2c4, 0x40d7b379, 0x81af66f2, 0x06b2bb15, 0x0d65762a},
{0xc2a5b65e, 0x80a71a4d, 0x04a2426b, 0x094484d6, 0x128909ac, 0x25121358, 0x4a2426b0, 0x94484d60,
0x2d7cec31, 0x5af9d862, 0xb5f3b0c4, 0x6e0b1779, 0xdc162ef2, 0xbdc02b15, 0x7e6c20db, 0xfcd841b6,
0xfc5cf59d, 0xfd559dcb, 0xff474d67, 0xfb62ec3f, 0xf329ae8f, 0xe3bf2bef, 0xc292212f, 0x80c834af,
0x047c1faf, 0x08f83f5e, 0x11f07ebc, 0x23e0fd78, 0x47c1faf0, 0x8f83f5e0, 0x1aeb9d31, 0x35d73a62},
{0xe040e0ac, 0xc56db7a9, 0x8f3719a3, 0x1b8245b7, 0x37048b6e, 0x6e0916dc, 0xdc122db8, 0xbdc82d81,
0x7e7c2df3, 0xfcf85be6, 0xfc1cc13d, 0xfdd5f48b, 0xfe479fe7, 0xf963493f, 0xf72ae48f, 0xebb9bfef,
0xd29f092f, 0xa0d264af, 0x4448bfaf, 0x88917f5e, 0x14ce884d, 0x299d109a, 0x533a2134, 0xa6744268,
0x4904f221, 0x9209e442, 0x21ffbe75, 0x43ff7cea, 0x87fef9d4, 0x0a118559, 0x14230ab2, 0x28461564},
{0xc7cacead, 0x8a79ebab, 0x111fa1a7, 0x223f434e, 0x447e869c, 0x88fd0d38, 0x14166c81, 0x282cd902,
0x5059b204, 0xa0b36408, 0x448abee1, 0x89157dc2, 0x17c68d75, 0x2f8d1aea, 0x5f1a35d4, 0xbe346ba8,
0x7984a1a1, 0xf3094342, 0xe3fef075, 0xc211961b, 0x81cf5ac7, 0x0672c37f, 0x0ce586fe, 0x19cb0dfc,
0x33961bf8, 0x672c37f0, 0xce586fe0, 0x995ca931, 0x37552493, 0x6eaa4926, 0xdd54924c, 0xbf455269},
{0x04fcdcbf, 0x09f9b97e, 0x13f372fc, 0x27e6e5f8, 0x4fcdcbf0, 0x9f9b97e0, 0x3adb5931, 0x75b6b262,
0xeb6d64c4, 0xd336bf79, 0xa3810803, 0x42ee66f7, 0x85dccdee, 0x0e55ed2d, 0x1cabda5a, 0x3957b4b4,
0x72af6968, 0xe55ed2d0, 0xcf51d351, 0x9b4fd053, 0x3373d657, 0x66e7acae, 0xcdcf595c, 0x9e72c449,
0x3909fe63, 0x7213fcc6, 0xe427f98c, 0xcda385e9, 0x9eab7d23, 0x38ba8cb7, 0x7175196e, 0xe2ea32dc},
{0x6bafcc21, 0xd75f9842, 0xab534675, 0x534afa1b, 0xa695f436, 0x48c79e9d, 0x918f3d3a, 0x26f20c85,
0x4de4190a, 0x9bc83214, 0x327c12d9, 0x64f825b2, 0xc9f04b64, 0x960ce039, 0x29f5b683, 0x53eb6d06,
0xa7d6da0c, 0x4a41c2e9, 0x948385d2, 0x2ceb7d55, 0x59d6faaa, 0xb3adf554, 0x62b79c59, 0xc56f38b2,
0x8f320795, 0x1b8879db, 0x3710f3b6, 0x6e21e76c, 0xdc43ced8, 0xbd6beb41, 0x7f3ba073, 0xfe7740e6},
{0x140441c6, 0x2808838c, 0x50110718, 0xa0220e30, 0x45a86a91, 0x8b50d522, 0x134ddcb5, 0x269bb96a,
0x4d3772d4, 0x9a6ee5a8, 0x3131bda1, 0x62637b42, 0xc4c6f684, 0x8c619bf9, 0x1d2f4103, 0x3a5e8206,
0x74bd040c, 0xe97a0818, 0xd71866c1, 0xabdcbb73, 0x52550017, 0xa4aa002e, 0x4cb876ad, 0x9970ed5a,
0x370dac45, 0x6e1b588a, 0xdc36b114, 0xbd8114d9, 0x7eee5f43, 0xfddcbe86, 0xfe550bfd, 0xf946610b},
{0x68175a0a, 0xd02eb414, 0xa5b11ed9, 0x4e8e4b43, 0x9d1c9686, 0x3fd55bfd, 0x7faab7fa, 0xff556ff4,
0xfb46a919, 0xf36124c3, 0xe32e3f77, 0xc3b0081f, 0x828c66cf, 0x00f4bb6f, 0x01e976de, 0x03d2edbc,
0x07a5db78, 0x0f4bb6f0, 0x1e976de0, 0x3d2edbc0, 0x7a5db780, 0xf4bb6f00, 0xec9aa8f1, 0xdcd92713,
0xbc5e38d7, 0x7d50075f, 0xfaa00ebe, 0xf0ac6b8d, 0xe4b4a1eb, 0xcc853527, 0x9ce61cbf, 0x3c204f8f},
{0xe1ff3667, 0xc6121a3f, 0x89c8428f, 0x167cf3ef, 0x2cf9e7de, 0x59f3cfbc, 0xb3e79f78, 0x62234801,
0xc4469002, 0x8d6156f5, 0x1f2edb1b, 0x3e5db636, 0x7cbb6c6c, 0xf976d8d8, 0xf701c741, 0xebeff873,
0xd2338617, 0xa18b7adf, 0x46fa834f, 0x8df5069e, 0x1e067bcd, 0x3c0cf79a, 0x7819ef34, 0xf033de68,
0xe58bca21, 0xcefbe2b3, 0x981bb397, 0x35db11df, 0x6bb623be, 0xd76c477c, 0xab34f809, 0x538586e3},
{0x8b7230ec, 0x13081729, 0x26102e52, 0x4c205ca4, 0x9840b948, 0x356d0461, 0x6ada08c2, 0xd5b41184,
0xae8455f9, 0x58e4dd03, 0xb1c9ba06, 0x667f02fd, 0xccfe05fa, 0x9c107d05, 0x3dcc8cfb, 0x7b9919f6,
0xf73233ec, 0xeb881129, 0xd2fc54a3, 0xa014dfb7, 0x45c5c99f, 0x8b8b933e, 0x12fb508d, 0x25f6a11a,
0x4bed4234, 0x97da8468, 0x2a597e21, 0x54b2fc42, 0xa965f884, 0x572787f9, 0xae4f0ff2, 0x59726915},
{0x56175f20, 0xac2ebe40, 0x5db10a71, 0xbb6214e2, 0x73285f35, 0xe650be6a, 0xc94d0a25, 0x977662bb,
0x2b00b387, 0x5601670e, 0xac02ce1c, 0x5de9eac9, 0xbbd3d592, 0x724bddd5, 0xe497bbaa, 0xccc301a5,
0x9c6a75bb, 0x3d389d87, 0x7a713b0e, 0xf4e2761c, 0xec289ac9, 0xddbd4363, 0xbe96f037, 0x78c1969f,
0xf1832d3e, 0xe6ea2c8d, 0xc8382feb, 0x959c2927, 0x2ed424bf, 0x5da8497e, 0xbb5092fc, 0x734d5309},
{0xb9a3dcd0, 0x76abcf51, 0xed579ea2, 0xdf434bb5, 0xbb6ae19b, 0x7339b5c7, 0xe6736b8e, 0xc90aa1ed,
0x97f9352b, 0x2a1e1ca7, 0x543c394e, 0xa878729c, 0x551c93c9, 0xaa392792, 0x519e39d5, 0xa33c73aa,
0x439491a5, 0x8729234a, 0x0bbe3065, 0x177c60ca, 0x2ef8c194, 0x5df18328, 0xbbe30650, 0x722a7a51,
0xe454f4a2, 0xcd459fb5, 0x9f67499b, 0x3b22e5c7, 0x7645cb8e, 0xec8b971c, 0xdcfb58c9, 0xbc1ac763},
{0xdd2d789e, 0xbfb687cd, 0x7a81796b, 0xf502f2d6, 0xefe9935d, 0xda3f504b, 0xb192d667, 0x66c9da3f,
0xcd93b47e, 0x9ecb1e0d, 0x387a4aeb, 0x70f495d6, 0xe1e92bac, 0xc63e21a9, 0x899035a3, 0x16cc1db7,
0x2d983b6e, 0x5b3076dc, 0xb660edb8, 0x692dad81, 0xd25b5b02, 0xa15ac0f5, 0x4759f71b, 0x8eb3ee36,
0x188baa9d, 0x3117553a, 0x622eaa74, 0xc45d54e8, 0x8d56df21, 0x1f41c8b3, 0x3e839166, 0x7d0722cc},
{0x44036c4a, 0x8806d894, 0x15e1c7d9, 0x2bc38fb2, 0x57871f64, 0xaf0e3ec8, 0x5bf00b61, 0xb7e016c2,
0x6a2c5b75, 0xd458b6ea, 0xad5d1b25, 0x5f5640bb, 0xbeac8176, 0x78b5741d, 0xf16ae83a, 0xe739a685,
0xcb9f3bfb, 0x92d20107, 0x204874ff, 0x4090e9fe, 0x8121d3fc, 0x07afd109, 0x0f5fa212, 0x1ebf4424,
0x3d7e8848, 0x7afd1090, 0xf5fa2120, 0xee1834b1, 0xd9dc1f93, 0xb65449d7, 0x6944e55f, 0xd289cabe},
{0x4612657d, 0x8c24cafa, 0x1da5e305, 0x3b4bc60a, 0x76978c14, 0xed2f1828, 0xdfb246a1, 0xba88fbb3,
0x70fd8197, 0xe1fb032e, 0xc61a70ad, 0x89d897ab, 0x165d59a7, 0x2cbab34e, 0x5975669c, 0xb2eacd38,
0x6039ec81, 0xc073d902, 0x850bc4f5, 0x0ffbff1b, 0x1ff7fe36, 0x3feffc6c, 0x7fdff8d8, 0xffbff1b0,
0xfa939591, 0xf0cb5dd3, 0xe47acd57, 0xcd19ec5f, 0x9fdfae4f, 0x3a532a6f, 0x74a654de, 0xe94ca9bc},
{0x584d5569, 0xb09aaad2, 0x64d92355, 0xc9b246aa, 0x9688fba5, 0x28fd81bb, 0x51fb0376, 0xa3f606ec,
0x42007b29, 0x8400f652, 0x0ded9a55, 0x1bdb34aa, 0x37b66954, 0x6f6cd2a8, 0xded9a550, 0xb85f3c51,
0x75520e53, 0xeaa41ca6, 0xd0a44fbd, 0xa4a4e98b, 0x4ca5a5e7, 0x994b4bce, 0x377ae16d, 0x6ef5c2da,
0xddeb85b4, 0xbe3b7d99, 0x799a8dc3, 0xf3351b86, 0xe38641fd, 0xc2e0f50b, 0x802d9ce7, 0x05b74f3f},
{0xe8cd33e2, 0xd4761135, 0xad00549b, 0x5fecdfc7, 0xbfd9bf8e, 0x7a5f09ed, 0xf4be13da, 0xec905145,
0xdcccd47b, 0xbc75de07, 0x7d07caff, 0xfa0f95fe, 0xf1f35d0d, 0xe60acceb, 0xc9f9ef27, 0x961fa8bf,
0x29d3278f, 0x53a64f1e, 0xa74c9e3c, 0x4b754a89, 0x96ea9512, 0x28395cd5, 0x5072b9aa, 0xa0e57354,
0x44269059, 0x884d20b2, 0x15763795, 0x2aec6f2a, 0x55d8de54, 0xabb1bca8, 0x528f0fa1, 0xa51e1f42},
{0x82f63b78, 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040,
0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000,
0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000,
0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000},
{0x417b1dbc, 0x82f63b78, 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020,
0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000,
0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000,
0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000},
{0x105ec76f, 0x20bd8ede, 0x417b1dbc, 0x82f63b78, 0x00000001, 0x00000002, 0x00000004, 0x00000008,
0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800,
0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000,
0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000},
{0xf26b8303, 0xe13b70f7, 0xc79a971f, 0x8ad958cf, 0x105ec76f, 0x20bd8ede, 0x417b1dbc, 0x82f63b78,
0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080,
0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000,
0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000}
};
uint32_t ceph_crc32c_zeros(uint32_t crc, unsigned len)
{
int range = 0;
unsigned remainder = len & 15;
len = len >> 4;
range = 4;
while (len != 0) {
if ((len & 1) == 1) {
uint32_t crc1 = 0;
uint32_t* ptr = crc_turbo_table/*.val*/[range];
while (crc != 0) {
uint32_t mask = ~((crc & 1) - 1);
crc1 = crc1 ^ (mask & *ptr);
crc = crc >> 1;
ptr++;
}
crc = crc1;
}
len = len >> 1;
range++;
}
if (remainder > 0)
crc = ceph_crc32c(crc, nullptr, remainder);
return crc;
}
| 15,943 | 65.157676 | 101 | cc |
null | ceph-main/src/common/crc32c_aarch64.h | #ifndef CEPH_COMMON_CRC32C_AARCH64_H
#define CEPH_COMMON_CRC32C_AARCH64_H
#include "acconfig.h"
#include "arch/arm.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HAVE_ARMV8_CRC
extern uint32_t ceph_crc32c_aarch64(uint32_t crc, unsigned char const *buffer, unsigned len);
#else
static inline uint32_t ceph_crc32c_aarch64(uint32_t crc, unsigned char const *buffer, unsigned len)
{
return 0;
}
#endif
#ifdef __cplusplus
}
#endif
#endif
| 445 | 14.37931 | 99 | h |
null | ceph-main/src/common/crc32c_intel_baseline.h | #ifndef CEPH_COMMON_CRC32C_INTEL_BASELINE_H
#define CEPH_COMMON_CRC32C_INTEL_BASELINE_H
#include "include/int_types.h"
#ifdef __cplusplus
extern "C" {
#endif
extern uint32_t ceph_crc32c_intel_baseline(uint32_t crc, unsigned char const *buffer, unsigned len);
#ifdef __cplusplus
}
#endif
#endif
| 299 | 16.647059 | 100 | h |
null | ceph-main/src/common/crc32c_intel_fast.h | #ifndef CEPH_COMMON_CRC32C_INTEL_FAST_H
#define CEPH_COMMON_CRC32C_INTEL_FAST_H
#ifdef __cplusplus
extern "C" {
#endif
/* is the fast version compiled in */
extern int ceph_crc32c_intel_fast_exists(void);
#ifdef __x86_64__
extern uint32_t ceph_crc32c_intel_fast(uint32_t crc, unsigned char const *buffer, unsigned len);
#else
static inline uint32_t ceph_crc32c_intel_fast(uint32_t crc, unsigned char const *buffer, unsigned len)
{
return 0;
}
#endif
#ifdef __cplusplus
}
#endif
#endif
| 495 | 16.103448 | 102 | h |
null | ceph-main/src/common/crc32c_ppc.h | /* 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 CEPH_COMMON_CRC32C_PPC_H
#define CEPH_COMMON_CRC32C_PPC_H
#ifdef __cplusplus
extern "C" {
#endif
extern uint32_t ceph_crc32c_ppc(uint32_t crc, unsigned char const *buffer, unsigned len);
#ifdef __cplusplus
}
#endif
#endif
| 577 | 24.130435 | 89 | h |
null | ceph-main/src/common/crc32c_ppc_constants.h | /* 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.
*/
#define CRC 0x1edc6f41
#define REFLECT
#ifndef __ASSEMBLY__
#ifdef CRC_TABLE
static const unsigned int crc_table[] = {
0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4,
0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb,
0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b,
0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24,
0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b,
0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384,
0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54,
0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b,
0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a,
0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35,
0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5,
0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa,
0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45,
0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a,
0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a,
0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595,
0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48,
0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957,
0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687,
0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198,
0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927,
0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38,
0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8,
0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7,
0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096,
0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789,
0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859,
0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46,
0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9,
0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6,
0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36,
0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829,
0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c,
0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93,
0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043,
0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c,
0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3,
0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc,
0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c,
0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033,
0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652,
0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d,
0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d,
0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982,
0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d,
0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622,
0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2,
0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed,
0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530,
0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f,
0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff,
0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0,
0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f,
0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540,
0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90,
0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f,
0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee,
0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1,
0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321,
0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e,
0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81,
0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e,
0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e,
0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351,};
#endif
#ifdef FAST_ZERO_TABLE
/* fast zero table */
unsigned int crc_zero[] = {
0x100,
0x10000,
0x1edc6f41,
0x3aab4576,
0x18571d18,
0x59a3508a,
0xaa97d41d,
0xe78dbf1d,
0x4ef6a711,
0x2506c32e,
0x68d4e827,
0x546ea6b0,
0x465cebac,
0x26a86214,
0x964aa2fd,
0x3b4c5747,
0x6702ee7f,
0xd086629f,
0xf1f2043c,
0xc761a1ca,
0xa8964e9a,
0x90cab2ce,
0xc6e3583d,
0x3344e0be,
0x7d53914b,
0x3d953297,
0xfcf2eda0,
0x42f878a5,
0x2,
0x4,
0x10,
0x100,
0x10000,
0x1edc6f41,
0x3aab4576,
0x18571d18,
0x59a3508a,
0xaa97d41d,
0xe78dbf1d,
0x4ef6a711,
0x2506c32e,
0x68d4e827,
0x546ea6b0,
0x465cebac,
0x26a86214,
0x964aa2fd,
0x3b4c5747,
0x6702ee7f,
0xd086629f,
0xf1f2043c,
0xc761a1ca,
0xa8964e9a,
0x90cab2ce,
0xc6e3583d,
0x3344e0be,
0x7d53914b,
0x3d953297,
0xfcf2eda0,
0x42f878a5,
0x2,
0x4,
0x10,
0x100,
0x10000
};
#endif
#else
#define MAX_SIZE 32768
.constants:
/* Reduce 262144 kbits to 1024 bits */
/* x^261120 mod p(x)` << 1, x^261184 mod p(x)` << 1 */
.octa 0x00000000b6ca9e20000000009c37c408
/* x^260096 mod p(x)` << 1, x^260160 mod p(x)` << 1 */
.octa 0x00000000350249a800000001b51df26c
/* x^259072 mod p(x)` << 1, x^259136 mod p(x)` << 1 */
.octa 0x00000001862dac54000000000724b9d0
/* x^258048 mod p(x)` << 1, x^258112 mod p(x)` << 1 */
.octa 0x00000001d87fb48c00000001c00532fe
/* x^257024 mod p(x)` << 1, x^257088 mod p(x)` << 1 */
.octa 0x00000001f39b699e00000000f05a9362
/* x^256000 mod p(x)` << 1, x^256064 mod p(x)` << 1 */
.octa 0x0000000101da11b400000001e1007970
/* x^254976 mod p(x)` << 1, x^255040 mod p(x)` << 1 */
.octa 0x00000001cab571e000000000a57366ee
/* x^253952 mod p(x)` << 1, x^254016 mod p(x)` << 1 */
.octa 0x00000000c7020cfe0000000192011284
/* x^252928 mod p(x)` << 1, x^252992 mod p(x)` << 1 */
.octa 0x00000000cdaed1ae0000000162716d9a
/* x^251904 mod p(x)` << 1, x^251968 mod p(x)` << 1 */
.octa 0x00000001e804effc00000000cd97ecde
/* x^250880 mod p(x)` << 1, x^250944 mod p(x)` << 1 */
.octa 0x0000000077c3ea3a0000000058812bc0
/* x^249856 mod p(x)` << 1, x^249920 mod p(x)` << 1 */
.octa 0x0000000068df31b40000000088b8c12e
/* x^248832 mod p(x)` << 1, x^248896 mod p(x)` << 1 */
.octa 0x00000000b059b6c200000001230b234c
/* x^247808 mod p(x)` << 1, x^247872 mod p(x)` << 1 */
.octa 0x0000000145fb8ed800000001120b416e
/* x^246784 mod p(x)` << 1, x^246848 mod p(x)` << 1 */
.octa 0x00000000cbc0916800000001974aecb0
/* x^245760 mod p(x)` << 1, x^245824 mod p(x)` << 1 */
.octa 0x000000005ceeedc2000000008ee3f226
/* x^244736 mod p(x)` << 1, x^244800 mod p(x)` << 1 */
.octa 0x0000000047d74e8600000001089aba9a
/* x^243712 mod p(x)` << 1, x^243776 mod p(x)` << 1 */
.octa 0x00000001407e9e220000000065113872
/* x^242688 mod p(x)` << 1, x^242752 mod p(x)` << 1 */
.octa 0x00000001da967bda000000005c07ec10
/* x^241664 mod p(x)` << 1, x^241728 mod p(x)` << 1 */
.octa 0x000000006c8983680000000187590924
/* x^240640 mod p(x)` << 1, x^240704 mod p(x)` << 1 */
.octa 0x00000000f2d14c9800000000e35da7c6
/* x^239616 mod p(x)` << 1, x^239680 mod p(x)` << 1 */
.octa 0x00000001993c6ad4000000000415855a
/* x^238592 mod p(x)` << 1, x^238656 mod p(x)` << 1 */
.octa 0x000000014683d1ac0000000073617758
/* x^237568 mod p(x)` << 1, x^237632 mod p(x)` << 1 */
.octa 0x00000001a7c93e6c0000000176021d28
/* x^236544 mod p(x)` << 1, x^236608 mod p(x)` << 1 */
.octa 0x000000010211e90a00000001c358fd0a
/* x^235520 mod p(x)` << 1, x^235584 mod p(x)` << 1 */
.octa 0x000000001119403e00000001ff7a2c18
/* x^234496 mod p(x)` << 1, x^234560 mod p(x)` << 1 */
.octa 0x000000001c3261aa00000000f2d9f7e4
/* x^233472 mod p(x)` << 1, x^233536 mod p(x)` << 1 */
.octa 0x000000014e37a634000000016cf1f9c8
/* x^232448 mod p(x)` << 1, x^232512 mod p(x)` << 1 */
.octa 0x0000000073786c0c000000010af9279a
/* x^231424 mod p(x)` << 1, x^231488 mod p(x)` << 1 */
.octa 0x000000011dc037f80000000004f101e8
/* x^230400 mod p(x)` << 1, x^230464 mod p(x)` << 1 */
.octa 0x0000000031433dfc0000000070bcf184
/* x^229376 mod p(x)` << 1, x^229440 mod p(x)` << 1 */
.octa 0x000000009cde8348000000000a8de642
/* x^228352 mod p(x)` << 1, x^228416 mod p(x)` << 1 */
.octa 0x0000000038d3c2a60000000062ea130c
/* x^227328 mod p(x)` << 1, x^227392 mod p(x)` << 1 */
.octa 0x000000011b25f26000000001eb31cbb2
/* x^226304 mod p(x)` << 1, x^226368 mod p(x)` << 1 */
.octa 0x000000001629e6f00000000170783448
/* x^225280 mod p(x)` << 1, x^225344 mod p(x)` << 1 */
.octa 0x0000000160838b4c00000001a684b4c6
/* x^224256 mod p(x)` << 1, x^224320 mod p(x)` << 1 */
.octa 0x000000007a44011c00000000253ca5b4
/* x^223232 mod p(x)` << 1, x^223296 mod p(x)` << 1 */
.octa 0x00000000226f417a0000000057b4b1e2
/* x^222208 mod p(x)` << 1, x^222272 mod p(x)` << 1 */
.octa 0x0000000045eb2eb400000000b6bd084c
/* x^221184 mod p(x)` << 1, x^221248 mod p(x)` << 1 */
.octa 0x000000014459d70c0000000123c2d592
/* x^220160 mod p(x)` << 1, x^220224 mod p(x)` << 1 */
.octa 0x00000001d406ed8200000000159dafce
/* x^219136 mod p(x)` << 1, x^219200 mod p(x)` << 1 */
.octa 0x0000000160c8e1a80000000127e1a64e
/* x^218112 mod p(x)` << 1, x^218176 mod p(x)` << 1 */
.octa 0x0000000027ba80980000000056860754
/* x^217088 mod p(x)` << 1, x^217152 mod p(x)` << 1 */
.octa 0x000000006d92d01800000001e661aae8
/* x^216064 mod p(x)` << 1, x^216128 mod p(x)` << 1 */
.octa 0x000000012ed7e3f200000000f82c6166
/* x^215040 mod p(x)` << 1, x^215104 mod p(x)` << 1 */
.octa 0x000000002dc8778800000000c4f9c7ae
/* x^214016 mod p(x)` << 1, x^214080 mod p(x)` << 1 */
.octa 0x0000000018240bb80000000074203d20
/* x^212992 mod p(x)` << 1, x^213056 mod p(x)` << 1 */
.octa 0x000000001ad381580000000198173052
/* x^211968 mod p(x)` << 1, x^212032 mod p(x)` << 1 */
.octa 0x00000001396b78f200000001ce8aba54
/* x^210944 mod p(x)` << 1, x^211008 mod p(x)` << 1 */
.octa 0x000000011a68133400000001850d5d94
/* x^209920 mod p(x)` << 1, x^209984 mod p(x)` << 1 */
.octa 0x000000012104732e00000001d609239c
/* x^208896 mod p(x)` << 1, x^208960 mod p(x)` << 1 */
.octa 0x00000000a140d90c000000001595f048
/* x^207872 mod p(x)` << 1, x^207936 mod p(x)` << 1 */
.octa 0x00000001b7215eda0000000042ccee08
/* x^206848 mod p(x)` << 1, x^206912 mod p(x)` << 1 */
.octa 0x00000001aaf1df3c000000010a389d74
/* x^205824 mod p(x)` << 1, x^205888 mod p(x)` << 1 */
.octa 0x0000000029d15b8a000000012a840da6
/* x^204800 mod p(x)` << 1, x^204864 mod p(x)` << 1 */
.octa 0x00000000f1a96922000000001d181c0c
/* x^203776 mod p(x)` << 1, x^203840 mod p(x)` << 1 */
.octa 0x00000001ac80d03c0000000068b7d1f6
/* x^202752 mod p(x)` << 1, x^202816 mod p(x)` << 1 */
.octa 0x000000000f11d56a000000005b0f14fc
/* x^201728 mod p(x)` << 1, x^201792 mod p(x)` << 1 */
.octa 0x00000001f1c022a20000000179e9e730
/* x^200704 mod p(x)` << 1, x^200768 mod p(x)` << 1 */
.octa 0x0000000173d00ae200000001ce1368d6
/* x^199680 mod p(x)` << 1, x^199744 mod p(x)` << 1 */
.octa 0x00000001d4ffe4ac0000000112c3a84c
/* x^198656 mod p(x)` << 1, x^198720 mod p(x)` << 1 */
.octa 0x000000016edc5ae400000000de940fee
/* x^197632 mod p(x)` << 1, x^197696 mod p(x)` << 1 */
.octa 0x00000001f1a0214000000000fe896b7e
/* x^196608 mod p(x)` << 1, x^196672 mod p(x)` << 1 */
.octa 0x00000000ca0b28a000000001f797431c
/* x^195584 mod p(x)` << 1, x^195648 mod p(x)` << 1 */
.octa 0x00000001928e30a20000000053e989ba
/* x^194560 mod p(x)` << 1, x^194624 mod p(x)` << 1 */
.octa 0x0000000097b1b002000000003920cd16
/* x^193536 mod p(x)` << 1, x^193600 mod p(x)` << 1 */
.octa 0x00000000b15bf90600000001e6f579b8
/* x^192512 mod p(x)` << 1, x^192576 mod p(x)` << 1 */
.octa 0x00000000411c5d52000000007493cb0a
/* x^191488 mod p(x)` << 1, x^191552 mod p(x)` << 1 */
.octa 0x00000001c36f330000000001bdd376d8
/* x^190464 mod p(x)` << 1, x^190528 mod p(x)` << 1 */
.octa 0x00000001119227e0000000016badfee6
/* x^189440 mod p(x)` << 1, x^189504 mod p(x)` << 1 */
.octa 0x00000000114d47020000000071de5c58
/* x^188416 mod p(x)` << 1, x^188480 mod p(x)` << 1 */
.octa 0x00000000458b5b9800000000453f317c
/* x^187392 mod p(x)` << 1, x^187456 mod p(x)` << 1 */
.octa 0x000000012e31fb8e0000000121675cce
/* x^186368 mod p(x)` << 1, x^186432 mod p(x)` << 1 */
.octa 0x000000005cf619d800000001f409ee92
/* x^185344 mod p(x)` << 1, x^185408 mod p(x)` << 1 */
.octa 0x0000000063f4d8b200000000f36b9c88
/* x^184320 mod p(x)` << 1, x^184384 mod p(x)` << 1 */
.octa 0x000000004138dc8a0000000036b398f4
/* x^183296 mod p(x)` << 1, x^183360 mod p(x)` << 1 */
.octa 0x00000001d29ee8e000000001748f9adc
/* x^182272 mod p(x)` << 1, x^182336 mod p(x)` << 1 */
.octa 0x000000006a08ace800000001be94ec00
/* x^181248 mod p(x)` << 1, x^181312 mod p(x)` << 1 */
.octa 0x0000000127d4201000000000b74370d6
/* x^180224 mod p(x)` << 1, x^180288 mod p(x)` << 1 */
.octa 0x0000000019d76b6200000001174d0b98
/* x^179200 mod p(x)` << 1, x^179264 mod p(x)` << 1 */
.octa 0x00000001b1471f6e00000000befc06a4
/* x^178176 mod p(x)` << 1, x^178240 mod p(x)` << 1 */
.octa 0x00000001f64c19cc00000001ae125288
/* x^177152 mod p(x)` << 1, x^177216 mod p(x)` << 1 */
.octa 0x00000000003c0ea00000000095c19b34
/* x^176128 mod p(x)` << 1, x^176192 mod p(x)` << 1 */
.octa 0x000000014d73abf600000001a78496f2
/* x^175104 mod p(x)` << 1, x^175168 mod p(x)` << 1 */
.octa 0x00000001620eb84400000001ac5390a0
/* x^174080 mod p(x)` << 1, x^174144 mod p(x)` << 1 */
.octa 0x0000000147655048000000002a80ed6e
/* x^173056 mod p(x)` << 1, x^173120 mod p(x)` << 1 */
.octa 0x0000000067b5077e00000001fa9b0128
/* x^172032 mod p(x)` << 1, x^172096 mod p(x)` << 1 */
.octa 0x0000000010ffe20600000001ea94929e
/* x^171008 mod p(x)` << 1, x^171072 mod p(x)` << 1 */
.octa 0x000000000fee8f1e0000000125f4305c
/* x^169984 mod p(x)` << 1, x^170048 mod p(x)` << 1 */
.octa 0x00000001da26fbae00000001471e2002
/* x^168960 mod p(x)` << 1, x^169024 mod p(x)` << 1 */
.octa 0x00000001b3a8bd880000000132d2253a
/* x^167936 mod p(x)` << 1, x^168000 mod p(x)` << 1 */
.octa 0x00000000e8f3898e00000000f26b3592
/* x^166912 mod p(x)` << 1, x^166976 mod p(x)` << 1 */
.octa 0x00000000b0d0d28c00000000bc8b67b0
/* x^165888 mod p(x)` << 1, x^165952 mod p(x)` << 1 */
.octa 0x0000000030f2a798000000013a826ef2
/* x^164864 mod p(x)` << 1, x^164928 mod p(x)` << 1 */
.octa 0x000000000fba10020000000081482c84
/* x^163840 mod p(x)` << 1, x^163904 mod p(x)` << 1 */
.octa 0x00000000bdb9bd7200000000e77307c2
/* x^162816 mod p(x)` << 1, x^162880 mod p(x)` << 1 */
.octa 0x0000000075d3bf5a00000000d4a07ec8
/* x^161792 mod p(x)` << 1, x^161856 mod p(x)` << 1 */
.octa 0x00000000ef1f98a00000000017102100
/* x^160768 mod p(x)` << 1, x^160832 mod p(x)` << 1 */
.octa 0x00000000689c760200000000db406486
/* x^159744 mod p(x)` << 1, x^159808 mod p(x)` << 1 */
.octa 0x000000016d5fa5fe0000000192db7f88
/* x^158720 mod p(x)` << 1, x^158784 mod p(x)` << 1 */
.octa 0x00000001d0d2b9ca000000018bf67b1e
/* x^157696 mod p(x)` << 1, x^157760 mod p(x)` << 1 */
.octa 0x0000000041e7b470000000007c09163e
/* x^156672 mod p(x)` << 1, x^156736 mod p(x)` << 1 */
.octa 0x00000001cbb6495e000000000adac060
/* x^155648 mod p(x)` << 1, x^155712 mod p(x)` << 1 */
.octa 0x000000010052a0b000000000bd8316ae
/* x^154624 mod p(x)` << 1, x^154688 mod p(x)` << 1 */
.octa 0x00000001d8effb5c000000019f09ab54
/* x^153600 mod p(x)` << 1, x^153664 mod p(x)` << 1 */
.octa 0x00000001d969853c0000000125155542
/* x^152576 mod p(x)` << 1, x^152640 mod p(x)` << 1 */
.octa 0x00000000523ccce2000000018fdb5882
/* x^151552 mod p(x)` << 1, x^151616 mod p(x)` << 1 */
.octa 0x000000001e2436bc00000000e794b3f4
/* x^150528 mod p(x)` << 1, x^150592 mod p(x)` << 1 */
.octa 0x00000000ddd1c3a2000000016f9bb022
/* x^149504 mod p(x)` << 1, x^149568 mod p(x)` << 1 */
.octa 0x0000000019fcfe3800000000290c9978
/* x^148480 mod p(x)` << 1, x^148544 mod p(x)` << 1 */
.octa 0x00000001ce95db640000000083c0f350
/* x^147456 mod p(x)` << 1, x^147520 mod p(x)` << 1 */
.octa 0x00000000af5828060000000173ea6628
/* x^146432 mod p(x)` << 1, x^146496 mod p(x)` << 1 */
.octa 0x00000001006388f600000001c8b4e00a
/* x^145408 mod p(x)` << 1, x^145472 mod p(x)` << 1 */
.octa 0x0000000179eca00a00000000de95d6aa
/* x^144384 mod p(x)` << 1, x^144448 mod p(x)` << 1 */
.octa 0x0000000122410a6a000000010b7f7248
/* x^143360 mod p(x)` << 1, x^143424 mod p(x)` << 1 */
.octa 0x000000004288e87c00000001326e3a06
/* x^142336 mod p(x)` << 1, x^142400 mod p(x)` << 1 */
.octa 0x000000016c5490da00000000bb62c2e6
/* x^141312 mod p(x)` << 1, x^141376 mod p(x)` << 1 */
.octa 0x00000000d1c71f6e0000000156a4b2c2
/* x^140288 mod p(x)` << 1, x^140352 mod p(x)` << 1 */
.octa 0x00000001b4ce08a6000000011dfe763a
/* x^139264 mod p(x)` << 1, x^139328 mod p(x)` << 1 */
.octa 0x00000001466ba60c000000007bcca8e2
/* x^138240 mod p(x)` << 1, x^138304 mod p(x)` << 1 */
.octa 0x00000001f6c488a40000000186118faa
/* x^137216 mod p(x)` << 1, x^137280 mod p(x)` << 1 */
.octa 0x000000013bfb06820000000111a65a88
/* x^136192 mod p(x)` << 1, x^136256 mod p(x)` << 1 */
.octa 0x00000000690e9e54000000003565e1c4
/* x^135168 mod p(x)` << 1, x^135232 mod p(x)` << 1 */
.octa 0x00000000281346b6000000012ed02a82
/* x^134144 mod p(x)` << 1, x^134208 mod p(x)` << 1 */
.octa 0x000000015646402400000000c486ecfc
/* x^133120 mod p(x)` << 1, x^133184 mod p(x)` << 1 */
.octa 0x000000016063a8dc0000000001b951b2
/* x^132096 mod p(x)` << 1, x^132160 mod p(x)` << 1 */
.octa 0x0000000116a663620000000048143916
/* x^131072 mod p(x)` << 1, x^131136 mod p(x)` << 1 */
.octa 0x000000017e8aa4d200000001dc2ae124
/* x^130048 mod p(x)` << 1, x^130112 mod p(x)` << 1 */
.octa 0x00000001728eb10c00000001416c58d6
/* x^129024 mod p(x)` << 1, x^129088 mod p(x)` << 1 */
.octa 0x00000001b08fd7fa00000000a479744a
/* x^128000 mod p(x)` << 1, x^128064 mod p(x)` << 1 */
.octa 0x00000001092a16e80000000096ca3a26
/* x^126976 mod p(x)` << 1, x^127040 mod p(x)` << 1 */
.octa 0x00000000a505637c00000000ff223d4e
/* x^125952 mod p(x)` << 1, x^126016 mod p(x)` << 1 */
.octa 0x00000000d94869b2000000010e84da42
/* x^124928 mod p(x)` << 1, x^124992 mod p(x)` << 1 */
.octa 0x00000001c8b203ae00000001b61ba3d0
/* x^123904 mod p(x)` << 1, x^123968 mod p(x)` << 1 */
.octa 0x000000005704aea000000000680f2de8
/* x^122880 mod p(x)` << 1, x^122944 mod p(x)` << 1 */
.octa 0x000000012e295fa2000000008772a9a8
/* x^121856 mod p(x)` << 1, x^121920 mod p(x)` << 1 */
.octa 0x000000011d0908bc0000000155f295bc
/* x^120832 mod p(x)` << 1, x^120896 mod p(x)` << 1 */
.octa 0x0000000193ed97ea00000000595f9282
/* x^119808 mod p(x)` << 1, x^119872 mod p(x)` << 1 */
.octa 0x000000013a0f1c520000000164b1c25a
/* x^118784 mod p(x)` << 1, x^118848 mod p(x)` << 1 */
.octa 0x000000010c2c40c000000000fbd67c50
/* x^117760 mod p(x)` << 1, x^117824 mod p(x)` << 1 */
.octa 0x00000000ff6fac3e0000000096076268
/* x^116736 mod p(x)` << 1, x^116800 mod p(x)` << 1 */
.octa 0x000000017b3609c000000001d288e4cc
/* x^115712 mod p(x)` << 1, x^115776 mod p(x)` << 1 */
.octa 0x0000000088c8c92200000001eaac1bdc
/* x^114688 mod p(x)` << 1, x^114752 mod p(x)` << 1 */
.octa 0x00000001751baae600000001f1ea39e2
/* x^113664 mod p(x)` << 1, x^113728 mod p(x)` << 1 */
.octa 0x000000010795297200000001eb6506fc
/* x^112640 mod p(x)` << 1, x^112704 mod p(x)` << 1 */
.octa 0x0000000162b00abe000000010f806ffe
/* x^111616 mod p(x)` << 1, x^111680 mod p(x)` << 1 */
.octa 0x000000000d7b404c000000010408481e
/* x^110592 mod p(x)` << 1, x^110656 mod p(x)` << 1 */
.octa 0x00000000763b13d40000000188260534
/* x^109568 mod p(x)` << 1, x^109632 mod p(x)` << 1 */
.octa 0x00000000f6dc22d80000000058fc73e0
/* x^108544 mod p(x)` << 1, x^108608 mod p(x)` << 1 */
.octa 0x000000007daae06000000000391c59b8
/* x^107520 mod p(x)` << 1, x^107584 mod p(x)` << 1 */
.octa 0x000000013359ab7c000000018b638400
/* x^106496 mod p(x)` << 1, x^106560 mod p(x)` << 1 */
.octa 0x000000008add438a000000011738f5c4
/* x^105472 mod p(x)` << 1, x^105536 mod p(x)` << 1 */
.octa 0x00000001edbefdea000000008cf7c6da
/* x^104448 mod p(x)` << 1, x^104512 mod p(x)` << 1 */
.octa 0x000000004104e0f800000001ef97fb16
/* x^103424 mod p(x)` << 1, x^103488 mod p(x)` << 1 */
.octa 0x00000000b48a82220000000102130e20
/* x^102400 mod p(x)` << 1, x^102464 mod p(x)` << 1 */
.octa 0x00000001bcb4684400000000db968898
/* x^101376 mod p(x)` << 1, x^101440 mod p(x)` << 1 */
.octa 0x000000013293ce0a00000000b5047b5e
/* x^100352 mod p(x)` << 1, x^100416 mod p(x)` << 1 */
.octa 0x00000001710d0844000000010b90fdb2
/* x^99328 mod p(x)` << 1, x^99392 mod p(x)` << 1 */
.octa 0x0000000117907f6e000000004834a32e
/* x^98304 mod p(x)` << 1, x^98368 mod p(x)` << 1 */
.octa 0x0000000087ddf93e0000000059c8f2b0
/* x^97280 mod p(x)` << 1, x^97344 mod p(x)` << 1 */
.octa 0x000000005970e9b00000000122cec508
/* x^96256 mod p(x)` << 1, x^96320 mod p(x)` << 1 */
.octa 0x0000000185b2b7d0000000000a330cda
/* x^95232 mod p(x)` << 1, x^95296 mod p(x)` << 1 */
.octa 0x00000001dcee0efc000000014a47148c
/* x^94208 mod p(x)` << 1, x^94272 mod p(x)` << 1 */
.octa 0x0000000030da27220000000042c61cb8
/* x^93184 mod p(x)` << 1, x^93248 mod p(x)` << 1 */
.octa 0x000000012f925a180000000012fe6960
/* x^92160 mod p(x)` << 1, x^92224 mod p(x)` << 1 */
.octa 0x00000000dd2e357c00000000dbda2c20
/* x^91136 mod p(x)` << 1, x^91200 mod p(x)` << 1 */
.octa 0x00000000071c80de000000011122410c
/* x^90112 mod p(x)` << 1, x^90176 mod p(x)` << 1 */
.octa 0x000000011513140a00000000977b2070
/* x^89088 mod p(x)` << 1, x^89152 mod p(x)` << 1 */
.octa 0x00000001df876e8e000000014050438e
/* x^88064 mod p(x)` << 1, x^88128 mod p(x)` << 1 */
.octa 0x000000015f81d6ce0000000147c840e8
/* x^87040 mod p(x)` << 1, x^87104 mod p(x)` << 1 */
.octa 0x000000019dd94dbe00000001cc7c88ce
/* x^86016 mod p(x)` << 1, x^86080 mod p(x)` << 1 */
.octa 0x00000001373d206e00000001476b35a4
/* x^84992 mod p(x)` << 1, x^85056 mod p(x)` << 1 */
.octa 0x00000000668ccade000000013d52d508
/* x^83968 mod p(x)` << 1, x^84032 mod p(x)` << 1 */
.octa 0x00000001b192d268000000008e4be32e
/* x^82944 mod p(x)` << 1, x^83008 mod p(x)` << 1 */
.octa 0x00000000e30f3a7800000000024120fe
/* x^81920 mod p(x)` << 1, x^81984 mod p(x)` << 1 */
.octa 0x000000010ef1f7bc00000000ddecddb4
/* x^80896 mod p(x)` << 1, x^80960 mod p(x)` << 1 */
.octa 0x00000001f5ac738000000000d4d403bc
/* x^79872 mod p(x)` << 1, x^79936 mod p(x)` << 1 */
.octa 0x000000011822ea7000000001734b89aa
/* x^78848 mod p(x)` << 1, x^78912 mod p(x)` << 1 */
.octa 0x00000000c3a33848000000010e7a58d6
/* x^77824 mod p(x)` << 1, x^77888 mod p(x)` << 1 */
.octa 0x00000001bd151c2400000001f9f04e9c
/* x^76800 mod p(x)` << 1, x^76864 mod p(x)` << 1 */
.octa 0x0000000056002d7600000000b692225e
/* x^75776 mod p(x)` << 1, x^75840 mod p(x)` << 1 */
.octa 0x000000014657c4f4000000019b8d3f3e
/* x^74752 mod p(x)` << 1, x^74816 mod p(x)` << 1 */
.octa 0x0000000113742d7c00000001a874f11e
/* x^73728 mod p(x)` << 1, x^73792 mod p(x)` << 1 */
.octa 0x000000019c5920ba000000010d5a4254
/* x^72704 mod p(x)` << 1, x^72768 mod p(x)` << 1 */
.octa 0x000000005216d2d600000000bbb2f5d6
/* x^71680 mod p(x)` << 1, x^71744 mod p(x)` << 1 */
.octa 0x0000000136f5ad8a0000000179cc0e36
/* x^70656 mod p(x)` << 1, x^70720 mod p(x)` << 1 */
.octa 0x000000018b07beb600000001dca1da4a
/* x^69632 mod p(x)` << 1, x^69696 mod p(x)` << 1 */
.octa 0x00000000db1e93b000000000feb1a192
/* x^68608 mod p(x)` << 1, x^68672 mod p(x)` << 1 */
.octa 0x000000000b96fa3a00000000d1eeedd6
/* x^67584 mod p(x)` << 1, x^67648 mod p(x)` << 1 */
.octa 0x00000001d9968af0000000008fad9bb4
/* x^66560 mod p(x)` << 1, x^66624 mod p(x)` << 1 */
.octa 0x000000000e4a77a200000001884938e4
/* x^65536 mod p(x)` << 1, x^65600 mod p(x)` << 1 */
.octa 0x00000000508c2ac800000001bc2e9bc0
/* x^64512 mod p(x)` << 1, x^64576 mod p(x)` << 1 */
.octa 0x0000000021572a8000000001f9658a68
/* x^63488 mod p(x)` << 1, x^63552 mod p(x)` << 1 */
.octa 0x00000001b859daf2000000001b9224fc
/* x^62464 mod p(x)` << 1, x^62528 mod p(x)` << 1 */
.octa 0x000000016f7884740000000055b2fb84
/* x^61440 mod p(x)` << 1, x^61504 mod p(x)` << 1 */
.octa 0x00000001b438810e000000018b090348
/* x^60416 mod p(x)` << 1, x^60480 mod p(x)` << 1 */
.octa 0x0000000095ddc6f2000000011ccbd5ea
/* x^59392 mod p(x)` << 1, x^59456 mod p(x)` << 1 */
.octa 0x00000001d977c20c0000000007ae47f8
/* x^58368 mod p(x)` << 1, x^58432 mod p(x)` << 1 */
.octa 0x00000000ebedb99a0000000172acbec0
/* x^57344 mod p(x)` << 1, x^57408 mod p(x)` << 1 */
.octa 0x00000001df9e9e9200000001c6e3ff20
/* x^56320 mod p(x)` << 1, x^56384 mod p(x)` << 1 */
.octa 0x00000001a4a3f95200000000e1b38744
/* x^55296 mod p(x)` << 1, x^55360 mod p(x)` << 1 */
.octa 0x00000000e2f5122000000000791585b2
/* x^54272 mod p(x)` << 1, x^54336 mod p(x)` << 1 */
.octa 0x000000004aa01f3e00000000ac53b894
/* x^53248 mod p(x)` << 1, x^53312 mod p(x)` << 1 */
.octa 0x00000000b3e90a5800000001ed5f2cf4
/* x^52224 mod p(x)` << 1, x^52288 mod p(x)` << 1 */
.octa 0x000000000c9ca2aa00000001df48b2e0
/* x^51200 mod p(x)` << 1, x^51264 mod p(x)` << 1 */
.octa 0x000000015168231600000000049c1c62
/* x^50176 mod p(x)` << 1, x^50240 mod p(x)` << 1 */
.octa 0x0000000036fce78c000000017c460c12
/* x^49152 mod p(x)` << 1, x^49216 mod p(x)` << 1 */
.octa 0x000000009037dc10000000015be4da7e
/* x^48128 mod p(x)` << 1, x^48192 mod p(x)` << 1 */
.octa 0x00000000d3298582000000010f38f668
/* x^47104 mod p(x)` << 1, x^47168 mod p(x)` << 1 */
.octa 0x00000001b42e8ad60000000039f40a00
/* x^46080 mod p(x)` << 1, x^46144 mod p(x)` << 1 */
.octa 0x00000000142a983800000000bd4c10c4
/* x^45056 mod p(x)` << 1, x^45120 mod p(x)` << 1 */
.octa 0x0000000109c7f1900000000042db1d98
/* x^44032 mod p(x)` << 1, x^44096 mod p(x)` << 1 */
.octa 0x0000000056ff931000000001c905bae6
/* x^43008 mod p(x)` << 1, x^43072 mod p(x)` << 1 */
.octa 0x00000001594513aa00000000069d40ea
/* x^41984 mod p(x)` << 1, x^42048 mod p(x)` << 1 */
.octa 0x00000001e3b5b1e8000000008e4fbad0
/* x^40960 mod p(x)` << 1, x^41024 mod p(x)` << 1 */
.octa 0x000000011dd5fc080000000047bedd46
/* x^39936 mod p(x)` << 1, x^40000 mod p(x)` << 1 */
.octa 0x00000001675f0cc20000000026396bf8
/* x^38912 mod p(x)` << 1, x^38976 mod p(x)` << 1 */
.octa 0x00000000d1c8dd4400000000379beb92
/* x^37888 mod p(x)` << 1, x^37952 mod p(x)` << 1 */
.octa 0x0000000115ebd3d8000000000abae54a
/* x^36864 mod p(x)` << 1, x^36928 mod p(x)` << 1 */
.octa 0x00000001ecbd0dac0000000007e6a128
/* x^35840 mod p(x)` << 1, x^35904 mod p(x)` << 1 */
.octa 0x00000000cdf67af2000000000ade29d2
/* x^34816 mod p(x)` << 1, x^34880 mod p(x)` << 1 */
.octa 0x000000004c01ff4c00000000f974c45c
/* x^33792 mod p(x)` << 1, x^33856 mod p(x)` << 1 */
.octa 0x00000000f2d8657e00000000e77ac60a
/* x^32768 mod p(x)` << 1, x^32832 mod p(x)` << 1 */
.octa 0x000000006bae74c40000000145895816
/* x^31744 mod p(x)` << 1, x^31808 mod p(x)` << 1 */
.octa 0x0000000152af8aa00000000038e362be
/* x^30720 mod p(x)` << 1, x^30784 mod p(x)` << 1 */
.octa 0x0000000004663802000000007f991a64
/* x^29696 mod p(x)` << 1, x^29760 mod p(x)` << 1 */
.octa 0x00000001ab2f5afc00000000fa366d3a
/* x^28672 mod p(x)` << 1, x^28736 mod p(x)` << 1 */
.octa 0x0000000074a4ebd400000001a2bb34f0
/* x^27648 mod p(x)` << 1, x^27712 mod p(x)` << 1 */
.octa 0x00000001d7ab3a4c0000000028a9981e
/* x^26624 mod p(x)` << 1, x^26688 mod p(x)` << 1 */
.octa 0x00000001a8da60c600000001dbc672be
/* x^25600 mod p(x)` << 1, x^25664 mod p(x)` << 1 */
.octa 0x000000013cf6382000000000b04d77f6
/* x^24576 mod p(x)` << 1, x^24640 mod p(x)` << 1 */
.octa 0x00000000bec12e1e0000000124400d96
/* x^23552 mod p(x)` << 1, x^23616 mod p(x)` << 1 */
.octa 0x00000001c6368010000000014ca4b414
/* x^22528 mod p(x)` << 1, x^22592 mod p(x)` << 1 */
.octa 0x00000001e6e78758000000012fe2c938
/* x^21504 mod p(x)` << 1, x^21568 mod p(x)` << 1 */
.octa 0x000000008d7f2b3c00000001faed01e6
/* x^20480 mod p(x)` << 1, x^20544 mod p(x)` << 1 */
.octa 0x000000016b4a156e000000007e80ecfe
/* x^19456 mod p(x)` << 1, x^19520 mod p(x)` << 1 */
.octa 0x00000001c63cfeb60000000098daee94
/* x^18432 mod p(x)` << 1, x^18496 mod p(x)` << 1 */
.octa 0x000000015f902670000000010a04edea
/* x^17408 mod p(x)` << 1, x^17472 mod p(x)` << 1 */
.octa 0x00000001cd5de11e00000001c00b4524
/* x^16384 mod p(x)` << 1, x^16448 mod p(x)` << 1 */
.octa 0x000000001acaec540000000170296550
/* x^15360 mod p(x)` << 1, x^15424 mod p(x)` << 1 */
.octa 0x000000002bd0ca780000000181afaa48
/* x^14336 mod p(x)` << 1, x^14400 mod p(x)` << 1 */
.octa 0x0000000032d63d5c0000000185a31ffa
/* x^13312 mod p(x)` << 1, x^13376 mod p(x)` << 1 */
.octa 0x000000001c6d4e4c000000002469f608
/* x^12288 mod p(x)` << 1, x^12352 mod p(x)` << 1 */
.octa 0x0000000106a60b92000000006980102a
/* x^11264 mod p(x)` << 1, x^11328 mod p(x)` << 1 */
.octa 0x00000000d3855e120000000111ea9ca8
/* x^10240 mod p(x)` << 1, x^10304 mod p(x)` << 1 */
.octa 0x00000000e312563600000001bd1d29ce
/* x^9216 mod p(x)` << 1, x^9280 mod p(x)` << 1 */
.octa 0x000000009e8f7ea400000001b34b9580
/* x^8192 mod p(x)` << 1, x^8256 mod p(x)` << 1 */
.octa 0x00000001c82e562c000000003076054e
/* x^7168 mod p(x)` << 1, x^7232 mod p(x)` << 1 */
.octa 0x00000000ca9f09ce000000012a608ea4
/* x^6144 mod p(x)` << 1, x^6208 mod p(x)` << 1 */
.octa 0x00000000c63764e600000000784d05fe
/* x^5120 mod p(x)` << 1, x^5184 mod p(x)` << 1 */
.octa 0x0000000168d2e49e000000016ef0d82a
/* x^4096 mod p(x)` << 1, x^4160 mod p(x)` << 1 */
.octa 0x00000000e986c1480000000075bda454
/* x^3072 mod p(x)` << 1, x^3136 mod p(x)` << 1 */
.octa 0x00000000cfb65894000000003dc0a1c4
/* x^2048 mod p(x)` << 1, x^2112 mod p(x)` << 1 */
.octa 0x0000000111cadee400000000e9a5d8be
/* x^1024 mod p(x)` << 1, x^1088 mod p(x)` << 1 */
.octa 0x0000000171fb63ce00000001609bc4b4
.short_constants:
/* Reduce final 1024-2048 bits to 64 bits, shifting 32 bits to include the trailing 32 bits of zeros */
/* x^1952 mod p(x)`, x^1984 mod p(x)`, x^2016 mod p(x)`, x^2048 mod p(x)` */
.octa 0x7fec2963e5bf80485cf015c388e56f72
/* x^1824 mod p(x)`, x^1856 mod p(x)`, x^1888 mod p(x)`, x^1920 mod p(x)` */
.octa 0x38e888d4844752a9963a18920246e2e6
/* x^1696 mod p(x)`, x^1728 mod p(x)`, x^1760 mod p(x)`, x^1792 mod p(x)` */
.octa 0x42316c00730206ad419a441956993a31
/* x^1568 mod p(x)`, x^1600 mod p(x)`, x^1632 mod p(x)`, x^1664 mod p(x)` */
.octa 0x543d5c543e65ddf9924752ba2b830011
/* x^1440 mod p(x)`, x^1472 mod p(x)`, x^1504 mod p(x)`, x^1536 mod p(x)` */
.octa 0x78e87aaf56767c9255bd7f9518e4a304
/* x^1312 mod p(x)`, x^1344 mod p(x)`, x^1376 mod p(x)`, x^1408 mod p(x)` */
.octa 0x8f68fcec1903da7f6d76739fe0553f1e
/* x^1184 mod p(x)`, x^1216 mod p(x)`, x^1248 mod p(x)`, x^1280 mod p(x)` */
.octa 0x3f4840246791d588c133722b1fe0b5c3
/* x^1056 mod p(x)`, x^1088 mod p(x)`, x^1120 mod p(x)`, x^1152 mod p(x)` */
.octa 0x34c96751b04de25a64b67ee0e55ef1f3
/* x^928 mod p(x)`, x^960 mod p(x)`, x^992 mod p(x)`, x^1024 mod p(x)` */
.octa 0x156c8e180b4a395b069db049b8fdb1e7
/* x^800 mod p(x)`, x^832 mod p(x)`, x^864 mod p(x)`, x^896 mod p(x)` */
.octa 0xe0b99ccbe661f7bea11bfaf3c9e90b9e
/* x^672 mod p(x)`, x^704 mod p(x)`, x^736 mod p(x)`, x^768 mod p(x)` */
.octa 0x041d37768cd75659817cdc5119b29a35
/* x^544 mod p(x)`, x^576 mod p(x)`, x^608 mod p(x)`, x^640 mod p(x)` */
.octa 0x3a0777818cfaa9651ce9d94b36c41f1c
/* x^416 mod p(x)`, x^448 mod p(x)`, x^480 mod p(x)`, x^512 mod p(x)` */
.octa 0x0e148e8252377a554f256efcb82be955
/* x^288 mod p(x)`, x^320 mod p(x)`, x^352 mod p(x)`, x^384 mod p(x)` */
.octa 0x9c25531d19e65ddeec1631edb2dea967
/* x^160 mod p(x)`, x^192 mod p(x)`, x^224 mod p(x)`, x^256 mod p(x)` */
.octa 0x790606ff9957c0a65d27e147510ac59a
/* x^32 mod p(x)`, x^64 mod p(x)`, x^96 mod p(x)`, x^128 mod p(x)` */
.octa 0x82f63b786ea2d55ca66805eb18b8ea18
.barrett_constants:
/* 33 bit reflected Barrett constant m - (4^32)/n */
.octa 0x000000000000000000000000dea713f1 /* x^64 div p(x)` */
/* 33 bit reflected Barrett constant n */
.octa 0x00000000000000000000000105ec76f1
#endif
| 31,832 | 31.482653 | 104 | h |
null | ceph-main/src/common/darwin_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 <errno.h>
#include "include/types.h"
#include "include/compat.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 -EPERM; //TODO ECHRNG
case -45:
return -EPERM; //TODO EL2NSYNC
case -46:
return -EPERM; //TODO EL3HLT
case -47:
return -EPERM; //TODO EL3RST
case -48:
return -EPERM; //TODO ELNRNG
case -49:
return -EPERM; //TODO EUNATCH
case -51:
return -EPERM; //TODO EL2HLT;
case -52:
return -EPERM; //TODO EBADE
case -53:
return -EPERM; //TODO EBADR
case -54:
return -EPERM; //TODO EXFULL
case -55:
return -EPERM; //TODO ENOANO
case -56:
return -EPERM; //TODO EBADRQC
case -57:
return -EPERM; //TODO EBADSLT
case -59:
return -EPERM; //TODO 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 -EPERM; //TODO ENOTUNIQ
case -77:
return -EPERM; //TODO EBADFD
case -78:
return -EPERM; //TODO EREMCHG
case -79:
return -EPERM; //TODO ELIBACC
case -80:
return -EPERM; //TODO ELIBBAD
case -81:
return -EPERM; //TODO ELIBSCN
case -82:
return -EPERM; //TODO ELIBMAX
case -83:
return -EPERM; // TODO ELIBEXEC
case -84:
return -EILSEQ;
case -85:
return -EINTR;
case -86:
return -EPERM; //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 -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,457 | 22.324786 | 70 | cc |
null | ceph-main/src/common/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-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_DEBUG_H
#define CEPH_DEBUG_H
#include "common/dout.h"
/* Global version of the stuff in common/dout.h
*/
#define dout(v) ldout((dout_context), (v))
#define pdout(v, p) lpdout((dout_context), (v), (p))
#define dlog_p(sub, v) ldlog_p1((dout_context), (sub), (v))
#define generic_dout(v) lgeneric_dout((dout_context), (v))
#define derr lderr((dout_context))
#define generic_derr lgeneric_derr((dout_context))
#endif
| 850 | 22.638889 | 70 | h |
null | ceph-main/src/common/deleter.h | /*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef CEPH_COMMON_DELETER_H
#define CEPH_COMMON_DELETER_H
#include <atomic>
#include <cstdlib>
#include <new>
#include <utility>
/// \addtogroup memory-module
/// @{
/// Provides a mechanism for managing the lifetime of a buffer.
///
/// A \c deleter is an object that is used to inform the consumer
/// of some buffer (not referenced by the deleter itself) how to
/// delete the buffer. This can be by calling an arbitrary function
/// or destroying an object carried by the deleter. Examples of
/// a deleter's encapsulated actions are:
///
/// - calling \c std::free(p) on some captured pointer, p
/// - calling \c delete \c p on some captured pointer, p
/// - decrementing a reference count somewhere
///
/// A deleter performs its action from its destructor.
class deleter final {
public:
/// \cond internal
struct impl;
struct raw_object_tag {};
/// \endcond
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
/// Constructs an empty deleter that does nothing in its destructor.
deleter() = default;
deleter(const deleter&) = delete;
/// Moves a deleter.
deleter(deleter&& x) noexcept : _impl(x._impl) { x._impl = nullptr; }
/// \cond internal
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
/// \endcond
/// Destroys the deleter and carries out the encapsulated action.
~deleter();
deleter& operator=(deleter&& x);
deleter& operator=(deleter&) = delete;
/// Performs a sharing operation. The encapsulated action will only
/// be carried out after both the original deleter and the returned
/// deleter are both destroyed.
///
/// \return a deleter with the same encapsulated action as this one.
deleter share();
/// Checks whether the deleter has an associated action.
explicit operator bool() const { return bool(_impl); }
/// \cond internal
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
/// \endcond
/// Appends another deleter to this deleter. When this deleter is
/// destroyed, both encapsulated actions will be carried out.
void append(deleter d);
private:
static bool is_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
/// \cond internal
struct deleter::impl {
std::atomic_uint refs;
deleter next;
impl(deleter next) : refs(1), next(std::move(next)) {}
virtual ~impl() {}
};
/// \endcond
inline deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline deleter& deleter::operator=(deleter&& x) {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
/// \cond internal
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
inline
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
/// \endcond
/// Makes a \ref deleter that encapsulates the action of
/// destroying an object, as well as running another deleter. The input
/// object is moved to the deleter, and destroyed when the deleter is destroyed.
///
/// \param d deleter that will become part of the new deleter's encapsulated action
/// \param o object whose destructor becomes part of the new deleter's encapsulated action
/// \related deleter
template <typename Object>
deleter make_deleter(deleter next, Object o) {
return deleter(new lambda_deleter_impl<Object>(std::move(next), std::move(o)));
}
/// Makes a \ref deleter that encapsulates the action of destroying an object. The input
/// object is moved to the deleter, and destroyed when the deleter is destroyed.
///
/// \param o object whose destructor becomes the new deleter's encapsulated action
/// \related deleter
template <typename Object>
deleter make_deleter(Object o) {
return make_deleter(deleter(), std::move(o));
}
/// \cond internal
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
~free_deleter_impl() override { std::free(obj); }
};
/// \endcond
inline deleter deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
if (next_impl == d._impl)
return ;
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl));
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
/// Makes a deleter that calls \c std::free() when it is destroyed.
///
/// \param obj object to free.
/// \related deleter
inline deleter make_free_deleter(void* obj) {
if (!obj) {
return deleter();
}
return deleter(deleter::raw_object_tag(), obj);
}
/// Makes a deleter that calls \c std::free() when it is destroyed, as well
/// as invoking the encapsulated action of another deleter.
///
/// \param d deleter to invoke.
/// \param obj object to free.
/// \related deleter
inline deleter make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
/// \see make_deleter(Object)
/// \related deleter
template <typename T>
inline deleter make_object_deleter(T&& obj) {
return deleter{make_object_deleter_impl(deleter(), std::move(obj))};
}
/// \see make_deleter(deleter, Object)
/// \related deleter
template <typename T>
inline deleter make_object_deleter(deleter d, T&& obj) {
return deleter{make_object_deleter_impl(std::move(d), std::move(obj))};
}
/// @}
#endif /* CEPH_COMMON_DELETER_H */
| 7,899 | 29.152672 | 107 | h |
null | ceph-main/src/common/dns_resolve.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 SUSE LINUX GmbH
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <arpa/inet.h>
#include "include/scope_guard.h"
#include "dns_resolve.h"
#include "common/debug.h"
#define dout_subsys ceph_subsys_
using std::map;
using std::string;
namespace ceph {
#ifdef HAVE_RES_NQUERY
int ResolvHWrapper::res_nquery(res_state s, const char *hostname, int cls,
int type, u_char *buf, int bufsz) {
return ::res_nquery(s, hostname, cls, type, buf, bufsz);
}
int ResolvHWrapper::res_nsearch(res_state s, const char *hostname, int cls,
int type, u_char *buf, int bufsz) {
return ::res_nsearch(s, hostname, cls, type, buf, bufsz);
}
#else
int ResolvHWrapper::res_query(const char *hostname, int cls,
int type, u_char *buf, int bufsz) {
return ::res_query(hostname, cls, type, buf, bufsz);
}
int ResolvHWrapper::res_search(const char *hostname, int cls,
int type, u_char *buf, int bufsz) {
return ::res_search(hostname, cls, type, buf, bufsz);
}
#endif
DNSResolver::~DNSResolver()
{
#ifdef HAVE_RES_NQUERY
for (auto iter = states.begin(); iter != states.end(); ++iter) {
struct __res_state *s = *iter;
delete s;
}
#endif
delete resolv_h;
}
#ifdef HAVE_RES_NQUERY
int DNSResolver::get_state(CephContext *cct, res_state *ps)
{
lock.lock();
if (!states.empty()) {
res_state s = states.front();
states.pop_front();
lock.unlock();
*ps = s;
return 0;
}
lock.unlock();
struct __res_state *s = new struct __res_state;
s->options = 0;
if (res_ninit(s) < 0) {
delete s;
lderr(cct) << "ERROR: failed to call res_ninit()" << dendl;
return -EINVAL;
}
*ps = s;
return 0;
}
void DNSResolver::put_state(res_state s)
{
std::lock_guard l(lock);
states.push_back(s);
}
#endif
int DNSResolver::resolve_cname(CephContext *cct, const string& hostname,
string *cname, bool *found)
{
*found = false;
#ifdef HAVE_RES_NQUERY
res_state res;
int r = get_state(cct, &res);
if (r < 0) {
return r;
}
auto put_state = make_scope_guard([res, this] {
this->put_state(res);
});
#endif
#define LARGE_ENOUGH_DNS_BUFSIZE 1024
unsigned char buf[LARGE_ENOUGH_DNS_BUFSIZE];
#define MAX_FQDN_SIZE 255
char host[MAX_FQDN_SIZE + 1];
const char *origname = hostname.c_str();
unsigned char *pt, *answer;
unsigned char *answend;
int len;
#ifdef HAVE_RES_NQUERY
len = resolv_h->res_nquery(res, origname, ns_c_in, ns_t_cname, buf, sizeof(buf));
#else
{
# ifndef HAVE_THREAD_SAFE_RES_QUERY
std::lock_guard l(lock);
# endif
len = resolv_h->res_query(origname, ns_c_in, ns_t_cname, buf, sizeof(buf));
}
#endif
if (len < 0) {
lderr(cct) << "res_query() failed" << dendl;
return 0;
}
answer = buf;
pt = answer + NS_HFIXEDSZ;
answend = answer + len;
/* read query */
if ((len = dn_expand(answer, answend, pt, host, sizeof(host))) < 0) {
lderr(cct) << "ERROR: dn_expand() failed" << dendl;
return -EINVAL;
}
pt += len;
if (pt + 4 > answend) {
lderr(cct) << "ERROR: bad reply" << dendl;
return -EIO;
}
int type;
NS_GET16(type, pt);
if (type != ns_t_cname) {
lderr(cct) << "ERROR: failed response type: type=" << type <<
" (was expecting " << ns_t_cname << ")" << dendl;
return -EIO;
}
pt += NS_INT16SZ; /* class */
/* read answer */
if ((len = dn_expand(answer, answend, pt, host, sizeof(host))) < 0) {
return 0;
}
pt += len;
ldout(cct, 20) << "name=" << host << dendl;
if (pt + 10 > answend) {
lderr(cct) << "ERROR: bad reply" << dendl;
return -EIO;
}
NS_GET16(type, pt);
pt += NS_INT16SZ; /* class */
pt += NS_INT32SZ; /* ttl */
pt += NS_INT16SZ; /* size */
if ((len = dn_expand(answer, answend, pt, host, sizeof(host))) < 0) {
return 0;
}
ldout(cct, 20) << "cname host=" << host << dendl;
*cname = host;
*found = true;
return 0;
}
int DNSResolver::resolve_ip_addr(CephContext *cct, const string& hostname,
entity_addr_t *addr) {
#ifdef HAVE_RES_NQUERY
res_state res;
int r = get_state(cct, &res);
if (r < 0) {
return r;
}
auto put_state = make_scope_guard([res, this] {
this->put_state(res);
});
return this->resolve_ip_addr(cct, &res, hostname, addr);
#else
return this->resolve_ip_addr(cct, NULL, hostname, addr);
#endif
}
int DNSResolver::resolve_ip_addr(CephContext *cct, res_state *res, const string& hostname,
entity_addr_t *addr) {
u_char nsbuf[NS_PACKETSZ];
int len;
int family = cct->_conf->ms_bind_ipv6 ? AF_INET6 : AF_INET;
int type = cct->_conf->ms_bind_ipv6 ? ns_t_aaaa : ns_t_a;
#ifdef HAVE_RES_NQUERY
len = resolv_h->res_nquery(*res, hostname.c_str(), ns_c_in, type, nsbuf, sizeof(nsbuf));
#else
{
# ifndef HAVE_THREAD_SAFE_RES_QUERY
std::lock_guard l(lock);
# endif
len = resolv_h->res_query(hostname.c_str(), ns_c_in, type, nsbuf, sizeof(nsbuf));
}
#endif
if (len < 0) {
lderr(cct) << "res_query() failed" << dendl;
return len;
}
else if (len == 0) {
ldout(cct, 20) << "no address found for hostname " << hostname << dendl;
return -1;
}
ns_msg handle;
ns_initparse(nsbuf, len, &handle);
if (ns_msg_count(handle, ns_s_an) == 0) {
ldout(cct, 20) << "no address found for hostname " << hostname << dendl;
return -1;
}
ns_rr rr;
int r;
if ((r = ns_parserr(&handle, ns_s_an, 0, &rr)) < 0) {
lderr(cct) << "error while parsing DNS record" << dendl;
return r;
}
char addr_buf[64];
// FIPS zeroization audit 20191115: this memset is not security related.
memset(addr_buf, 0, sizeof(addr_buf));
inet_ntop(family, ns_rr_rdata(rr), addr_buf, sizeof(addr_buf));
if (!addr->parse(addr_buf)) {
lderr(cct) << "failed to parse address '" << (const char *)ns_rr_rdata(rr)
<< "'" << dendl;
return -1;
}
return 0;
}
int DNSResolver::resolve_srv_hosts(CephContext *cct, const string& service_name,
const SRV_Protocol trans_protocol,
map<string, DNSResolver::Record> *srv_hosts) {
return this->resolve_srv_hosts(cct, service_name, trans_protocol, "", srv_hosts);
}
int DNSResolver::resolve_srv_hosts(CephContext *cct, const string& service_name,
const SRV_Protocol trans_protocol, const string& domain,
map<string, DNSResolver::Record> *srv_hosts) {
#ifdef HAVE_RES_NQUERY
res_state res;
int r = get_state(cct, &res);
if (r < 0) {
return r;
}
auto put_state = make_scope_guard([res, this] {
this->put_state(res);
});
#endif
u_char nsbuf[NS_PACKETSZ];
int num_hosts;
string proto_str = srv_protocol_to_str(trans_protocol);
string query_str = "_"+service_name+"._"+proto_str+(domain.empty() ? ""
: "."+domain);
int len;
#ifdef HAVE_RES_NQUERY
len = resolv_h->res_nsearch(res, query_str.c_str(), ns_c_in, ns_t_srv, nsbuf,
sizeof(nsbuf));
#else
{
# ifndef HAVE_THREAD_SAFE_RES_QUERY
std::lock_guard l(lock);
# endif
len = resolv_h->res_search(query_str.c_str(), ns_c_in, ns_t_srv, nsbuf,
sizeof(nsbuf));
}
#endif
if (len < 0) {
lderr(cct) << "failed for service " << query_str << dendl;
return len;
}
else if (len == 0) {
ldout(cct, 20) << "No hosts found for service " << query_str << dendl;
return 0;
}
ns_msg handle;
ns_initparse(nsbuf, len, &handle);
num_hosts = ns_msg_count (handle, ns_s_an);
if (num_hosts == 0) {
ldout(cct, 20) << "No hosts found for service " << query_str << dendl;
return 0;
}
ns_rr rr;
char full_target[NS_MAXDNAME];
for (int i = 0; i < num_hosts; i++) {
int r;
if ((r = ns_parserr(&handle, ns_s_an, i, &rr)) < 0) {
lderr(cct) << "Error while parsing DNS record" << dendl;
return r;
}
string full_srv_name = ns_rr_name(rr);
string protocol = "_" + proto_str;
string srv_domain = full_srv_name.substr(full_srv_name.find(protocol)
+ protocol.length());
auto rdata = ns_rr_rdata(rr);
uint16_t priority = ns_get16(rdata); rdata += NS_INT16SZ;
uint16_t weight = ns_get16(rdata); rdata += NS_INT16SZ;
uint16_t port = ns_get16(rdata); rdata += NS_INT16SZ;
// FIPS zeroization audit 20191115: this memset is not security related.
memset(full_target, 0, sizeof(full_target));
ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
rdata, full_target, sizeof(full_target));
entity_addr_t addr;
#ifdef HAVE_RES_NQUERY
r = this->resolve_ip_addr(cct, &res, full_target, &addr);
#else
r = this->resolve_ip_addr(cct, NULL, full_target, &addr);
#endif
if (r == 0) {
addr.set_port(port);
string target = full_target;
auto end = target.find(srv_domain);
if (end == target.npos) {
lderr(cct) << "resolved target not in search domain: "
<< target << " / " << srv_domain << dendl;
return -EINVAL;
}
target = target.substr(0, end);
(*srv_hosts)[target] = {priority, weight, addr};
}
}
return 0;
}
}
| 9,264 | 23.839142 | 91 | cc |
null | ceph-main/src/common/dns_resolve.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 SUSE LINUX GmbH
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_DNS_RESOLVE_H
#define CEPH_DNS_RESOLVE_H
#include <netinet/in.h>
#ifndef _WIN32
#include <resolv.h>
#endif
#include "common/ceph_mutex.h"
#include "msg/msg_types.h" // for entity_addr_t
namespace ceph {
/**
* this class is used to facilitate the testing of
* resolv.h functions.
*/
class ResolvHWrapper {
public:
virtual ~ResolvHWrapper() {}
#ifdef HAVE_RES_NQUERY
virtual int res_nquery(res_state s, const char *hostname, int cls, int type,
u_char *buf, int bufsz);
virtual int res_nsearch(res_state s, const char *hostname, int cls, int type,
u_char *buf, int bufsz);
#else
virtual int res_query(const char *hostname, int cls, int type,
u_char *buf, int bufsz);
virtual int res_search(const char *hostname, int cls, int type,
u_char *buf, int bufsz);
#endif
};
/**
* @class DNSResolver
*
* This is a singleton class that exposes the functionality of DNS querying.
*/
class DNSResolver {
public:
// singleton declaration
static DNSResolver *get_instance()
{
static DNSResolver instance;
return &instance;
}
DNSResolver(DNSResolver const&) = delete;
void operator=(DNSResolver const&) = delete;
// this function is used by the unit test
static DNSResolver *get_instance(ResolvHWrapper *resolv_wrapper) {
DNSResolver *resolv = DNSResolver::get_instance();
delete resolv->resolv_h;
resolv->resolv_h = resolv_wrapper;
return resolv;
}
enum class SRV_Protocol {
TCP, UDP
};
struct Record {
uint16_t priority;
uint16_t weight;
entity_addr_t addr;
};
int resolve_cname(CephContext *cct, const std::string& hostname,
std::string *cname, bool *found);
/**
* Resolves the address given a hostname.
*
* @param hostname the hostname to resolved
* @param[out] addr the hostname's address
* @returns 0 on success, negative error code on failure
*/
int resolve_ip_addr(CephContext *cct, const std::string& hostname,
entity_addr_t *addr);
/**
* Returns the list of hostnames and addresses that provide a given
* service configured as DNS SRV records.
*
* @param service_name the service name
* @param trans_protocol the IP protocol used by the service (TCP or UDP)
* @param[out] srv_hosts the hostname to address map of available hosts
* providing the service. If no host exists the map is not
* changed.
* @returns 0 on success, negative error code on failure
*/
int resolve_srv_hosts(CephContext *cct, const std::string& service_name,
const SRV_Protocol trans_protocol, std::map<std::string, Record> *srv_hosts);
/**
* Returns the list of hostnames and addresses that provide a given
* service configured as DNS SRV records.
*
* @param service_name the service name
* @param trans_protocol the IP protocol used by the service (TCP or UDP)
* @param domain the domain of the service
* @param[out] srv_hosts the hostname to address map of available hosts
* providing the service. If no host exists the map is not
* changed.
* @returns 0 on success, negative error code on failure
*/
int resolve_srv_hosts(CephContext *cct, const std::string& service_name,
const SRV_Protocol trans_protocol, const std::string& domain,
std::map<std::string, Record> *srv_hosts);
private:
DNSResolver() { resolv_h = new ResolvHWrapper(); }
~DNSResolver();
ceph::mutex lock = ceph::make_mutex("DNSResolver::lock");
ResolvHWrapper *resolv_h;
#ifdef HAVE_RES_NQUERY
std::list<res_state> states;
int get_state(CephContext *cct, res_state *ps);
void put_state(res_state s);
#endif
#ifndef _WIN32
/* this private function allows to reuse the res_state structure used
* by other function of this class
*/
int resolve_ip_addr(CephContext *cct, res_state *res,
const std::string& hostname, entity_addr_t *addr);
#endif
std::string srv_protocol_to_str(SRV_Protocol proto) {
switch (proto) {
case SRV_Protocol::TCP:
return "tcp";
case SRV_Protocol::UDP:
return "udp";
}
return "";
}
};
}
#endif
| 4,743 | 27.238095 | 85 | h |
null | ceph-main/src/common/dout.cc |
#include <iostream>
void dout_emergency(const char * const str)
{
std::cerr << str;
std::cerr.flush();
}
void dout_emergency(const std::string &str)
{
std::cerr << str;
std::cerr.flush();
}
| 201 | 12.466667 | 43 | cc |
null | ceph-main/src/common/dout.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-2010 Sage Weil <[email protected]>
* 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_DOUT_H
#define CEPH_DOUT_H
#include <type_traits>
#include "include/ceph_assert.h"
#include "include/common_fwd.h"
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
#include <seastar/util/log.hh>
#include "crimson/common/log.h"
#include "crimson/common/config_proxy.h"
#else
#include "global/global_context.h"
#include "common/ceph_context.h"
#include "common/config.h"
#include "common/likely.h"
#include "common/Clock.h"
#include "log/Log.h"
#endif
extern void dout_emergency(const char * const str);
extern void dout_emergency(const std::string &str);
// intentionally conflict with endl
class _bad_endl_use_dendl_t { public: _bad_endl_use_dendl_t(int) {} };
static const _bad_endl_use_dendl_t endl = 0;
inline std::ostream& operator<<(std::ostream& out, _bad_endl_use_dendl_t) {
ceph_abort_msg("you are using the wrong endl.. use std::endl or dendl");
return out;
}
class DoutPrefixProvider {
public:
virtual std::ostream& gen_prefix(std::ostream& out) const = 0;
virtual CephContext *get_cct() const = 0;
virtual unsigned get_subsys() const = 0;
virtual ~DoutPrefixProvider() {}
};
inline std::ostream &operator<<(
std::ostream &lhs, const DoutPrefixProvider &dpp) {
return dpp.gen_prefix(lhs);
}
#if FMT_VERSION >= 90000
template <> struct fmt::formatter<DoutPrefixProvider> : fmt::ostream_formatter {};
#endif
// a prefix provider with empty prefix
class NoDoutPrefix : public DoutPrefixProvider {
CephContext *const cct;
const unsigned subsys;
public:
NoDoutPrefix(CephContext *cct, unsigned subsys) : cct(cct), subsys(subsys) {}
std::ostream& gen_prefix(std::ostream& out) const override { return out; }
CephContext *get_cct() const override { return cct; }
unsigned get_subsys() const override { return subsys; }
};
// a prefix provider with static (const char*) prefix
class DoutPrefix : public NoDoutPrefix {
const char *const prefix;
public:
DoutPrefix(CephContext *cct, unsigned subsys, const char *prefix)
: NoDoutPrefix(cct, subsys), prefix(prefix) {}
std::ostream& gen_prefix(std::ostream& out) const override {
return out << prefix;
}
};
// a prefix provider that composes itself on top of another
class DoutPrefixPipe : public DoutPrefixProvider {
const DoutPrefixProvider& dpp;
public:
DoutPrefixPipe(const DoutPrefixProvider& dpp) : dpp(dpp) {}
std::ostream& gen_prefix(std::ostream& out) const override final {
dpp.gen_prefix(out);
add_prefix(out);
return out;
}
CephContext *get_cct() const override { return dpp.get_cct(); }
unsigned get_subsys() const override { return dpp.get_subsys(); }
virtual void add_prefix(std::ostream& out) const = 0;
};
// helpers
namespace ceph::dout {
template<typename T>
struct dynamic_marker_t {
T value;
// constexpr ctor isn't needed as it's an aggregate type
constexpr operator T() const { return value; }
};
template<typename T>
constexpr dynamic_marker_t<T> need_dynamic(T&& t) {
return dynamic_marker_t<T>{ std::forward<T>(t) };
}
template<typename T>
struct is_dynamic : public std::false_type {};
template<typename T>
struct is_dynamic<dynamic_marker_t<T>> : public std::true_type {};
} // ceph::dout
// generic macros
#define dout_prefix *_dout
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
#define dout_impl(cct, sub, v) \
do { \
if (crimson::common::local_conf()->subsys.should_gather(sub, v)) { \
seastar::logger& _logger = crimson::get_logger(sub); \
const auto _lv = v; \
std::ostringstream _out; \
std::ostream* _dout = &_out;
#define dendl_impl \
""; \
_logger.log(crimson::to_log_level(_lv), \
"{}", _out.str().c_str()); \
} \
} while (0)
#else
#define dout_impl(cct, sub, v) \
do { \
const bool should_gather = [&](const auto cctX) { \
if constexpr (ceph::dout::is_dynamic<decltype(sub)>::value || \
ceph::dout::is_dynamic<decltype(v)>::value) { \
return cctX->_conf->subsys.should_gather(sub, v); \
} else { \
/* The parentheses are **essential** because commas in angle \
* brackets are NOT ignored on macro expansion! A language's \
* limitation, sorry. */ \
return (cctX->_conf->subsys.template should_gather<sub, v>()); \
} \
}(cct); \
\
if (should_gather) { \
ceph::logging::MutableEntry _dout_e(v, sub); \
static_assert(std::is_convertible<decltype(&*cct), \
CephContext* >::value, \
"provided cct must be compatible with CephContext*"); \
auto _dout_cct = cct; \
std::ostream* _dout = &_dout_e.get_ostream();
#define dendl_impl std::flush; \
_dout_cct->_log->submit_entry(std::move(_dout_e)); \
} \
} while (0)
#endif // WITH_SEASTAR
#define lsubdout(cct, sub, v) dout_impl(cct, ceph_subsys_##sub, v) dout_prefix
#define ldout(cct, v) dout_impl(cct, dout_subsys, v) dout_prefix
#define lderr(cct) dout_impl(cct, ceph_subsys_, -1) dout_prefix
#define ldpp_subdout(dpp, sub, v) \
if (decltype(auto) pdpp = (dpp); pdpp) /* workaround -Wnonnull-compare for 'this' */ \
dout_impl(pdpp->get_cct(), ceph_subsys_##sub, v) \
pdpp->gen_prefix(*_dout)
#define ldpp_dout(dpp, v) \
if (decltype(auto) pdpp = (dpp); pdpp) /* workaround -Wnonnull-compare for 'this' */ \
dout_impl(pdpp->get_cct(), ceph::dout::need_dynamic(pdpp->get_subsys()), v) \
pdpp->gen_prefix(*_dout)
#define lgeneric_subdout(cct, sub, v) dout_impl(cct, ceph_subsys_##sub, v) *_dout
#define lgeneric_dout(cct, v) dout_impl(cct, ceph_subsys_, v) *_dout
#define lgeneric_derr(cct) dout_impl(cct, ceph_subsys_, -1) *_dout
#define ldlog_p1(cct, sub, lvl) \
(cct->_conf->subsys.should_gather((sub), (lvl)))
#define dendl dendl_impl
#endif
| 6,715 | 33.091371 | 88 | h |
null | ceph-main/src/common/dummy.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 Inktank, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
/*
* A dummy file with a .cc extension to make autotools link
* ceph_test_librbd_fsx with a C++ linker. An approach w/o a physical
* dummy.cc recommended in 8.3.5 Libtool Convenience Libraries works,
* but breaks 'make tags' and friends.
*/
| 652 | 30.095238 | 71 | cc |
null | ceph-main/src/common/entity_name.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/entity_name.h"
#include "common/ceph_strings.h"
#include <sstream>
using std::string;
const std::array<EntityName::str_to_entity_type_t, 6> EntityName::STR_TO_ENTITY_TYPE = {{
{ CEPH_ENTITY_TYPE_AUTH, "auth" },
{ CEPH_ENTITY_TYPE_MON, "mon" },
{ CEPH_ENTITY_TYPE_OSD, "osd" },
{ CEPH_ENTITY_TYPE_MDS, "mds" },
{ CEPH_ENTITY_TYPE_MGR, "mgr" },
{ CEPH_ENTITY_TYPE_CLIENT, "client" },
}};
const std::string& EntityName::
to_str() const
{
return type_id;
}
const char* EntityName::
to_cstr() const
{
return type_id.c_str();
}
bool EntityName::
from_str(std::string_view s)
{
size_t pos = s.find('.');
if (pos == string::npos)
return false;
auto type_ = s.substr(0, pos);
auto id_ = s.substr(pos + 1);
if (set(type_, id_))
return false;
return true;
}
void EntityName::
set(uint32_t type_, std::string_view id_)
{
type = type_;
id = id_;
if (type) {
std::ostringstream oss;
oss << ceph_entity_type_name(type_) << "." << id_;
type_id = oss.str();
} else {
type_id.clear();
}
}
int EntityName::
set(std::string_view type_, std::string_view id_)
{
uint32_t t = str_to_ceph_entity_type(type_);
if (t == CEPH_ENTITY_TYPE_ANY)
return -EINVAL;
set(t, id_);
return 0;
}
void EntityName::
set_type(uint32_t type_)
{
set(type_, id);
}
int EntityName::
set_type(std::string_view type_)
{
return set(type_, id);
}
void EntityName::
set_id(std::string_view id_)
{
set(type, id_);
}
void EntityName::set_name(entity_name_t n)
{
char s[40];
sprintf(s, "%lld", (long long)n.num());
set(n.type(), s);
}
const char* EntityName::
get_type_str() const
{
return ceph_entity_type_name(type);
}
std::string_view EntityName::
get_type_name() const
{
return ceph_entity_type_name(type);
}
const std::string &EntityName::
get_id() const
{
return id;
}
bool EntityName::
has_default_id() const
{
return (id == "admin");
}
std::string EntityName::
get_valid_types_as_str()
{
std::ostringstream out;
size_t i;
for (i = 0; i < STR_TO_ENTITY_TYPE.size(); ++i) {
if (i > 0) {
out << ", ";
}
out << STR_TO_ENTITY_TYPE[i].str;
}
return out.str();
}
uint32_t EntityName::str_to_ceph_entity_type(std::string_view s)
{
size_t i;
for (i = 0; i < STR_TO_ENTITY_TYPE.size(); ++i) {
if (s == STR_TO_ENTITY_TYPE[i].str)
return STR_TO_ENTITY_TYPE[i].type;
}
return CEPH_ENTITY_TYPE_ANY;
}
bool operator<(const EntityName& a, const EntityName& b)
{
return (a.type < b.type) || (a.type == b.type && a.id < b.id);
}
std::ostream& operator<<(std::ostream& out, const EntityName& n)
{
return out << n.to_str();
}
| 3,054 | 17.403614 | 89 | cc |
null | ceph-main/src/common/entity_name.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_ENTITY_NAME_H
#define CEPH_COMMON_ENTITY_NAME_H
#include <string_view>
#include <ifaddrs.h>
#include "msg/msg_types.h"
/* Represents a Ceph entity name.
*
* For example, mds.0 is the name of the first metadata server.
* client
*/
struct EntityName
{
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
encode(type, bl);
encode(id, bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
using ceph::decode;
uint32_t type_;
std::string id_;
decode(type_, bl);
decode(id_, bl);
set(type_, id_);
}
const std::string& to_str() const;
const char *to_cstr() const;
bool from_str(std::string_view s);
void set(uint32_t type_, std::string_view id_);
int set(std::string_view type_, std::string_view id_);
void set_type(uint32_t type_);
int set_type(std::string_view type);
void set_id(std::string_view id_);
void set_name(entity_name_t n);
const char* get_type_str() const;
uint32_t get_type() const { return type; }
bool is_osd() const { return get_type() == CEPH_ENTITY_TYPE_OSD; }
bool is_mgr() const { return get_type() == CEPH_ENTITY_TYPE_MGR; }
bool is_mds() const { return get_type() == CEPH_ENTITY_TYPE_MDS; }
bool is_client() const { return get_type() == CEPH_ENTITY_TYPE_CLIENT; }
bool is_mon() const { return get_type() == CEPH_ENTITY_TYPE_MON; }
std::string_view get_type_name() const;
const std::string &get_id() const;
bool has_default_id() const;
static std::string get_valid_types_as_str();
static uint32_t str_to_ceph_entity_type(std::string_view);
friend bool operator<(const EntityName& a, const EntityName& b);
friend std::ostream& operator<<(std::ostream& out, const EntityName& n);
bool operator==(const EntityName& rhs) const noexcept {
return type == rhs.type && id == rhs.id;
}
private:
struct str_to_entity_type_t {
uint32_t type;
const char *str;
};
static const std::array<str_to_entity_type_t, 6> STR_TO_ENTITY_TYPE;
uint32_t type = 0;
std::string id;
std::string type_id;
};
WRITE_CLASS_ENCODER(EntityName)
#endif
| 2,519 | 26.096774 | 74 | h |
null | ceph-main/src/common/environment.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/environment.h"
#include <stdlib.h>
#include <strings.h>
bool get_env_bool(const char *key)
{
const char *val = getenv(key);
if (!val)
return false;
if (strcasecmp(val, "off") == 0)
return false;
if (strcasecmp(val, "no") == 0)
return false;
if (strcasecmp(val, "false") == 0)
return false;
if (strcasecmp(val, "0") == 0)
return false;
return true;
}
int get_env_int(const char *key)
{
const char *val = getenv(key);
if (!val)
return 0;
int v = atoi(val);
return v;
}
| 942 | 20.431818 | 70 | cc |
null | ceph-main/src/common/environment.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_ENVIRONMENT_H
#define CEPH_COMMON_ENVIRONMENT_H
extern bool get_env_bool(const char *key);
extern int get_env_int(const char *key);
#endif
| 570 | 24.954545 | 70 | h |
null | ceph-main/src/common/errno.cc | #include "common/errno.h"
#include "acconfig.h"
#include "include/compat.h"
#include <sstream>
#include <string.h>
std::string cpp_strerror(int err)
{
char buf[128];
char *errmsg;
if (err < 0)
err = -err;
std::ostringstream oss;
errmsg = ceph_strerror_r(err, buf, sizeof(buf));
oss << "(" << err << ") " << errmsg;
return oss.str();
}
| 359 | 14.652174 | 50 | cc |
null | ceph-main/src/common/errno.h | #ifndef CEPH_ERRNO_H
#define CEPH_ERRNO_H
#include <string>
/* Return a given error code as a string */
std::string cpp_strerror(int err);
#ifdef _WIN32
// While cpp_strerror handles errors defined in errno.h, this one
// accepts standard Windows error codes.
std::string win32_strerror(int err);
std::string win32_lasterror_str();
#endif /* _WIN32 */
#endif
| 363 | 20.411765 | 65 | h |
null | ceph-main/src/common/error_code.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 Red Hat, Inc. <[email protected]>
*
* Author: Adam C. Emerson <[email protected]>
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 2.1, as published by the Free Software Foundation. See file
* COPYING.
*/
#include <exception>
#include "common/error_code.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
using boost::system::error_category;
using boost::system::error_condition;
using boost::system::generic_category;
using boost::system::system_category;
namespace ceph {
// A category for error conditions particular to Ceph
class ceph_error_category : public converting_category {
public:
ceph_error_category(){}
const char* name() const noexcept override;
using converting_category::message;
std::string message(int ev) const override;
const char* message(int ev, char*, std::size_t) const noexcept override;
using converting_category::equivalent;
bool equivalent(const boost::system::error_code& c,
int ev) const noexcept override;
int from_code(int ev) const noexcept override;
};
const char* ceph_error_category::name() const noexcept {
return "ceph";
}
const char* ceph_error_category::message(int ev, char*,
std::size_t) const noexcept {
if (ev == 0)
return "No error";
switch (static_cast<errc>(ev)) {
case errc::not_in_map:
return "Map does not contain requested entry.";
case errc::does_not_exist:
return "Item does not exist";
case errc::failure:
return "An internal fault or inconsistency occurred";
case errc::exists:
return "Already exists";
case errc::limit_exceeded:
return "Attempt to use too much";
case errc::auth:
return "Authentication error";
case errc::conflict:
return "Conflict detected or precondition failed";
}
return "Unknown error.";
}
std::string ceph_error_category::message(int ev) const {
return message(ev, nullptr, 0);
}
bool ceph_error_category::equivalent(const boost::system::error_code& c,
int ev) const noexcept {
if (c.category() == system_category()) {
if (c.value() == boost::system::errc::no_such_file_or_directory) {
if (ev == static_cast<int>(errc::not_in_map) ||
ev == static_cast<int>(errc::does_not_exist)) {
// Blargh. A bunch of stuff returns ENOENT now, so just to be safe.
return true;
}
}
if (c.value() == boost::system::errc::io_error) {
if (ev == static_cast<int>(errc::failure)) {
return true;
}
}
if (c.value() == boost::system::errc::file_exists) {
if (ev == static_cast<int>(errc::exists)) {
return true;
}
}
if (c.value() == boost::system::errc::no_space_on_device ||
c.value() == boost::system::errc::invalid_argument) {
if (ev == static_cast<int>(errc::limit_exceeded)) {
return true;
}
}
if (c.value() == boost::system::errc::operation_not_permitted) {
if (ev == static_cast<int>(ceph::errc::conflict)) {
return true;
}
}
}
return false;
}
int ceph_error_category::from_code(int ev) const noexcept {
if (ev == 0)
return 0;
switch (static_cast<errc>(ev)) {
case errc::not_in_map:
case errc::does_not_exist:
// What we use now.
return -ENOENT;
case errc::failure:
return -EIO;
case errc::exists:
return -EEXIST;
case errc::limit_exceeded:
return -EIO;
case errc::auth:
return -EACCES;
case errc::conflict:
return -EINVAL;
}
return -EDOM;
}
const error_category& ceph_category() noexcept {
static const ceph_error_category c;
return c;
}
// This is part of the glue for hooking new code to old. Since
// Context* and other things give us integer codes from errno, wrap
// them in an error_code.
[[nodiscard]] boost::system::error_code to_error_code(int ret) noexcept
{
if (ret == 0)
return {};
return { std::abs(ret), boost::system::system_category() };
}
// This is more complicated. For the case of categories defined
// elsewhere, we have to convert everything here.
[[nodiscard]] int from_error_code(boost::system::error_code e) noexcept
{
if (!e)
return 0;
auto c = dynamic_cast<const converting_category*>(&e.category());
// For categories we define
if (c)
return c->from_code(e.value());
// For categories matching values of errno
if (e.category() == boost::system::system_category() ||
e.category() == boost::system::generic_category() ||
// ASIO uses the system category for these and matches system
// error values.
e.category() == boost::asio::error::get_netdb_category() ||
e.category() == boost::asio::error::get_addrinfo_category())
return -e.value();
if (e.category() == boost::asio::error::get_misc_category()) {
// These values are specific to asio
switch (e.value()) {
case boost::asio::error::already_open:
return -EIO;
case boost::asio::error::eof:
return -EIO;
case boost::asio::error::not_found:
return -ENOENT;
case boost::asio::error::fd_set_failure:
return -EINVAL;
}
}
// Add any other categories we use here.
// Marcus likes this as a sentinel for 'Error code? What error code?'
return -EDOM;
}
}
#pragma GCC diagnostic pop
#pragma clang diagnostic pop
| 5,545 | 27.152284 | 74 | cc |
null | ceph-main/src/common/error_code.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 Red Hat, Inc. <[email protected]>
*
* Author: Adam C. Emerson <[email protected]>
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 2.1, as published by the Free Software Foundation. See file
* COPYING.
*/
#ifndef COMMON_CEPH_ERROR_CODE
#define COMMON_CEPH_ERROR_CODE
#include <netdb.h>
#include <boost/system/error_code.hpp>
#include <boost/asio.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
namespace ceph {
// This is for error categories we define, so we can specify the
// equivalent integral value at the point of definition.
class converting_category : public boost::system::error_category {
public:
virtual int from_code(int code) const noexcept = 0;
};
const boost::system::error_category& ceph_category() noexcept;
enum class errc {
not_in_map = 1, // The requested item was not found in the map
does_not_exist, // Item does not exist
failure, // An internal fault or inconsistency
exists, // Already exists
limit_exceeded, // Attempting to use too much of something
auth, // May not be an auth failure. It could be that the
// preconditions to attempt auth failed.
conflict, // Conflict or precondition failure
};
}
namespace boost::system {
template<>
struct is_error_condition_enum<::ceph::errc> {
static const bool value = true;
};
template<>
struct is_error_code_enum<::ceph::errc> {
static const bool value = false;
};
}
namespace ceph {
// explicit conversion:
inline boost::system::error_code make_error_code(errc e) noexcept {
return { static_cast<int>(e), ceph_category() };
}
// implicit conversion:
inline boost::system::error_condition make_error_condition(errc e) noexcept {
return { static_cast<int>(e), ceph_category() };
}
[[nodiscard]] boost::system::error_code to_error_code(int ret) noexcept;
[[nodiscard]] int from_error_code(boost::system::error_code e) noexcept;
}
#pragma GCC diagnostic pop
#pragma clang diagnostic pop
// Moved here from buffer.h so librados doesn't gain a dependency on
// Boost.System
namespace ceph::buffer {
inline namespace v15_2_0 {
const boost::system::error_category& buffer_category() noexcept;
enum class errc { bad_alloc = 1,
end_of_buffer,
malformed_input };
}
}
namespace boost::system {
template<>
struct is_error_code_enum<::ceph::buffer::errc> {
static const bool value = true;
};
template<>
struct is_error_condition_enum<::ceph::buffer::errc> {
static const bool value = false;
};
}
namespace ceph::buffer {
inline namespace v15_2_0 {
// implicit conversion:
inline boost::system::error_code make_error_code(errc e) noexcept {
return { static_cast<int>(e), buffer_category() };
}
// explicit conversion:
inline boost::system::error_condition
make_error_condition(errc e) noexcept {
return { static_cast<int>(e), buffer_category() };
}
struct error : boost::system::system_error {
using system_error::system_error;
};
struct bad_alloc : public error {
bad_alloc() : error(errc::bad_alloc) {}
bad_alloc(const char* what_arg) : error(errc::bad_alloc, what_arg) {}
bad_alloc(const std::string& what_arg) : error(errc::bad_alloc, what_arg) {}
};
struct end_of_buffer : public error {
end_of_buffer() : error(errc::end_of_buffer) {}
end_of_buffer(const char* what_arg) : error(errc::end_of_buffer, what_arg) {}
end_of_buffer(const std::string& what_arg)
: error(errc::end_of_buffer, what_arg) {}
};
struct malformed_input : public error {
malformed_input() : error(errc::malformed_input) {}
malformed_input(const char* what_arg)
: error(errc::malformed_input, what_arg) {}
malformed_input(const std::string& what_arg)
: error(errc::malformed_input, what_arg) {}
};
struct error_code : public error {
error_code(int r) : error(-r, boost::system::system_category()) {}
error_code(int r, const char* what_arg)
: error(-r, boost::system::system_category(), what_arg) {}
error_code(int r, const std::string& what_arg)
: error(-r, boost::system::system_category(), what_arg) {}
};
}
}
#endif // COMMON_CEPH_ERROR_CODE
| 4,378 | 27.809211 | 79 | h |
null | ceph-main/src/common/escape.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/escape.h"
#include <stdio.h>
#include <string.h>
#include <iomanip>
#include <boost/optional.hpp>
/*
* Some functions for escaping RGW responses
*/
/* Static string length */
#define SSTRL(x) ((sizeof(x)/sizeof(x[0])) - 1)
#define LESS_THAN_XESCAPE "<"
#define AMPERSAND_XESCAPE "&"
#define GREATER_THAN_XESCAPE ">"
#define SGL_QUOTE_XESCAPE "'"
#define DBL_QUOTE_XESCAPE """
size_t escape_xml_attr_len(const char *buf)
{
const char *b;
size_t ret = 0;
for (b = buf; *b; ++b) {
unsigned char c = *b;
switch (c) {
case '<':
ret += SSTRL(LESS_THAN_XESCAPE);
break;
case '&':
ret += SSTRL(AMPERSAND_XESCAPE);
break;
case '>':
ret += SSTRL(GREATER_THAN_XESCAPE);
break;
case '\'':
ret += SSTRL(SGL_QUOTE_XESCAPE);
break;
case '"':
ret += SSTRL(DBL_QUOTE_XESCAPE);
break;
default:
// Escape control characters.
if (((c < 0x20) && (c != 0x09) && (c != 0x0a)) ||
(c == 0x7f)) {
ret += 6;
}
else {
ret++;
}
}
}
// leave room for null terminator
ret++;
return ret;
}
void escape_xml_attr(const char *buf, char *out)
{
char *o = out;
const char *b;
for (b = buf; *b; ++b) {
unsigned char c = *b;
switch (c) {
case '<':
memcpy(o, LESS_THAN_XESCAPE, SSTRL(LESS_THAN_XESCAPE));
o += SSTRL(LESS_THAN_XESCAPE);
break;
case '&':
memcpy(o, AMPERSAND_XESCAPE, SSTRL(AMPERSAND_XESCAPE));
o += SSTRL(AMPERSAND_XESCAPE);
break;
case '>':
memcpy(o, GREATER_THAN_XESCAPE, SSTRL(GREATER_THAN_XESCAPE));
o += SSTRL(GREATER_THAN_XESCAPE);
break;
case '\'':
memcpy(o, SGL_QUOTE_XESCAPE, SSTRL(SGL_QUOTE_XESCAPE));
o += SSTRL(SGL_QUOTE_XESCAPE);
break;
case '"':
memcpy(o, DBL_QUOTE_XESCAPE, SSTRL(DBL_QUOTE_XESCAPE));
o += SSTRL(DBL_QUOTE_XESCAPE);
break;
default:
// Escape control characters.
if (((c < 0x20) && (c != 0x09) && (c != 0x0a)) ||
(c == 0x7f)) {
snprintf(o, 7, "&#x%02x;", c);
o += 6;
}
else {
*o++ = c;
}
break;
}
}
// null terminator
*o = '\0';
}
// applies hex formatting on construction, restores on destruction
struct hex_formatter {
std::ostream& out;
const char old_fill;
const std::ostream::fmtflags old_flags;
explicit hex_formatter(std::ostream& out)
: out(out),
old_fill(out.fill('0')),
old_flags(out.setf(out.hex, out.basefield))
{}
~hex_formatter() {
out.fill(old_fill);
out.flags(old_flags);
}
};
std::ostream& operator<<(std::ostream& out, const xml_stream_escaper& e)
{
boost::optional<hex_formatter> fmt;
for (unsigned char c : e.str) {
switch (c) {
case '<':
out << LESS_THAN_XESCAPE;
break;
case '&':
out << AMPERSAND_XESCAPE;
break;
case '>':
out << GREATER_THAN_XESCAPE;
break;
case '\'':
out << SGL_QUOTE_XESCAPE;
break;
case '"':
out << DBL_QUOTE_XESCAPE;
break;
default:
// Escape control characters.
if (((c < 0x20) && (c != 0x09) && (c != 0x0a)) || (c == 0x7f)) {
if (!fmt) {
fmt.emplace(out); // enable hex formatting
}
out << "&#x" << std::setw(2) << static_cast<unsigned int>(c) << ';';
} else {
out << c;
}
break;
}
}
return out;
}
#define DBL_QUOTE_JESCAPE "\\\""
#define BACKSLASH_JESCAPE "\\\\"
#define TAB_JESCAPE "\\t"
#define NEWLINE_JESCAPE "\\n"
size_t escape_json_attr_len(const char *buf, size_t src_len)
{
const char *b;
size_t i, ret = 0;
for (i = 0, b = buf; i < src_len; ++i, ++b) {
unsigned char c = *b;
switch (c) {
case '"':
ret += SSTRL(DBL_QUOTE_JESCAPE);
break;
case '\\':
ret += SSTRL(BACKSLASH_JESCAPE);
break;
case '\t':
ret += SSTRL(TAB_JESCAPE);
break;
case '\n':
ret += SSTRL(NEWLINE_JESCAPE);
break;
default:
// Escape control characters.
if ((c < 0x20) || (c == 0x7f)) {
ret += 6;
}
else {
ret++;
}
}
}
// leave room for null terminator
ret++;
return ret;
}
void escape_json_attr(const char *buf, size_t src_len, char *out)
{
char *o = out;
const char *b;
size_t i;
for (i = 0, b = buf; i < src_len; ++i, ++b) {
unsigned char c = *b;
switch (c) {
case '"':
// cppcheck-suppress invalidFunctionArg
memcpy(o, DBL_QUOTE_JESCAPE, SSTRL(DBL_QUOTE_JESCAPE));
o += SSTRL(DBL_QUOTE_JESCAPE);
break;
case '\\':
// cppcheck-suppress invalidFunctionArg
memcpy(o, BACKSLASH_JESCAPE, SSTRL(BACKSLASH_JESCAPE));
o += SSTRL(BACKSLASH_JESCAPE);
break;
case '\t':
// cppcheck-suppress invalidFunctionArg
memcpy(o, TAB_JESCAPE, SSTRL(TAB_JESCAPE));
o += SSTRL(TAB_JESCAPE);
break;
case '\n':
// cppcheck-suppress invalidFunctionArg
memcpy(o, NEWLINE_JESCAPE, SSTRL(NEWLINE_JESCAPE));
o += SSTRL(NEWLINE_JESCAPE);
break;
default:
// Escape control characters.
if ((c < 0x20) || (c == 0x7f)) {
snprintf(o, 7, "\\u%04x", c);
o += 6;
}
else {
*o++ = c;
}
break;
}
}
// null terminator
*o = '\0';
}
std::ostream& operator<<(std::ostream& out, const json_stream_escaper& e)
{
boost::optional<hex_formatter> fmt;
for (unsigned char c : e.str) {
switch (c) {
case '"':
out << DBL_QUOTE_JESCAPE;
break;
case '\\':
out << BACKSLASH_JESCAPE;
break;
case '\t':
out << TAB_JESCAPE;
break;
case '\n':
out << NEWLINE_JESCAPE;
break;
default:
// Escape control characters.
if ((c < 0x20) || (c == 0x7f)) {
if (!fmt) {
fmt.emplace(out); // enable hex formatting
}
out << "\\u" << std::setw(4) << static_cast<unsigned int>(c);
} else {
out << c;
}
break;
}
}
return out;
}
| 6,180 | 20.536585 | 76 | cc |
null | ceph-main/src/common/escape.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_RGW_ESCAPE_H
#define CEPH_RGW_ESCAPE_H
#include <ostream>
#include <string_view>
/* Returns the length of a buffer that would be needed to escape 'buf'
* as an XML attribute
*/
size_t escape_xml_attr_len(const char *buf);
/* Escapes 'buf' as an XML attribute. Assumes that 'out' is at least long
* enough to fit the output. You can find out the required length by calling
* escape_xml_attr_len first.
*/
void escape_xml_attr(const char *buf, char *out);
/* Returns the length of a buffer that would be needed to escape 'buf'
* as an JSON attribute
*/
size_t escape_json_attr_len(const char *buf, size_t src_len);
/* Escapes 'buf' as an JSON attribute. Assumes that 'out' is at least long
* enough to fit the output. You can find out the required length by calling
* escape_json_attr_len first.
*/
void escape_json_attr(const char *buf, size_t src_len, char *out);
/* Note: we escape control characters. Although the XML spec doesn't actually
* require this, Amazon does it in their XML responses.
*/
// stream output operators that write escaped text without making a copy
// usage:
// std::string xml_input = ...;
// std::cout << xml_stream_escaper(xml_input) << std::endl;
struct xml_stream_escaper {
std::string_view str;
xml_stream_escaper(std::string_view str) : str(str.data(), str.size()) {}
};
std::ostream& operator<<(std::ostream& out, const xml_stream_escaper& e);
struct json_stream_escaper {
std::string_view str;
json_stream_escaper(std::string_view str) : str(str.data(), str.size()) {}
};
std::ostream& operator<<(std::ostream& out, const json_stream_escaper& e);
#endif
| 2,043 | 30.446154 | 77 | h |
null | ceph-main/src/common/event_socket.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2015 XSky <[email protected]>
*
* Author: Haomai Wang <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_EVENT_SOCKET_H
#define CEPH_COMMON_EVENT_SOCKET_H
#include <unistd.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <errno.h>
#endif
#include "include/event_type.h"
class EventSocket {
int socket;
int type;
public:
EventSocket(): socket(-1), type(EVENT_SOCKET_TYPE_NONE) {}
bool is_valid() const { return socket != -1; }
int init(int fd, int t) {
switch (t) {
case EVENT_SOCKET_TYPE_PIPE:
#ifdef HAVE_EVENTFD
case EVENT_SOCKET_TYPE_EVENTFD:
#endif
{
socket = fd;
type = t;
return 0;
}
}
return -EINVAL;
}
int notify() {
int ret;
switch (type) {
case EVENT_SOCKET_TYPE_PIPE:
{
char buf[1];
buf[0] = 'i';
ret = write(socket, buf, 1);
if (ret < 0)
ret = -errno;
else
ret = 0;
break;
}
#ifdef HAVE_EVENTFD
case EVENT_SOCKET_TYPE_EVENTFD:
{
uint64_t value = 1;
ret = write(socket, &value, sizeof (value));
if (ret < 0)
ret = -errno;
else
ret = 0;
break;
}
#endif
default:
{
ret = -1;
break;
}
}
return ret;
}
};
#endif
| 1,702 | 19.27381 | 70 | h |
null | ceph-main/src/common/fair_mutex.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:nil -*-
#pragma once
#include "common/ceph_mutex.h"
#include <thread>
#include <string>
namespace ceph {
/// a FIFO mutex
class fair_mutex {
public:
fair_mutex(const std::string& name)
: mutex{ceph::make_mutex(name)}
{}
~fair_mutex() = default;
fair_mutex(const fair_mutex&) = delete;
fair_mutex& operator=(const fair_mutex&) = delete;
void lock()
{
std::unique_lock lock(mutex);
const unsigned my_id = next_id++;
cond.wait(lock, [&] {
return my_id == unblock_id;
});
_set_locked_by();
}
bool try_lock()
{
std::lock_guard lock(mutex);
if (is_locked()) {
return false;
}
++next_id;
_set_locked_by();
return true;
}
void unlock()
{
std::lock_guard lock(mutex);
++unblock_id;
_reset_locked_by();
cond.notify_all();
}
bool is_locked() const
{
return next_id != unblock_id;
}
#ifdef CEPH_DEBUG_MUTEX
bool is_locked_by_me() const {
return is_locked() && locked_by == std::this_thread::get_id();
}
private:
void _set_locked_by() {
locked_by = std::this_thread::get_id();
}
void _reset_locked_by() {
locked_by = {};
}
#else
void _set_locked_by() {}
void _reset_locked_by() {}
#endif
private:
unsigned next_id = 0;
unsigned unblock_id = 0;
ceph::condition_variable cond;
ceph::mutex mutex;
#ifdef CEPH_DEBUG_MUTEX
std::thread::id locked_by = {};
#endif
};
} // namespace ceph
| 1,494 | 17.45679 | 72 | h |
null | ceph-main/src/common/fault_injector.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) 2020 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 <type_traits>
#include <boost/type_traits/has_equal_to.hpp>
#include <boost/type_traits/has_left_shift.hpp>
#include <variant>
#include "include/ceph_assert.h"
#include "common/dout.h"
/// @file
/// A failure type that aborts the process with a failed assertion.
struct InjectAbort {};
/// A failure type that injects an error code and optionally logs a message.
struct InjectError {
/// error code to inject
int error;
/// an optional log channel to print an error message
const DoutPrefixProvider* dpp = nullptr;
};
/** @class FaultInjector
* @brief Used to instrument a code path with deterministic fault injection
* by making one or more calls to check().
*
* A default-constructed FaultInjector contains no failure. It can also be
* constructed with a failure of type InjectAbort or InjectError, along with
* a location to inject that failure.
*
* The contained failure can be overwritten with a call to inject() or clear().
* This is not thread-safe with respect to other member functions on the same
* instance.
*
* @tparam Key The location can be represented by any Key type that is
* movable, default-constructible, inequality-comparable and stream-outputable.
* A string or string_view Key may be preferable when the location comes from
* user input, or to describe the steps like "before-foo" and "after-foo".
* An integer Key may be preferable for a code path with many steps, where you
* just want to check 1, 2, 3, etc. without inventing names for each.
*/
template <typename Key>
class FaultInjector {
public:
/// Default-construct with no injected failure.
constexpr FaultInjector() noexcept : location() {}
/// Construct with an injected assertion failure at the given location.
constexpr FaultInjector(Key location, InjectAbort a)
: location(std::move(location)), failure(a) {}
/// Construct with an injected error code at the given location.
constexpr FaultInjector(Key location, InjectError e)
: location(std::move(location)), failure(e) {}
/// Inject an assertion failure at the given location.
void inject(Key location, InjectAbort a) {
this->location = std::move(location);
this->failure = a;
}
/// Inject an error at the given location.
void inject(Key location, InjectError e) {
this->location = std::move(location);
this->failure = e;
}
/// Clear any injected failure.
void clear() {
this->failure = Empty{};
}
/// Check for an injected failure at the given location. If the location
/// matches an InjectAbort failure, the process aborts here with an assertion
/// failure.
/// @returns 0 or InjectError::error if the location matches an InjectError
/// failure
[[nodiscard]] constexpr int check(const Key& location) const {
struct visitor {
const Key& check_location;
const Key& this_location;
constexpr int operator()(const std::monostate&) const {
return 0;
}
int operator()(const InjectAbort&) const {
if (check_location == this_location) {
ceph_assert_always(!"FaultInjector");
}
return 0;
}
int operator()(const InjectError& e) const {
if (check_location == this_location) {
ldpp_dout(e.dpp, -1) << "Injecting error=" << e.error
<< " at location=" << this_location << dendl;
return e.error;
}
return 0;
}
};
return std::visit(visitor{location, this->location}, failure);
}
private:
// Key requirements:
static_assert(std::is_default_constructible_v<Key>,
"Key must be default-constrible");
static_assert(std::is_move_constructible_v<Key>,
"Key must be move-constructible");
static_assert(std::is_move_assignable_v<Key>,
"Key must be move-assignable");
static_assert(boost::has_equal_to<Key, Key, bool>::value,
"Key must be equality-comparable");
static_assert(boost::has_left_shift<std::ostream, Key, std::ostream&>::value,
"Key must have an ostream operator<<");
Key location; // location of the check that should fail
using Empty = std::monostate; // empty state for std::variant
std::variant<Empty, InjectAbort, InjectError> failure;
};
| 4,680 | 33.419118 | 79 | h |
null | ceph-main/src/common/fd.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 "include/compat.h"
#include "debug.h"
#include "errno.h"
#ifndef _WIN32
void dump_open_fds(CephContext *cct)
{
#ifdef __APPLE__
const char *fn = "/dev/fd";
#else
const char *fn = PROCPREFIX "/proc/self/fd";
#endif
DIR *d = opendir(fn);
if (!d) {
lderr(cct) << "dump_open_fds unable to open " << fn << dendl;
return;
}
struct dirent *de = nullptr;
int n = 0;
while ((de = ::readdir(d))) {
if (de->d_name[0] == '.')
continue;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", fn, de->d_name);
char target[PATH_MAX];
ssize_t r = readlink(path, target, sizeof(target) - 1);
if (r < 0) {
r = -errno;
lderr(cct) << "dump_open_fds unable to readlink " << path << ": " << cpp_strerror(r) << dendl;
continue;
}
target[r] = 0;
lderr(cct) << "dump_open_fds " << de->d_name << " -> " << target << dendl;
n++;
}
lderr(cct) << "dump_open_fds dumped " << n << " open files" << dendl;
closedir(d);
}
#else
void dump_open_fds(CephContext *cct)
{
}
#endif
| 1,457 | 23.3 | 100 | cc |
null | ceph-main/src/common/fork_function.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
// Run a function in a forked child, with a timeout.
#pragma once
#include <functional>
#include <iostream>
#include <ostream>
#include <signal.h>
#ifndef _WIN32
#include <sys/wait.h>
#endif
#include <sys/types.h>
#include "include/ceph_assert.h"
#include "common/errno.h"
#ifndef _WIN32
static void _fork_function_dummy_sighandler(int sig) {}
// Run a function post-fork, with a timeout. Function can return
// int8_t only due to unix exit code limitations. Returns -ETIMEDOUT
// if timeout is reached.
static inline int fork_function(
int timeout,
std::ostream& errstr,
std::function<int8_t(void)> f)
{
// first fork the forker.
pid_t forker_pid = fork();
if (forker_pid) {
// just wait
int status;
while (waitpid(forker_pid, &status, 0) == -1) {
ceph_assert(errno == EINTR);
}
if (WIFSIGNALED(status)) {
errstr << ": got signal: " << WTERMSIG(status) << "\n";
return 128 + WTERMSIG(status);
}
if (WIFEXITED(status)) {
int8_t r = WEXITSTATUS(status);
errstr << ": exit status: " << (int)r << "\n";
return r;
}
errstr << ": waitpid: unknown status returned\n";
return -1;
}
// we are forker (first child)
// close all fds
int maxfd = sysconf(_SC_OPEN_MAX);
if (maxfd == -1)
maxfd = 16384;
for (int fd = 0; fd <= maxfd; fd++) {
if (fd == STDIN_FILENO)
continue;
if (fd == STDOUT_FILENO)
continue;
if (fd == STDERR_FILENO)
continue;
::close(fd);
}
sigset_t mask, oldmask;
int pid;
// Restore default action for SIGTERM in case the parent process decided
// to ignore it.
if (signal(SIGTERM, SIG_DFL) == SIG_ERR) {
std::cerr << ": signal failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
// Because SIGCHLD is ignored by default, setup dummy handler for it,
// so we can mask it.
if (signal(SIGCHLD, _fork_function_dummy_sighandler) == SIG_ERR) {
std::cerr << ": signal failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
// Setup timeout handler.
if (signal(SIGALRM, timeout_sighandler) == SIG_ERR) {
std::cerr << ": signal failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
// Block interesting signals.
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGCHLD);
sigaddset(&mask, SIGALRM);
if (sigprocmask(SIG_SETMASK, &mask, &oldmask) == -1) {
std::cerr << ": sigprocmask failed: "
<< cpp_strerror(errno) << "\n";
goto fail_exit;
}
pid = fork();
if (pid == -1) {
std::cerr << ": fork failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
if (pid == 0) { // we are second child
// Restore old sigmask.
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1) {
std::cerr << ": sigprocmask failed: "
<< cpp_strerror(errno) << "\n";
goto fail_exit;
}
(void)setpgid(0, 0); // Become process group leader.
int8_t r = f();
_exit((uint8_t)r);
}
// Parent
(void)alarm(timeout);
for (;;) {
int signo;
if (sigwait(&mask, &signo) == -1) {
std::cerr << ": sigwait failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
switch (signo) {
case SIGCHLD:
int status;
if (waitpid(pid, &status, WNOHANG) == -1) {
std::cerr << ": waitpid failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
if (WIFEXITED(status))
_exit(WEXITSTATUS(status));
if (WIFSIGNALED(status))
_exit(128 + WTERMSIG(status));
std::cerr << ": unknown status returned\n";
goto fail_exit;
case SIGINT:
case SIGTERM:
// Pass SIGINT and SIGTERM, which are usually used to terminate
// a process, to the child.
if (::kill(pid, signo) == -1) {
std::cerr << ": kill failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
continue;
case SIGALRM:
std::cerr << ": timed out (" << timeout << " sec)\n";
if (::killpg(pid, SIGKILL) == -1) {
std::cerr << ": kill failed: " << cpp_strerror(errno) << "\n";
goto fail_exit;
}
_exit(-ETIMEDOUT);
default:
std::cerr << ": sigwait: invalid signal: " << signo << "\n";
goto fail_exit;
}
}
return 0;
fail_exit:
_exit(EXIT_FAILURE);
}
#else
static inline int fork_function(
int timeout,
std::ostream& errstr,
std::function<int8_t(void)> f)
{
errstr << "Forking is not available on Windows.\n";
return -1;
}
#endif
| 4,562 | 24.779661 | 74 | h |
null | ceph-main/src/common/freebsd_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 <errno.h>
#include "include/types.h"
#include "include/compat.h"
#define H2C_ERRNO(a,b) [a] = b
#define C2H_ERRNO(a,b) [a] = b
// Build a table with the FreeBSD error as index
// and the Linux error as value
// Use the fact that the arry is initialised per default on all 0's
// And we do not translate for 0's, but return the original value.
static const __s32 ceph_to_hostos_conv[256] = {
// Linux errno FreeBSD errno
C2H_ERRNO(11, EAGAIN),
C2H_ERRNO(35, EDEADLK),
C2H_ERRNO(36, ENAMETOOLONG),
C2H_ERRNO(37, ENOLCK),
C2H_ERRNO(38, ENOSYS),
C2H_ERRNO(39, ENOTEMPTY),
C2H_ERRNO(40, ELOOP),
C2H_ERRNO(42, ENOMSG),
C2H_ERRNO(43, EIDRM),
C2H_ERRNO(44, EPERM), //TODO ECHRNG /* Channel number out of range */
C2H_ERRNO(45, EPERM), //TODO EL2NSYNC /* Level 2 not synchronized */
C2H_ERRNO(46, EPERM), //TODO EL3HLT /* Level 3 halted */
C2H_ERRNO(47, EPERM), //TODO EL3RST /* Level 3 reset */
C2H_ERRNO(48, EPERM), //TODO ELNRNG /* Link number out of range */
C2H_ERRNO(49, EPERM), //TODO EUNATCH /* Protocol driver not attached */
C2H_ERRNO(50, EPERM), //TODO ENOCSI /* No CSI structure available */
C2H_ERRNO(51, EPERM), //TODO EL2HLT /* Level 2 halted */
C2H_ERRNO(52, EPERM), //TODO EBADE /* Invalid exchange */
C2H_ERRNO(53, EPERM), //TODO EBADR /* Invalid request descriptor */
C2H_ERRNO(54, EPERM), //TODO EXFULL /* Exchange full */
C2H_ERRNO(55, EPERM), //TODO ENOANO /* No anode */
C2H_ERRNO(56, EPERM), //TODO EBADRQC /* Invalid request code */
C2H_ERRNO(57, EPERM), //TODO EBADSLT /* Invalid slot */
C2H_ERRNO(59, EPERM), //TODO EBFONT /* Bad font file format */
C2H_ERRNO(60, ENOSTR),
C2H_ERRNO(61, ENODATA),
C2H_ERRNO(62, ETIME),
C2H_ERRNO(63, ENOSR),
C2H_ERRNO(64, EPERM), //TODO ENONET
C2H_ERRNO(65, EPERM), //TODO ENOPKG
C2H_ERRNO(66, EREMOTE),
C2H_ERRNO(67, ENOLINK),
C2H_ERRNO(68, EPERM), //TODO EADV
C2H_ERRNO(69, EPERM), //TODO ESRMNT
C2H_ERRNO(70, EPERM), //TODO ECOMM
C2H_ERRNO(71, EPROTO),
C2H_ERRNO(72, EMULTIHOP),
C2H_ERRNO(73, EPERM), //TODO EDOTDOT
C2H_ERRNO(74, EBADMSG),
C2H_ERRNO(75, EOVERFLOW),
C2H_ERRNO(76, EPERM), //TODO ENOTUNIQ
C2H_ERRNO(77, EPERM), //TODO EBADFD
C2H_ERRNO(78, EPERM), //TODO EREMCHG
C2H_ERRNO(79, EPERM), //TODO ELIBACC
C2H_ERRNO(80, EPERM), //TODO ELIBBAD
C2H_ERRNO(81, EPERM), //TODO ELIBSCN
C2H_ERRNO(82, EPERM), //TODO ELIBMAX
C2H_ERRNO(83, EPERM), //TODO ELIBEXEC
C2H_ERRNO(84, EILSEQ),
C2H_ERRNO(85, EINTR), /* not quite, since this is a syscll restart */
C2H_ERRNO(86, EPERM), //ESTRPIPE;
C2H_ERRNO(87, EUSERS),
C2H_ERRNO(88, ENOTSOCK),
C2H_ERRNO(89, EDESTADDRREQ),
C2H_ERRNO(90, EMSGSIZE),
C2H_ERRNO(91, EPROTOTYPE),
C2H_ERRNO(92, ENOPROTOOPT),
C2H_ERRNO(93, EPROTONOSUPPORT),
C2H_ERRNO(94, ESOCKTNOSUPPORT),
C2H_ERRNO(95, EOPNOTSUPP),
C2H_ERRNO(96, EPFNOSUPPORT),
C2H_ERRNO(97, EAFNOSUPPORT),
C2H_ERRNO(98, EADDRINUSE),
C2H_ERRNO(99, EADDRNOTAVAIL),
C2H_ERRNO(100, ENETDOWN),
C2H_ERRNO(101, ENETUNREACH),
C2H_ERRNO(102, ENETRESET),
C2H_ERRNO(103, ECONNABORTED),
C2H_ERRNO(104, ECONNRESET),
C2H_ERRNO(105, ENOBUFS),
C2H_ERRNO(106, EISCONN),
C2H_ERRNO(107, ENOTCONN),
C2H_ERRNO(108, ESHUTDOWN),
C2H_ERRNO(109, ETOOMANYREFS),
C2H_ERRNO(110, ETIMEDOUT),
C2H_ERRNO(111, ECONNREFUSED),
C2H_ERRNO(112, EHOSTDOWN),
C2H_ERRNO(113, EHOSTUNREACH),
C2H_ERRNO(114, EALREADY),
C2H_ERRNO(115, EINPROGRESS),
C2H_ERRNO(116, ESTALE),
C2H_ERRNO(117, EPERM), //TODO EUCLEAN
C2H_ERRNO(118, EPERM), //TODO ENOTNAM
C2H_ERRNO(119, EPERM), //TODO ENAVAIL
C2H_ERRNO(120, EPERM), //TODO EISNAM
C2H_ERRNO(121, EREMOTEIO),
C2H_ERRNO(122, EDQUOT),
C2H_ERRNO(123, EPERM), //TODO ENOMEDIUM
C2H_ERRNO(124, EPERM), //TODO EMEDIUMTYPE - not used
C2H_ERRNO(125, ECANCELED),
C2H_ERRNO(126, EPERM), //TODO ENOKEY
C2H_ERRNO(127, EPERM), //TODO EKEYEXPIRED
C2H_ERRNO(128, EPERM), //TODO EKEYREVOKED
C2H_ERRNO(129, EPERM), //TODO EKEYREJECTED
C2H_ERRNO(130, EOWNERDEAD),
C2H_ERRNO(131, ENOTRECOVERABLE),
C2H_ERRNO(132, EPERM), //TODO ERFKILL
C2H_ERRNO(133, EPERM), //TODO EHWPOISON
};
// Build a table with the FreeBSD error as index
// and the Linux error as value
// Use the fact that the arry is initialised per default on all 0's
// And we do not translate for 0's, but return the original value.
static const __s32 hostos_to_ceph_conv[256] = {
// FreeBSD errno Linux errno
H2C_ERRNO(EDEADLK, 35), /* Resource deadlock avoided */
H2C_ERRNO(EAGAIN, 11), /* Resource temporarily unavailable */
H2C_ERRNO(EINPROGRESS, 115), /* Operation now in progress */
H2C_ERRNO(EALREADY, 114), /* Operation already in progress */
H2C_ERRNO(ENOTSOCK, 88), /* Socket operation on non-socket */
H2C_ERRNO(EDESTADDRREQ, 89), /* Destination address required */
H2C_ERRNO(EMSGSIZE, 90), /* Message too long */
H2C_ERRNO(EPROTOTYPE, 91), /* Protocol wrong type for socket */
H2C_ERRNO(ENOPROTOOPT, 92), /* Protocol not available */
H2C_ERRNO(EPROTONOSUPPORT, 93), /* Protocol not supported */
H2C_ERRNO(ESOCKTNOSUPPORT, 94), /* Socket type not supported */
H2C_ERRNO(EOPNOTSUPP, 95), /* Operation not supported */
H2C_ERRNO(EPFNOSUPPORT, 96), /* Protocol family not supported */
H2C_ERRNO(EAFNOSUPPORT, 97), /* Address family not supported by protocol family */
H2C_ERRNO(EADDRINUSE, 98), /* Address already in use */
H2C_ERRNO(EADDRNOTAVAIL, 99), /* Can't assign requested address */
H2C_ERRNO(ENETDOWN, 100), /* Network is down */
H2C_ERRNO(ENETUNREACH, 101), /* Network is unreachable */
H2C_ERRNO(ENETRESET, 102), /* Network dropped connection on reset */
H2C_ERRNO(ECONNABORTED, 103), /* Software caused connection abort */
H2C_ERRNO(ECONNRESET, 104), /* Connection reset by peer */
H2C_ERRNO(ENOBUFS, 105), /* No buffer space available */
H2C_ERRNO(EISCONN, 106), /* Socket is already connected */
H2C_ERRNO(ENOTCONN, 107), /* Socket is not connected */
H2C_ERRNO(ESHUTDOWN, 108), /* Can't send after socket shutdown */
H2C_ERRNO(ETOOMANYREFS, 109), /* Too many references: can't splice */
H2C_ERRNO(ETIMEDOUT, 110), /* Operation timed out */
H2C_ERRNO(ECONNREFUSED, 111), /* Connection refused */
H2C_ERRNO(ELOOP, 40), /* Too many levels of symbolic links */
H2C_ERRNO(ENAMETOOLONG, 36), /* File name too long */
H2C_ERRNO(EHOSTDOWN, 112), /* Host is down */
H2C_ERRNO(EHOSTUNREACH, 113), /* No route to host */
H2C_ERRNO(ENOTEMPTY, 39), /* Directory not empty */
H2C_ERRNO(EPROCLIM, EPERM), /* Too many processes */
H2C_ERRNO(EUSERS, 87), /* Too many users */
H2C_ERRNO(EDQUOT, 122), /* Disc quota exceeded */
H2C_ERRNO(ESTALE, 116), /* Stale NFS file handle */
H2C_ERRNO(EREMOTE, 66), /* Too many levels of remote in path */
H2C_ERRNO(EBADRPC, EPERM), /* RPC struct is bad */
H2C_ERRNO(ERPCMISMATCH, EPERM), /* RPC version wrong */
H2C_ERRNO(EPROGUNAVAIL, EPERM), /* RPC prog. not avail */
H2C_ERRNO(EPROGMISMATCH, EPERM),/* Program version wrong */
H2C_ERRNO(EPROCUNAVAIL, EPERM), /* Bad procedure for program */
H2C_ERRNO(ENOLCK, EPERM), /* No locks available */
H2C_ERRNO(ENOSYS, EPERM), /* Function not implemented */
H2C_ERRNO(EFTYPE, EPERM), /* Inappropriate file type or format */
H2C_ERRNO(EAUTH, EPERM), /* Authentication error */
H2C_ERRNO(ENEEDAUTH, EPERM), /* Need authenticator */
H2C_ERRNO(EIDRM, 43), /* Identifier removed */
H2C_ERRNO(ENOMSG, 42), /* No message of desired type */
H2C_ERRNO(EOVERFLOW, 75), /* Value too large to be stored in data type */
H2C_ERRNO(ECANCELED, 125), /* Operation canceled */
H2C_ERRNO(EILSEQ, 84), /* Illegal byte sequence */
H2C_ERRNO(ENOATTR, 61), /* Attribute not found */
H2C_ERRNO(EDOOFUS, EPERM), /* Programming error */
H2C_ERRNO(EBADMSG, 74), /* Bad message */
H2C_ERRNO(EMULTIHOP, 72), /* Multihop attempted */
H2C_ERRNO(ENOLINK, 67), /* Link has been severed */
H2C_ERRNO(EPROTO, 71), /* Protocol error */
H2C_ERRNO(ENOTCAPABLE, EPERM), /* Capabilities insufficient */
H2C_ERRNO(ECAPMODE, EPERM), /* Not permitted in capability mode */
H2C_ERRNO(ENOTRECOVERABLE, 131),/* State not recoverable */
H2C_ERRNO(EOWNERDEAD, 130), /* Previous owner died */
};
// converts from linux errno values to host values
__s32 ceph_to_hostos_errno(__s32 r)
{
int sign = (r < 0 ? -1 : 1);
int err = std::abs(r);
if (err < 256 && ceph_to_hostos_conv[err] !=0 ) {
err = ceph_to_hostos_conv[err];
}
return err * sign;
}
// converts Host OS errno values to linux/Ceph values
__s32 hostos_to_ceph_errno(__s32 r)
{
int sign = (r < 0 ? -1 : 1);
int err = std::abs(r);
if (err < 256 && hostos_to_ceph_conv[err] !=0 ) {
err = hostos_to_ceph_conv[err];
}
return err * sign;
}
| 10,162 | 45.195455 | 90 | cc |
null | ceph-main/src/common/fs_types.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "include/fs_types.h"
#include "common/Formatter.h"
#include "include/ceph_features.h"
#include "common/ceph_json.h"
void dump(const ceph_file_layout& l, ceph::Formatter *f)
{
f->dump_unsigned("stripe_unit", l.fl_stripe_unit);
f->dump_unsigned("stripe_count", l.fl_stripe_count);
f->dump_unsigned("object_size", l.fl_object_size);
if (l.fl_cas_hash)
f->dump_unsigned("cas_hash", l.fl_cas_hash);
if (l.fl_object_stripe_unit)
f->dump_unsigned("object_stripe_unit", l.fl_object_stripe_unit);
if (l.fl_pg_pool)
f->dump_unsigned("pg_pool", l.fl_pg_pool);
}
void dump(const ceph_dir_layout& l, ceph::Formatter *f)
{
f->dump_unsigned("dir_hash", l.dl_dir_hash);
f->dump_unsigned("unused1", l.dl_unused1);
f->dump_unsigned("unused2", l.dl_unused2);
f->dump_unsigned("unused3", l.dl_unused3);
}
// file_layout_t
bool file_layout_t::is_valid() const
{
/* stripe unit, object size must be non-zero, 64k increment */
if (!stripe_unit || (stripe_unit & (CEPH_MIN_STRIPE_UNIT-1)))
return false;
if (!object_size || (object_size & (CEPH_MIN_STRIPE_UNIT-1)))
return false;
/* object size must be a multiple of stripe unit */
if (object_size < stripe_unit || object_size % stripe_unit)
return false;
/* stripe count must be non-zero */
if (!stripe_count)
return false;
return true;
}
void file_layout_t::from_legacy(const ceph_file_layout& fl)
{
stripe_unit = fl.fl_stripe_unit;
stripe_count = fl.fl_stripe_count;
object_size = fl.fl_object_size;
pool_id = (int32_t)fl.fl_pg_pool;
// in the legacy encoding, a zeroed structure was the default and
// would have pool 0 instead of -1.
if (pool_id == 0 && stripe_unit == 0 && stripe_count == 0 && object_size == 0)
pool_id = -1;
pool_ns.clear();
}
void file_layout_t::to_legacy(ceph_file_layout *fl) const
{
fl->fl_stripe_unit = stripe_unit;
fl->fl_stripe_count = stripe_count;
fl->fl_object_size = object_size;
fl->fl_cas_hash = 0;
fl->fl_object_stripe_unit = 0;
fl->fl_unused = 0;
// in the legacy encoding, pool 0 was undefined.
if (pool_id >= 0)
fl->fl_pg_pool = pool_id;
else
fl->fl_pg_pool = 0;
}
void file_layout_t::encode(ceph::buffer::list& bl, uint64_t features) const
{
using ceph::encode;
if ((features & CEPH_FEATURE_FS_FILE_LAYOUT_V2) == 0) {
ceph_file_layout fl;
ceph_assert((stripe_unit & 0xff) == 0); // first byte must be 0
to_legacy(&fl);
encode(fl, bl);
return;
}
ENCODE_START(2, 2, bl);
encode(stripe_unit, bl);
encode(stripe_count, bl);
encode(object_size, bl);
encode(pool_id, bl);
encode(pool_ns, bl);
ENCODE_FINISH(bl);
}
void file_layout_t::decode(ceph::buffer::list::const_iterator& p)
{
using ceph::decode;
if (*p == 0) {
ceph_file_layout fl;
decode(fl, p);
from_legacy(fl);
return;
}
DECODE_START(2, p);
decode(stripe_unit, p);
decode(stripe_count, p);
decode(object_size, p);
decode(pool_id, p);
decode(pool_ns, p);
DECODE_FINISH(p);
}
void file_layout_t::dump(ceph::Formatter *f) const
{
f->dump_unsigned("stripe_unit", stripe_unit);
f->dump_unsigned("stripe_count", stripe_count);
f->dump_unsigned("object_size", object_size);
f->dump_int("pool_id", pool_id);
f->dump_string("pool_ns", pool_ns);
}
void file_layout_t::decode_json(JSONObj *obj){
JSONDecoder::decode_json("stripe_unit", stripe_unit, obj, true);
JSONDecoder::decode_json("stripe_count", stripe_count, obj, true);
JSONDecoder::decode_json("object_size", object_size, obj, true);
JSONDecoder::decode_json("pool_id", pool_id, obj, true);
JSONDecoder::decode_json("pool_ns", pool_ns, obj, true);
}
void file_layout_t::generate_test_instances(std::list<file_layout_t*>& o)
{
o.push_back(new file_layout_t);
o.push_back(new file_layout_t);
o.back()->stripe_unit = 4096;
o.back()->stripe_count = 16;
o.back()->object_size = 1048576;
o.back()->pool_id = 3;
o.back()->pool_ns = "myns";
}
std::ostream& operator<<(std::ostream& out, const file_layout_t &layout)
{
ceph::JSONFormatter f;
layout.dump(&f);
f.flush(out);
return out;
}
| 4,209 | 26.880795 | 80 | cc |
null | ceph-main/src/common/function_signature.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Copied from:
* https://github.com/exclipy/inline_variant_visitor/blob/master/function_signature.hpp
* which apparently copied it from
* http://stackoverflow.com/questions/4771417/how-to-get-the-signature-of-a-c-bind-expression
*/
#ifndef FUNCTION_SIGNATURE_H
#define FUNCTION_SIGNATURE_H
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/parameter_types.hpp>
template <typename F>
struct signature_of_member
{
typedef typename boost::function_types::result_type<F>::type result_type;
typedef typename boost::function_types::parameter_types<F>::type parameter_types;
typedef typename boost::mpl::pop_front<parameter_types>::type base;
typedef typename boost::mpl::push_front<base, result_type>::type L;
typedef typename boost::function_types::function_type<L>::type type;
};
template <typename F, bool is_class>
struct signature_of_impl
{
typedef typename boost::function_types::function_type<F>::type type;
};
template <typename F>
struct signature_of_impl<F, true>
{
typedef typename signature_of_member<decltype(&F::operator())>::type type;
};
template <typename F>
struct signature_of
{
typedef typename signature_of_impl<F, boost::is_class<F>::value>::type type;
};
#endif
| 1,474 | 29.729167 | 93 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.