repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
null | ceph-main/src/include/ceph_fuse.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2012 Inktank Storage, Inc.
* Copyright (C) 2014 Red Hat <[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_FUSE_H
#define CEPH_FUSE_H
/*
* The API version that we want to use, regardless of what the
* library version is. Note that this must be defined before
* fuse.h is included.
*/
#ifndef FUSE_USE_VERSION
#define FUSE_USE_VERSION 312
#endif
#include <fuse.h>
#include "acconfig.h"
/*
* Redefine the FUSE_VERSION macro defined in "fuse_common.h"
* header file, because the MINOR numner has been forgotten to
* update since libfuse 3.2 to 3.8. We need to fetch the MINOR
* number from pkgconfig file.
*/
#ifdef FUSE_VERSION
#undef FUSE_VERSION
#define FUSE_VERSION FUSE_MAKE_VERSION(CEPH_FUSE_MAJOR_VERSION, CEPH_FUSE_MINOR_VERSION)
#endif
static inline int filler_compat(fuse_fill_dir_t filler,
void *buf, const char *name,
const struct stat *stbuf,
off_t off)
{
return filler(buf, name, stbuf, off
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, static_cast<enum fuse_fill_dir_flags>(0)
#endif
);
}
#endif /* CEPH_FUSE_H */
| 1,529 | 28.423077 | 88 | h |
null | ceph-main/src/include/common_fwd.h | #pragma once
#if defined(WITH_SEASTAR) && !defined(WITH_ALIEN)
#define TOPNSPC crimson
#else
#define TOPNSPC ceph
#endif
namespace TOPNSPC::common {
class CephContext;
class PerfCounters;
class PerfCountersBuilder;
class PerfCountersCollection;
class PerfCountersCollectionImpl;
class PerfGuard;
class RefCountedObject;
class RefCountedObjectSafe;
class RefCountedCond;
class RefCountedWaitObject;
class ConfigProxy;
}
using TOPNSPC::common::CephContext;
using TOPNSPC::common::PerfCounters;
using TOPNSPC::common::PerfCountersBuilder;
using TOPNSPC::common::PerfCountersCollection;
using TOPNSPC::common::PerfCountersCollectionImpl;
using TOPNSPC::common::PerfGuard;
using TOPNSPC::common::RefCountedObject;
using TOPNSPC::common::RefCountedObjectSafe;
using TOPNSPC::common::RefCountedCond;
using TOPNSPC::common::RefCountedWaitObject;
using TOPNSPC::common::ConfigProxy;
| 898 | 26.242424 | 50 | h |
null | ceph-main/src/include/compact_map.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2015 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_COMPACT_MAP_H
#define CEPH_COMPACT_MAP_H
#include "buffer.h"
#include "encoding.h"
#include <map>
#include <memory>
#include "include/encoding.h"
template <class Key, class T, class Map>
class compact_map_base {
protected:
std::unique_ptr<Map> map;
void alloc_internal() {
if (!map)
map.reset(new Map);
}
void free_internal() {
map.reset();
}
template <class It>
class const_iterator_base {
const compact_map_base *map;
It it;
const_iterator_base() : map(0) { }
const_iterator_base(const compact_map_base* m) : map(m) { }
const_iterator_base(const compact_map_base *m, const It& i) : map(m), it(i) { }
friend class compact_map_base;
friend class iterator_base;
public:
const_iterator_base(const const_iterator_base& o) {
map = o.map;
it = o.it;
}
bool operator==(const const_iterator_base& o) const {
return (map == o.map) && (!map->map || it == o.it);
}
bool operator!=(const const_iterator_base& o) const {
return !(*this == o);;
}
const_iterator_base& operator=(const const_iterator_base& o) {
map = o.map;
it = o.it;
return *this;
}
const_iterator_base& operator++() {
++it;
return *this;
}
const_iterator_base& operator--() {
--it;
return *this;
}
const std::pair<const Key,T>& operator*() {
return *it;
}
const std::pair<const Key,T>* operator->() {
return it.operator->();
}
};
template <class It>
class iterator_base {
private:
const compact_map_base* map;
It it;
iterator_base() : map(0) { }
iterator_base(compact_map_base* m) : map(m) { }
iterator_base(compact_map_base* m, const It& i) : map(m), it(i) { }
friend class compact_map_base;
public:
iterator_base(const iterator_base& o) {
map = o.map;
it = o.it;
}
bool operator==(const iterator_base& o) const {
return (map == o.map) && (!map->map || it == o.it);
}
bool operator!=(const iterator_base& o) const {
return !(*this == o);;
}
iterator_base& operator=(const iterator_base& o) {
map = o.map;
it = o.it;
return *this;
}
iterator_base& operator++() {
++it;
return *this;
}
iterator_base operator++(int) {
iterator_base tmp = *this;
++it;
return tmp;
}
iterator_base& operator--() {
--it;
return *this;
}
std::pair<const Key,T>& operator*() {
return *it;
}
std::pair<const Key,T>* operator->() {
return it.operator->();
}
operator const_iterator_base<It>() const {
return const_iterator_base<It>(map, it);
}
};
public:
class iterator : public iterator_base<typename Map::iterator> {
public:
iterator() { }
iterator(const iterator_base<typename Map::iterator>& o)
: iterator_base<typename Map::iterator>(o) { }
iterator(compact_map_base* m) : iterator_base<typename Map::iterator>(m) { }
iterator(compact_map_base* m, const typename Map::iterator& i)
: iterator_base<typename Map::iterator>(m, i) { }
};
class const_iterator : public const_iterator_base<typename Map::const_iterator> {
public:
const_iterator() { }
const_iterator(const iterator_base<typename Map::const_iterator>& o)
: const_iterator_base<typename Map::const_iterator>(o) { }
const_iterator(const compact_map_base* m) : const_iterator_base<typename Map::const_iterator>(m) { }
const_iterator(const compact_map_base* m, const typename Map::const_iterator& i)
: const_iterator_base<typename Map::const_iterator>(m, i) { }
};
class reverse_iterator : public iterator_base<typename Map::reverse_iterator> {
public:
reverse_iterator() { }
reverse_iterator(const iterator_base<typename Map::reverse_iterator>& o)
: iterator_base<typename Map::reverse_iterator>(o) { }
reverse_iterator(compact_map_base* m) : iterator_base<typename Map::reverse_iterator>(m) { }
reverse_iterator(compact_map_base* m, const typename Map::reverse_iterator& i)
: iterator_base<typename Map::reverse_iterator>(m, i) { }
};
class const_reverse_iterator : public const_iterator_base<typename Map::const_reverse_iterator> {
public:
const_reverse_iterator() { }
const_reverse_iterator(const iterator_base<typename Map::const_reverse_iterator>& o)
: iterator_base<typename Map::const_reverse_iterator>(o) { }
const_reverse_iterator(const compact_map_base* m) : const_iterator_base<typename Map::const_reverse_iterator>(m) { }
const_reverse_iterator(const compact_map_base* m, const typename Map::const_reverse_iterator& i)
: const_iterator_base<typename Map::const_reverse_iterator>(m, i) { }
};
compact_map_base(const compact_map_base& o) {
if (o.map) {
alloc_internal();
*map = *o.map;
}
}
compact_map_base() {}
~compact_map_base() {}
bool empty() const {
return !map || map->empty();
}
size_t size() const {
return map ? map->size() : 0;
}
bool operator==(const compact_map_base& o) const {
return (empty() && o.empty()) || (map && o.map && *map == *o.map);
}
bool operator!=(const compact_map_base& o) const {
return !(*this == o);
}
size_t count (const Key& k) const {
return map ? map->count(k) : 0;
}
iterator erase (iterator p) {
if (map) {
ceph_assert(this == p.map);
auto it = map->erase(p.it);
if (map->empty()) {
free_internal();
return iterator(this);
} else {
return iterator(this, it);
}
} else {
return iterator(this);
}
}
size_t erase (const Key& k) {
if (!map)
return 0;
size_t r = map->erase(k);
if (map->empty())
free_internal();
return r;
}
void clear() {
free_internal();
}
void swap(compact_map_base& o) {
map.swap(o.map);
}
compact_map_base& operator=(const compact_map_base& o) {
if (o.map) {
alloc_internal();
*map = *o.map;
} else
free_internal();
return *this;
}
iterator insert(const std::pair<const Key, T>& val) {
alloc_internal();
return iterator(this, map->insert(val));
}
template <class... Args>
std::pair<iterator,bool> emplace ( Args&&... args ) {
alloc_internal();
auto em = map->emplace(std::forward<Args>(args)...);
return std::pair<iterator,bool>(iterator(this, em.first), em.second);
}
iterator begin() {
if (!map)
return iterator(this);
return iterator(this, map->begin());
}
iterator end() {
if (!map)
return iterator(this);
return iterator(this, map->end());
}
reverse_iterator rbegin() {
if (!map)
return reverse_iterator(this);
return reverse_iterator(this, map->rbegin());
}
reverse_iterator rend() {
if (!map)
return reverse_iterator(this);
return reverse_iterator(this, map->rend());
}
iterator find(const Key& k) {
if (!map)
return iterator(this);
return iterator(this, map->find(k));
}
iterator lower_bound(const Key& k) {
if (!map)
return iterator(this);
return iterator(this, map->lower_bound(k));
}
iterator upper_bound(const Key& k) {
if (!map)
return iterator(this);
return iterator(this, map->upper_bound(k));
}
const_iterator begin() const {
if (!map)
return const_iterator(this);
return const_iterator(this, map->begin());
}
const_iterator end() const {
if (!map)
return const_iterator(this);
return const_iterator(this, map->end());
}
const_reverse_iterator rbegin() const {
if (!map)
return const_reverse_iterator(this);
return const_reverse_iterator(this, map->rbegin());
}
const_reverse_iterator rend() const {
if (!map)
return const_reverse_iterator(this);
return const_reverse_iterator(this, map->rend());
}
const_iterator find(const Key& k) const {
if (!map)
return const_iterator(this);
return const_iterator(this, map->find(k));
}
const_iterator lower_bound(const Key& k) const {
if (!map)
return const_iterator(this);
return const_iterator(this, map->lower_bound(k));
}
const_iterator upper_bound(const Key& k) const {
if (!map)
return const_iterator(this);
return const_iterator(this, map->upper_bound(k));
}
void encode(ceph::buffer::list &bl) const {
using ceph::encode;
if (map)
encode(*map, bl);
else
encode((uint32_t)0, bl);
}
void encode(ceph::buffer::list &bl, uint64_t features) const {
using ceph::encode;
if (map)
encode(*map, bl, features);
else
encode((uint32_t)0, bl);
}
void decode(ceph::buffer::list::const_iterator& p) {
using ceph::decode;
using ceph::decode_nohead;
uint32_t n;
decode(n, p);
if (n > 0) {
alloc_internal();
decode_nohead(n, *map, p);
} else
free_internal();
}
};
template<class Key, class T, class Map>
inline void encode(const compact_map_base<Key, T, Map>& m, ceph::buffer::list& bl) {
m.encode(bl);
}
template<class Key, class T, class Map>
inline void encode(const compact_map_base<Key, T, Map>& m, ceph::buffer::list& bl,
uint64_t features) {
m.encode(bl, features);
}
template<class Key, class T, class Map>
inline void decode(compact_map_base<Key, T, Map>& m, ceph::buffer::list::const_iterator& p) {
m.decode(p);
}
template <class Key, class T, class Compare = std::less<Key>, class Alloc = std::allocator< std::pair<const Key, T> > >
class compact_map : public compact_map_base<Key, T, std::map<Key,T,Compare,Alloc> > {
public:
T& operator[](const Key& k) {
this->alloc_internal();
return (*(this->map))[k];
}
};
template <class Key, class T, class Compare = std::less<Key>, class Alloc = std::allocator< std::pair<const Key, T> > >
inline std::ostream& operator<<(std::ostream& out, const compact_map<Key, T, Compare, Alloc>& m)
{
out << "{";
bool first = true;
for (const auto &p : m) {
if (!first)
out << ",";
out << p.first << "=" << p.second;
first = false;
}
out << "}";
return out;
}
template <class Key, class T, class Compare = std::less<Key>, class Alloc = std::allocator< std::pair<const Key, T> > >
class compact_multimap : public compact_map_base<Key, T, std::multimap<Key,T,Compare,Alloc> > {
};
template <class Key, class T, class Compare = std::less<Key>, class Alloc = std::allocator< std::pair<const Key, T> > >
inline std::ostream& operator<<(std::ostream& out, const compact_multimap<Key, T, Compare, Alloc>& m)
{
out << "{{";
bool first = true;
for (const auto &p : m) {
if (!first)
out << ",";
out << p.first << "=" << p.second;
first = false;
}
out << "}}";
return out;
}
#endif
| 11,062 | 27.809896 | 122 | h |
null | ceph-main/src/include/compact_set.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2015 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_COMPACT_SET_H
#define CEPH_COMPACT_SET_H
#include "buffer.h"
#include "encoding.h"
#include <memory>
#include <set>
template <class T, class Set>
class compact_set_base {
protected:
std::unique_ptr<Set> set;
void alloc_internal() {
if (!set)
set.reset(new Set);
}
void free_internal() {
set.reset();
}
template <class It>
class iterator_base {
private:
const compact_set_base* set;
It it;
iterator_base() : set(0) { }
iterator_base(const compact_set_base* s) : set(s) { }
iterator_base(const compact_set_base* s, const It& i) : set(s), it(i) { }
friend class compact_set_base;
public:
iterator_base(const iterator_base& o) {
set = o.set;
it = o.it;
}
bool operator==(const iterator_base& o) const {
return (set == o.set) && (!set->set || it == o.it);
}
bool operator!=(const iterator_base& o) const {
return !(*this == o);;
}
iterator_base& operator=(const iterator_base& o) {
set->set = o.set;
it = o.it;
return *this;
}
iterator_base& operator++() {
++it;
return *this;
}
iterator_base operator++(int) {
iterator_base tmp = *this;
++it;
return tmp;
}
iterator_base& operator--() {
--it;
return *this;
}
const T& operator*() {
return *it;
}
};
public:
class const_iterator : public iterator_base<typename Set::const_iterator> {
public:
const_iterator() { }
const_iterator(const iterator_base<typename Set::const_iterator>& o)
: iterator_base<typename Set::const_iterator>(o) { }
const_iterator(const compact_set_base* s) : iterator_base<typename Set::const_iterator>(s) { }
const_iterator(const compact_set_base* s, const typename Set::const_iterator& i)
: iterator_base<typename Set::const_iterator>(s, i) { }
};
class iterator : public iterator_base<typename Set::iterator> {
public:
iterator() { }
iterator(const iterator_base<typename Set::iterator>& o)
: iterator_base<typename Set::iterator>(o) { }
iterator(compact_set_base* s) : iterator_base<typename Set::iterator>(s) { }
iterator(compact_set_base* s, const typename Set::iterator& i)
: iterator_base<typename Set::iterator>(s, i) { }
operator const_iterator() const {
return const_iterator(this->set, this->it);
}
};
class const_reverse_iterator : public iterator_base<typename Set::const_reverse_iterator> {
public:
const_reverse_iterator() { }
const_reverse_iterator(const iterator_base<typename Set::const_reverse_iterator>& o)
: iterator_base<typename Set::const_reverse_iterator>(o) { }
const_reverse_iterator(const compact_set_base* s) : iterator_base<typename Set::const_reverse_iterator>(s) { }
const_reverse_iterator(const compact_set_base* s, const typename Set::const_reverse_iterator& i)
: iterator_base<typename Set::const_reverse_iterator>(s, i) { }
};
class reverse_iterator : public iterator_base<typename Set::reverse_iterator> {
public:
reverse_iterator() { }
reverse_iterator(const iterator_base<typename Set::reverse_iterator>& o)
: iterator_base<typename Set::reverse_iterator>(o) { }
reverse_iterator(compact_set_base* s) : iterator_base<typename Set::reverse_iterator>(s) { }
reverse_iterator(compact_set_base* s, const typename Set::reverse_iterator& i)
: iterator_base<typename Set::reverse_iterator>(s, i) { }
operator const_iterator() const {
return const_iterator(this->set, this->it);
}
};
compact_set_base() {}
compact_set_base(const compact_set_base& o) {
if (o.set) {
alloc_internal();
*set = *o.set;
}
}
~compact_set_base() {}
bool empty() const {
return !set || set->empty();
}
size_t size() const {
return set ? set->size() : 0;
}
bool operator==(const compact_set_base& o) const {
return (empty() && o.empty()) || (set && o.set && *set == *o.set);
}
bool operator!=(const compact_set_base& o) const {
return !(*this == o);
}
size_t count(const T& t) const {
return set ? set->count(t) : 0;
}
iterator erase (iterator p) {
if (set) {
ceph_assert(this == p.set);
auto it = set->erase(p.it);
if (set->empty()) {
free_internal();
return iterator(this);
} else {
return iterator(this, it);
}
} else {
return iterator(this);
}
}
size_t erase (const T& t) {
if (!set)
return 0;
size_t r = set->erase(t);
if (set->empty())
free_internal();
return r;
}
void clear() {
free_internal();
}
void swap(compact_set_base& o) {
set.swap(o.set);
}
compact_set_base& operator=(const compact_set_base& o) {
if (o.set) {
alloc_internal();
*set = *o.set;
} else
free_internal();
return *this;
}
std::pair<iterator,bool> insert(const T& t) {
alloc_internal();
std::pair<typename Set::iterator,bool> r = set->insert(t);
return std::make_pair(iterator(this, r.first), r.second);
}
template <class... Args>
std::pair<iterator,bool> emplace ( Args&&... args ) {
alloc_internal();
auto em = set->emplace(std::forward<Args>(args)...);
return std::pair<iterator,bool>(iterator(this, em.first), em.second);
}
iterator begin() {
if (!set)
return iterator(this);
return iterator(this, set->begin());
}
iterator end() {
if (!set)
return iterator(this);
return iterator(this, set->end());
}
reverse_iterator rbegin() {
if (!set)
return reverse_iterator(this);
return reverse_iterator(this, set->rbegin());
}
reverse_iterator rend() {
if (!set)
return reverse_iterator(this);
return reverse_iterator(this, set->rend());
}
iterator find(const T& t) {
if (!set)
return iterator(this);
return iterator(this, set->find(t));
}
iterator lower_bound(const T& t) {
if (!set)
return iterator(this);
return iterator(this, set->lower_bound(t));
}
iterator upper_bound(const T& t) {
if (!set)
return iterator(this);
return iterator(this, set->upper_bound(t));
}
const_iterator begin() const {
if (!set)
return const_iterator(this);
return const_iterator(this, set->begin());
}
const_iterator end() const {
if (!set)
return const_iterator(this);
return const_iterator(this, set->end());
}
const_reverse_iterator rbegin() const {
if (!set)
return const_reverse_iterator(this);
return const_reverse_iterator(this, set->rbegin());
}
const_reverse_iterator rend() const {
if (!set)
return const_reverse_iterator(this);
return const_reverse_iterator(this, set->rend());
}
const_iterator find(const T& t) const {
if (!set)
return const_iterator(this);
return const_iterator(this, set->find(t));
}
const_iterator lower_bound(const T& t) const {
if (!set)
return const_iterator(this);
return const_iterator(this, set->lower_bound(t));
}
const_iterator upper_bound(const T& t) const {
if (!set)
return const_iterator(this);
return const_iterator(this, set->upper_bound(t));
}
void encode(ceph::buffer::list &bl) const {
using ceph::encode;
if (set)
encode(*set, bl);
else
encode((uint32_t)0, bl);
}
void decode(ceph::buffer::list::const_iterator& p) {
using ceph::decode;
uint32_t n;
decode(n, p);
if (n > 0) {
alloc_internal();
ceph::decode_nohead(n, *set, p);
} else
free_internal();
}
};
template<class T, class Set>
inline void encode(const compact_set_base<T, Set>& m, ceph::buffer::list& bl) {
m.encode(bl);
}
template<class T, class Set>
inline void decode(compact_set_base<T, Set>& m, ceph::buffer::list::const_iterator& p) {
m.decode(p);
}
template <class T, class Compare = std::less<T>, class Alloc = std::allocator<T> >
class compact_set : public compact_set_base<T, std::set<T, Compare, Alloc> > {
};
template <class T, class Compare = std::less<T>, class Alloc = std::allocator<T> >
inline std::ostream& operator<<(std::ostream& out, const compact_set<T,Compare,Alloc>& s)
{
bool first = true;
for (auto &v : s) {
if (!first)
out << ",";
out << v;
first = false;
}
return out;
}
#endif
| 8,630 | 27.205882 | 116 | h |
null | ceph-main/src/include/compat.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 Stanislav Sedov <[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_COMPAT_H
#define CEPH_COMPAT_H
#include "acconfig.h"
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#if defined(__linux__)
#define PROCPREFIX
#endif
#include <fcntl.h>
#ifndef F_OFD_SETLK
#define F_OFD_SETLK F_SETLK
#endif
#include <sys/stat.h>
#ifdef _WIN32
#include "include/win32/fs_compat.h"
#endif
#ifndef ACCESSPERMS
#define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO)
#endif
#ifndef ALLPERMS
#define ALLPERMS (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
#endif
#if defined(__FreeBSD__)
// FreeBSD supports Linux procfs with its compatibility module
// And all compatibility stuff is standard mounted on this
#define PROCPREFIX "/compat/linux"
#ifndef MSG_MORE
#define MSG_MORE 0
#endif
#ifndef O_DSYNC
#define O_DSYNC O_SYNC
#endif
/* And include the extra required include file */
#include <pthread_np.h>
#include <sys/param.h>
#include <sys/cpuset.h>
#define cpu_set_t cpuset_t
int sched_setaffinity(pid_t pid, size_t cpusetsize,
cpu_set_t *mask);
#endif /* __FreeBSD__ */
#if defined(__APPLE__)
struct cpu_set_t;
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
/* Make sure that ENODATA is defined in the correct way */
#ifdef ENODATA
#if (ENODATA == 9919)
// #warning ENODATA already defined to be 9919, redefining to fix
// Silencing this warning because it fires at all files where compat.h
// is included after boost files.
//
// This value stems from the definition in the boost library
// And when this case occurs it is due to the fact that boost files
// are included before this file. Redefinition might not help in this
// case since already parsed code has evaluated to the wrong value.
// This would warrrant for d definition that would actually be evaluated
// at the location of usage and report a possible conflict.
// This is left up to a future improvement
#elif (ENODATA != 87)
// #warning ENODATA already defined to a value different from 87 (ENOATRR), refining to fix
#endif
#undef ENODATA
#endif
#define ENODATA ENOATTR
// Fix clock accuracy
#if !defined(CLOCK_MONOTONIC_COARSE)
#if defined(CLOCK_MONOTONIC_FAST)
#define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC_FAST
#else
#define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
#endif
#endif
#if !defined(CLOCK_REALTIME_COARSE)
#if defined(CLOCK_REALTIME_FAST)
#define CLOCK_REALTIME_COARSE CLOCK_REALTIME_FAST
#else
#define CLOCK_REALTIME_COARSE CLOCK_REALTIME
#endif
#endif
/* get PATH_MAX */
#include <limits.h>
#ifndef EUCLEAN
#define EUCLEAN 117
#endif
#ifndef EREMOTEIO
#define EREMOTEIO 121
#endif
#ifndef EKEYREJECTED
#define EKEYREJECTED 129
#endif
#ifndef XATTR_CREATE
#define XATTR_CREATE 1
#endif
#endif /* __APPLE__ */
#ifndef HOST_NAME_MAX
#ifdef MAXHOSTNAMELEN
#define HOST_NAME_MAX MAXHOSTNAMELEN
#else
#define HOST_NAME_MAX 255
#endif
#endif /* HOST_NAME_MAX */
/* O_LARGEFILE is not defined/required on OSX/FreeBSD */
#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif
/* Could be relevant for other platforms */
#ifndef ERESTART
#define ERESTART EINTR
#endif
#ifndef TEMP_FAILURE_RETRY
#define TEMP_FAILURE_RETRY(expression) ({ \
__typeof(expression) __result; \
do { \
__result = (expression); \
} while (__result == -1 && errno == EINTR); \
__result; })
#endif
#ifdef __cplusplus
# define VOID_TEMP_FAILURE_RETRY(expression) \
static_cast<void>(TEMP_FAILURE_RETRY(expression))
#else
# define VOID_TEMP_FAILURE_RETRY(expression) \
do { (void)TEMP_FAILURE_RETRY(expression); } while (0)
#endif
#if defined(__FreeBSD__) || defined(__APPLE__)
#define lseek64(fd, offset, whence) lseek(fd, offset, whence)
#endif
#if defined(__sun) || defined(_AIX)
#define LOG_AUTHPRIV (10<<3)
#define LOG_FTP (11<<3)
#define __STRING(x) "x"
#endif
#if defined(__sun) || defined(_AIX) || defined(_WIN32)
#define IFTODT(mode) (((mode) & 0170000) >> 12)
#endif
#if defined(_AIX)
#define MSG_DONTWAIT MSG_NONBLOCK
#endif
#if defined(HAVE_PTHREAD_SETNAME_NP)
#if defined(__APPLE__)
#define ceph_pthread_setname(thread, name) ({ \
int __result = 0; \
if (thread == pthread_self()) \
__result = pthread_setname_np(name); \
__result; })
#else
#define ceph_pthread_setname pthread_setname_np
#endif
#elif defined(HAVE_PTHREAD_SET_NAME_NP)
/* Fix a small name diff and return 0 */
#define ceph_pthread_setname(thread, name) ({ \
pthread_set_name_np(thread, name); \
0; })
#else
/* compiler warning free success noop */
#define ceph_pthread_setname(thread, name) ({ \
int __i = 0; \
__i; })
#endif
#if defined(HAVE_PTHREAD_GETNAME_NP)
#define ceph_pthread_getname pthread_getname_np
#elif defined(HAVE_PTHREAD_GET_NAME_NP)
#define ceph_pthread_getname(thread, name, len) ({ \
pthread_get_name_np(thread, name, len); \
0; })
#else
/* compiler warning free success noop */
#define ceph_pthread_getname(thread, name, len) ({ \
if (name != NULL) \
*name = '\0'; \
0; })
#endif
int ceph_posix_fallocate(int fd, off_t offset, off_t len);
#ifdef __cplusplus
extern "C" {
#endif
int pipe_cloexec(int pipefd[2], int flags);
char *ceph_strerror_r(int errnum, char *buf, size_t buflen);
unsigned get_page_size();
// On success, returns the number of bytes written to the buffer. On
// failure, returns -1.
ssize_t get_self_exe_path(char* path, int buff_length);
int ceph_memzero_s(void *dest, size_t destsz, size_t count);
#ifdef __cplusplus
}
#endif
#if defined(_WIN32)
#include "include/win32/winsock_compat.h"
#include <windows.h>
#include <time.h>
#include "include/win32/win32_errno.h"
// There are a few name collisions between Windows headers and Ceph.
// Updating Ceph definitions would be the prefferable fix in order to avoid
// confussion, unless it requires too many changes, in which case we're going
// to redefine Windows values by adding the "WIN32_" prefix.
#define WIN32_DELETE 0x00010000L
#undef DELETE
#define WIN32_ERROR 0
#undef ERROR
#ifndef uint
typedef unsigned int uint;
#endif
typedef _sigset_t sigset_t;
typedef unsigned int blksize_t;
typedef unsigned __int64 blkcnt_t;
typedef unsigned short nlink_t;
typedef long long loff_t;
#define CPU_SETSIZE (sizeof(size_t)*8)
typedef union
{
char cpuset[CPU_SETSIZE/8];
size_t _align;
} cpu_set_t;
struct iovec {
void *iov_base;
size_t iov_len;
};
#define SHUT_RD SD_RECEIVE
#define SHUT_WR SD_SEND
#define SHUT_RDWR SD_BOTH
#ifndef SIGINT
#define SIGINT 2
#endif
#ifndef SIGKILL
#define SIGKILL 9
#endif
#define IOV_MAX 1024
#ifdef __cplusplus
extern "C" {
#endif
ssize_t readv(int fd, const struct iovec *iov, int iov_cnt);
ssize_t writev(int fd, const struct iovec *iov, int iov_cnt);
int fsync(int fd);
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
long int lrand48(void);
int random();
int pipe(int pipefd[2]);
int posix_memalign(void **memptr, size_t alignment, size_t size);
char *strptime(const char *s, const char *format, struct tm *tm);
int chown(const char *path, uid_t owner, gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *path, uid_t owner, gid_t group);
int setenv(const char *name, const char *value, int overwrite);
int geteuid();
int getegid();
int getuid();
int getgid();
#define unsetenv(name) _putenv_s(name, "")
int win_socketpair(int socks[2]);
#ifdef __MINGW32__
extern _CRTIMP errno_t __cdecl _putenv_s(const char *_Name,const char *_Value);
#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define htobe16(x) __builtin_bswap16(x)
#define htole16(x) (x)
#define be16toh(x) __builtin_bswap16(x)
#define le16toh(x) (x)
#define htobe32(x) __builtin_bswap32(x)
#define htole32(x) (x)
#define be32toh(x) __builtin_bswap32(x)
#define le32toh(x) (x)
#define htobe64(x) __builtin_bswap64(x)
#define htole64(x) (x)
#define be64toh(x) __builtin_bswap64(x)
#define le64toh(x) (x)
#endif // defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#endif // __MINGW32__
#ifdef __cplusplus
}
#endif
#define compat_closesocket closesocket
// Use "aligned_free" when freeing memory allocated using posix_memalign or
// _aligned_malloc. Using "free" will crash.
static inline void aligned_free(void* ptr) {
_aligned_free(ptr);
}
// O_CLOEXEC is not defined on Windows. Since handles aren't inherited
// with subprocesses unless explicitly requested, we'll define this
// flag as a no-op.
#define O_CLOEXEC 0
#define SOCKOPT_VAL_TYPE char*
#define DEV_NULL "nul"
#else /* WIN32 */
#define SOCKOPT_VAL_TYPE void*
static inline void aligned_free(void* ptr) {
free(ptr);
}
static inline int compat_closesocket(int fildes) {
return close(fildes);
}
#define DEV_NULL "/dev/null"
#endif /* WIN32 */
/* Supplies code to be run at startup time before invoking main().
* Use as:
*
* CEPH_CONSTRUCTOR(my_constructor) {
* ...some code...
* }
*/
#ifdef _MSC_VER
#pragma section(".CRT$XCU",read)
#define CEPH_CONSTRUCTOR(f) \
static void __cdecl f(void); \
__declspec(allocate(".CRT$XCU")) static void (__cdecl*f##_)(void) = f; \
static void __cdecl f(void)
#else
#define CEPH_CONSTRUCTOR(f) \
static void f(void) __attribute__((constructor)); \
static void f(void)
#endif
/* This should only be used with the socket API. */
static inline int ceph_sock_errno() {
#ifdef _WIN32
return wsae_to_errno(WSAGetLastError());
#else
return errno;
#endif
}
// Needed on Windows when handling binary files. Without it, line
// endings will be replaced and certain characters can be treated as
// EOF.
#ifndef O_BINARY
#define O_BINARY 0
#endif
#endif /* !CEPH_COMPAT_H */
| 10,220 | 23.27791 | 91 | h |
null | ceph-main/src/include/cpp_lib_backport.h | #pragma once
#include <cstring>
#include <type_traits>
namespace std {
#ifndef __cpp_lib_bit_cast
#define __cpp_lib_bit_cast 201806L
/// Create a value of type `To` from the bits of `from`.
template<typename To, typename From>
requires (sizeof(To) == sizeof(From)) &&
std::is_trivially_copyable_v<From> &&
std::is_trivially_copyable_v<To>
[[nodiscard]] constexpr To
bit_cast(const From& from) noexcept {
#if __has_builtin(__builtin_bit_cast)
return __builtin_bit_cast(To, from);
#else
static_assert(std::is_trivially_constructible_v<To>);
To to;
std::memcpy(&to, &from, sizeof(To));
return to;
#endif
}
#endif // __cpp_lib_bit_cast
} // namespace std
| 685 | 21.129032 | 56 | h |
null | ceph-main/src/include/crc32c.h | #ifndef CEPH_CRC32C_H
#define CEPH_CRC32C_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef uint32_t (*ceph_crc32c_func_t)(uint32_t crc, unsigned char const *data, unsigned length);
/*
* this is a static global with the chosen crc32c implementation for
* the given architecture.
*/
extern ceph_crc32c_func_t ceph_crc32c_func;
extern ceph_crc32c_func_t ceph_choose_crc32(void);
/**
* calculate crc32c for data that is entirely 0 (ZERO)
*
* Note: works the same as ceph_crc32c_func for data == nullptr,
* but faster than the optimized assembly on certain architectures.
* This is faster than intel optimized assembly, but not as fast as
* ppc64le optimized assembly.
*
* @param crc initial value
* @param length length of buffer
*/
uint32_t ceph_crc32c_zeros(uint32_t crc, unsigned length);
/**
* calculate crc32c
*
* Note: if the data pointer is NULL, we calculate a crc value as if
* it were zero-filled.
*
* @param crc initial value
* @param data pointer to data buffer
* @param length length of buffer
*/
static inline uint32_t ceph_crc32c(uint32_t crc, unsigned char const *data, unsigned length)
{
#ifndef HAVE_POWER8
if (!data && length > 16)
return ceph_crc32c_zeros(crc, length);
#endif /* HAVE_POWER8 */
return ceph_crc32c_func(crc, data, length);
}
#ifdef __cplusplus
}
#endif
#endif
| 1,356 | 22.396552 | 97 | h |
null | ceph-main/src/include/demangle.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 Allen Samuels <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_INCLUDE_DEMANGLE
#define CEPH_INCLUDE_DEMANGLE
//// Stole this code from http://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
static std::string ceph_demangle(const char* name)
{
int status = -4; // some arbitrary value to eliminate the compiler warning
// enable c++11 by passing the flag -std=c++11 to g++
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return (status == 0) ? res.get() : name ;
}
#else
// does nothing if not g++
static std::string demangle(const char* name)
{
return name;
}
#endif
#endif
| 1,146 | 22.408163 | 109 | h |
null | ceph-main/src/include/dlfcn_compat.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 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 DLFCN_COMPAT_H
#define DLFCN_COMPAT_H
#include "acconfig.h"
#define SHARED_LIB_SUFFIX CMAKE_SHARED_LIBRARY_SUFFIX
#ifdef _WIN32
#include <string>
using dl_errmsg_t = std::string;
// The load mode flags will be ignored on Windows. We keep the same
// values for debugging purposes though.
#define RTLD_LAZY 0x00001
#define RTLD_NOW 0x00002
#define RTLD_BINDING_MASK 0x3
#define RTLD_NOLOAD 0x00004
#define RTLD_DEEPBIND 0x00008
#define RTLD_GLOBAL 0x00100
#define RTLD_LOCAL 0
#define RTLD_NODELETE 0x01000
void* dlopen(const char *filename, int flags);
int dlclose(void* handle);
dl_errmsg_t dlerror();
void* dlsym(void* handle, const char* symbol);
#else
#include <dlfcn.h>
using dl_errmsg_t = char*;
#endif /* _WIN32 */
#endif /* DLFCN_H */
| 1,234 | 24.204082 | 70 | h |
null | ceph-main/src/include/elist.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_ELIST_H
#define CEPH_ELIST_H
/*
* elist: embedded list.
*
* requirements:
* - elist<T>::item be embedded in the parent class
* - items are _always_ added to the list via the same elist<T>::item at the same
* fixed offset in the class.
* - begin(), front(), back() methods take the member offset as an argument for traversal.
*
*/
#define member_offset(cls, member) ((size_t)(&((cls*)1)->member) - 1)
template<typename T>
class elist {
public:
struct item {
item *_prev, *_next;
item(T i=0) : _prev(this), _next(this) {}
~item() {
ceph_assert(!is_on_list());
}
item(const item& other) = delete;
const item& operator= (const item& right) = delete;
bool empty() const { return _prev == this; }
bool is_on_list() const { return !empty(); }
bool remove_myself() {
if (_next == this) {
ceph_assert(_prev == this);
return false;
}
_next->_prev = _prev;
_prev->_next = _next;
_prev = _next = this;
return true;
}
void insert_after(item *other) {
ceph_assert(other->empty());
other->_prev = this;
other->_next = _next;
_next->_prev = other;
_next = other;
}
void insert_before(item *other) {
ceph_assert(other->empty());
other->_next = this;
other->_prev = _prev;
_prev->_next = other;
_prev = other;
}
T get_item(size_t offset) {
ceph_assert(offset);
return (T)(((char *)this) - offset);
}
};
private:
item _head;
size_t item_offset;
public:
elist(const elist& other);
const elist& operator=(const elist& other);
elist(size_t o) : _head(NULL), item_offset(o) {}
~elist() {
ceph_assert(_head.empty());
}
bool empty() const {
return _head.empty();
}
void clear() {
while (!_head.empty())
pop_front();
}
void push_front(item *i) {
if (!i->empty())
i->remove_myself();
_head.insert_after(i);
}
void push_back(item *i) {
if (!i->empty())
i->remove_myself();
_head.insert_before(i);
}
T front(size_t o=0) {
ceph_assert(!_head.empty());
return _head._next->get_item(o ? o : item_offset);
}
T back(size_t o=0) {
ceph_assert(!_head.empty());
return _head._prev->get_item(o ? o : item_offset);
}
void pop_front() {
ceph_assert(!empty());
_head._next->remove_myself();
}
void pop_back() {
ceph_assert(!empty());
_head._prev->remove_myself();
}
void clear_list() {
while (!empty())
pop_front();
}
enum mode_t {
MAGIC, CURRENT, CACHE_NEXT
};
class iterator {
private:
item *head;
item *cur, *next;
size_t item_offset;
mode_t mode;
public:
iterator(item *h, size_t o, mode_t m) :
head(h), cur(h->_next), next(cur->_next), item_offset(o),
mode(m) {
ceph_assert(item_offset > 0);
}
T operator*() {
return cur->get_item(item_offset);
}
iterator& operator++() {
ceph_assert(cur);
ceph_assert(cur != head);
if (mode == MAGIC) {
// if 'cur' appears to be valid, use that. otherwise,
// use cached 'next'.
// this is a bit magic, and probably a bad idea... :/
if (cur->empty())
cur = next;
else
cur = cur->_next;
} else if (mode == CURRENT)
cur = cur->_next;
else if (mode == CACHE_NEXT)
cur = next;
else
ceph_abort();
next = cur->_next;
return *this;
}
bool end() const {
return cur == head;
}
};
iterator begin(size_t o=0) {
return iterator(&_head, o ? o : item_offset, MAGIC);
}
iterator begin_use_current(size_t o=0) {
return iterator(&_head, o ? o : item_offset, CURRENT);
}
iterator begin_cache_next(size_t o=0) {
return iterator(&_head, o ? o : item_offset, CACHE_NEXT);
}
};
#endif
| 4,262 | 20.974227 | 92 | h |
null | ceph-main/src/include/error.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 <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SYSERROR() syserror("At %s:%d", __FILE__, __LINE__)
#define ASSERT(c) \
((c) || (exiterror("Assertion failed at %s:%d", __FILE__, __LINE__), 1))
/* print usage error message and exit */
extern void userror(const char *use, const char *fmt, ...);
/* print system error message and exit */
extern void syserror(const char *fmt, ...);
/* print error message and exit */
extern void exiterror(const char *fmt, ...);
/* print error message */
extern void error(const char *fmt, ...);
#ifdef __cplusplus
} // extern "C"
#endif
| 1,034 | 23.642857 | 74 | h |
null | ceph-main/src/include/event_type.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_TYPE_H
#define CEPH_COMMON_EVENT_TYPE_H
#define EVENT_SOCKET_TYPE_NONE 0
#define EVENT_SOCKET_TYPE_PIPE 1
#define EVENT_SOCKET_TYPE_EVENTFD 2
#endif
| 640 | 24.64 | 70 | h |
null | ceph-main/src/include/filepath.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_FILEPATH_H
#define CEPH_FILEPATH_H
/*
* BUG: /a/b/c is equivalent to a/b/c in dentry-breakdown, but not string.
* -> should it be different? how? should this[0] be "", with depth 4?
*
*/
#include <iosfwd>
#include <string>
#include <string_view>
#include <vector>
#include "buffer.h"
#include "encoding.h"
#include "include/types.h"
#include "include/fs_types.h"
#include "common/Formatter.h"
class filepath {
inodeno_t ino = 0; // base inode. ino=0 implies pure relative path.
std::string path; // relative path.
/** bits - path segments
* this is ['a', 'b', 'c'] for both the aboslute and relative case.
*
* NOTE: this value is LAZILY maintained... i.e. it's a cache
*/
mutable std::vector<std::string> bits;
bool encoded = false;
void rebuild_path() {
path.clear();
for (unsigned i=0; i<bits.size(); i++) {
if (i) path += "/";
path += bits[i];
}
}
void parse_bits() const {
bits.clear();
int off = 0;
while (off < (int)path.length()) {
int nextslash = path.find('/', off);
if (nextslash < 0)
nextslash = path.length(); // no more slashes
if (((nextslash - off) > 0) || encoded) {
// skip empty components unless they were introduced deliberately
// see commit message for more detail
bits.push_back( path.substr(off,nextslash-off) );
}
off = nextslash+1;
}
}
public:
filepath() = default;
filepath(std::string_view p, inodeno_t i) : ino(i), path(p) {}
filepath(const filepath& o) {
ino = o.ino;
path = o.path;
bits = o.bits;
encoded = o.encoded;
}
filepath(inodeno_t i) : ino(i) {}
filepath& operator=(const char* path) {
set_path(path);
return *this;
}
/*
* if we are fed a relative path as a string, either set ino=0 (strictly
* relative) or 1 (absolute). throw out any leading '/'.
*/
filepath(std::string_view s) { set_path(s); }
filepath(const char* s) { set_path(s); }
void set_path(std::string_view s, inodeno_t b) {
path = s;
ino = b;
}
void set_path(std::string_view s) {
if (s[0] == '/') {
path = s.substr(1);
ino = 1;
} else {
ino = 0;
path = s;
}
bits.clear();
}
// accessors
inodeno_t get_ino() const { return ino; }
const std::string& get_path() const { return path; }
const char *c_str() const { return path.c_str(); }
int length() const { return path.length(); }
unsigned depth() const {
if (bits.empty() && path.length() > 0) parse_bits();
return bits.size();
}
bool empty() const { return path.length() == 0 && ino == 0; }
bool absolute() const { return ino == 1; }
bool pure_relative() const { return ino == 0; }
bool ino_relative() const { return ino > 0; }
const std::string& operator[](int i) const {
if (bits.empty() && path.length() > 0) parse_bits();
return bits[i];
}
const std::string& last_dentry() const {
if (bits.empty() && path.length() > 0) parse_bits();
ceph_assert(!bits.empty());
return bits[ bits.size()-1 ];
}
filepath prefixpath(int s) const {
filepath t(ino);
for (int i=0; i<s; i++)
t.push_dentry(bits[i]);
return t;
}
filepath postfixpath(int s) const {
filepath t;
for (unsigned i=s; i<bits.size(); i++)
t.push_dentry(bits[i]);
return t;
}
// modifiers
// string can be relative "a/b/c" (ino=0) or absolute "/a/b/c" (ino=1)
void _set_ino(inodeno_t i) { ino = i; }
void clear() {
ino = 0;
path = "";
bits.clear();
}
void pop_dentry() {
if (bits.empty() && path.length() > 0)
parse_bits();
bits.pop_back();
rebuild_path();
}
void push_dentry(std::string_view s) {
if (bits.empty() && path.length() > 0)
parse_bits();
if (!bits.empty())
path += "/";
path += s;
bits.emplace_back(s);
}
void push_dentry(const std::string& s) {
push_dentry(std::string_view(s));
}
void push_dentry(const char *cs) {
push_dentry(std::string_view(cs, strlen(cs)));
}
void push_front_dentry(const std::string& s) {
bits.insert(bits.begin(), s);
rebuild_path();
}
void append(const filepath& a) {
ceph_assert(a.pure_relative());
for (unsigned i=0; i<a.depth(); i++)
push_dentry(a[i]);
}
// encoding
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
__u8 struct_v = 1;
encode(struct_v, bl);
encode(ino, bl);
encode(path, bl);
}
void decode(ceph::buffer::list::const_iterator& blp) {
using ceph::decode;
bits.clear();
__u8 struct_v;
decode(struct_v, blp);
decode(ino, blp);
decode(path, blp);
encoded = true;
}
void dump(ceph::Formatter *f) const {
f->dump_unsigned("base_ino", ino);
f->dump_string("relative_path", path);
}
static void generate_test_instances(std::list<filepath*>& o) {
o.push_back(new filepath);
o.push_back(new filepath("/usr/bin", 0));
o.push_back(new filepath("/usr/sbin", 1));
o.push_back(new filepath("var/log", 1));
o.push_back(new filepath("foo/bar", 101));
}
bool is_last_dot_or_dotdot() const {
if (depth() > 0) {
std::string dname = last_dentry();
if (dname == "." || dname == "..") {
return true;
}
}
return false;
}
bool is_last_snap() const {
// walk into snapdir?
return depth() > 0 && bits[0].length() == 0;
}
};
WRITE_CLASS_ENCODER(filepath)
inline std::ostream& operator<<(std::ostream& out, const filepath& path)
{
if (path.get_ino()) {
out << '#' << path.get_ino();
if (path.length())
out << '/';
}
return out << path.get_path();
}
#endif
| 6,138 | 23.458167 | 75 | h |
null | ceph-main/src/include/frag.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_FRAG_H
#define CEPH_FRAG_H
#include <boost/container/small_vector.hpp>
#include <iostream>
#include <stdint.h>
#include <stdio.h>
#include "buffer.h"
#include "compact_map.h"
#include "ceph_frag.h"
#include "include/encoding.h"
#include "include/ceph_assert.h"
#include "common/dout.h"
/*
*
* the goal here is to use a binary split strategy to partition a namespace.
* frag_t represents a particular fragment. bits() tells you the size of the
* fragment, and value() it's name. this is roughly analogous to an ip address
* and netmask.
*
* fragtree_t represents an entire namespace and it's partition. it essentially
* tells you where fragments are split into other fragments, and by how much
* (i.e. by how many bits, resulting in a power of 2 number of child fragments).
*
* this vaguely resembles a btree, in that when a fragment becomes large or small
* we can split or merge, except that there is no guarantee of being balanced.
*
* presumably we are partitioning the output of a (perhaps specialized) hash
* function.
*/
/**
* frag_t
*
* description of an individual fragment. that is, a particular piece
* of the overall namespace.
*
* this is conceptually analogous to an ip address and netmask.
*
* a value v falls "within" fragment f iff (v & f.mask()) == f.value().
*
* we write it as v/b, where v is a value and b is the number of bits.
* 0/0 (bits==0) corresponds to the entire namespace. if we bisect that,
* we get 0/1 and 1/1. quartering gives us 0/2, 1/2, 2/2, 3/2. and so on.
*
* this makes the right most bit of v the "most significant", which is the
* opposite of what we usually see.
*/
/*
* TODO:
* - get_first_child(), next_sibling(int parent_bits) to make (possibly partial)
* iteration efficient (see, e.g., try_assimilate_children()
* - rework frag_t so that we mask the left-most (most significant) bits instead of
* the right-most (least significant) bits. just because it's more intuitive, and
* matches the network/netmask concept.
*/
class frag_t {
/*
* encoding is dictated by frag_* functions in ceph_fs.h. use those
* helpers _exclusively_.
*/
public:
using _frag_t = uint32_t;
frag_t() = default;
frag_t(unsigned v, unsigned b) : _enc(ceph_frag_make(b, v)) { }
frag_t(_frag_t e) : _enc(e) { }
// constructors
void from_unsigned(unsigned e) { _enc = e; }
// accessors
unsigned value() const { return ceph_frag_value(_enc); }
unsigned bits() const { return ceph_frag_bits(_enc); }
unsigned mask() const { return ceph_frag_mask(_enc); }
unsigned mask_shift() const { return ceph_frag_mask_shift(_enc); }
operator _frag_t() const { return _enc; }
// tests
bool contains(unsigned v) const { return ceph_frag_contains_value(_enc, v); }
bool contains(frag_t sub) const { return ceph_frag_contains_frag(_enc, sub._enc); }
bool is_root() const { return bits() == 0; }
frag_t parent() const {
ceph_assert(bits() > 0);
return frag_t(ceph_frag_parent(_enc));
}
// splitting
frag_t make_child(int i, int nb) const {
ceph_assert(i < (1<<nb));
return frag_t(ceph_frag_make_child(_enc, nb, i));
}
template<typename T>
void split(int nb, T& fragments) const {
ceph_assert(nb > 0);
unsigned nway = 1 << nb;
for (unsigned i=0; i<nway; i++)
fragments.push_back(make_child(i, nb));
}
// binary splitting
frag_t left_child() const { return frag_t(ceph_frag_left_child(_enc)); }
frag_t right_child() const { return frag_t(ceph_frag_right_child(_enc)); }
bool is_left() const { return ceph_frag_is_left_child(_enc); }
bool is_right() const { return ceph_frag_is_right_child(_enc); }
frag_t get_sibling() const {
ceph_assert(!is_root());
return frag_t(ceph_frag_sibling(_enc));
}
// sequencing
bool is_leftmost() const { return ceph_frag_is_leftmost(_enc); }
bool is_rightmost() const { return ceph_frag_is_rightmost(_enc); }
frag_t next() const {
ceph_assert(!is_rightmost());
return frag_t(ceph_frag_next(_enc));
}
// parse
bool parse(const char *s) {
int pvalue, pbits;
int r = sscanf(s, "%x/%d", &pvalue, &pbits);
if (r == 2) {
*this = frag_t(pvalue, pbits);
return true;
}
return false;
}
void encode(ceph::buffer::list& bl) const {
ceph::encode_raw(_enc, bl);
}
void decode(ceph::buffer::list::const_iterator& p) {
__u32 v;
ceph::decode_raw(v, p);
_enc = v;
}
bool operator<(const frag_t& b) const
{
if (value() != b.value())
return value() < b.value();
else
return bits() < b.bits();
}
private:
_frag_t _enc = 0;
};
WRITE_CLASS_ENCODER(frag_t)
inline std::ostream& operator<<(std::ostream& out, const frag_t& hb)
{
//out << std::hex << hb.value() << std::dec << "/" << hb.bits() << '=';
unsigned num = hb.bits();
if (num) {
unsigned val = hb.value();
for (unsigned bit = 23; num; num--, bit--)
out << ((val & (1<<bit)) ? '1':'0');
}
return out << '*';
}
using frag_vec_t = boost::container::small_vector<frag_t, 4>;
/**
* fragtree_t -- partition an entire namespace into one or more frag_t's.
*/
class fragtree_t {
// pairs <f, b>:
// frag_t f is split by b bits.
// if child frag_t does not appear, it is not split.
public:
compact_map<frag_t,int32_t> _splits;
public:
// -------------
// basics
void swap(fragtree_t& other) {
_splits.swap(other._splits);
}
void clear() {
_splits.clear();
}
// -------------
// accessors
bool empty() const {
return _splits.empty();
}
int get_split(const frag_t hb) const {
compact_map<frag_t,int32_t>::const_iterator p = _splits.find(hb);
if (p == _splits.end())
return 0;
else
return p->second;
}
bool is_leaf(frag_t x) const {
frag_vec_t s;
get_leaves_under(x, s);
//generic_dout(10) << "is_leaf(" << x << ") -> " << ls << dendl;
return s.size() == 1 && s.front() == x;
}
/**
* get_leaves -- list all leaves
*/
template<typename T>
void get_leaves(T& c) const {
return get_leaves_under_split(frag_t(), c);
}
/**
* get_leaves_under_split -- list all leaves under a known split point (or root)
*/
template<typename T>
void get_leaves_under_split(frag_t under, T& c) const {
frag_vec_t s;
s.push_back(under);
while (!s.empty()) {
frag_t t = s.back();
s.pop_back();
int nb = get_split(t);
if (nb)
t.split(nb, s); // queue up children
else
c.push_back(t); // not spit, it's a leaf.
}
}
/**
* get_branch -- get branch point at OR above frag @a x
* - may be @a x itself, if @a x is a split
* - may be root (frag_t())
*/
frag_t get_branch(frag_t x) const {
while (1) {
if (x == frag_t()) return x; // root
if (get_split(x)) return x; // found it!
x = x.parent();
}
}
/**
* get_branch_above -- get a branch point above frag @a x
* - may be root (frag_t())
* - may NOT be @a x, even if @a x is a split.
*/
frag_t get_branch_above(frag_t x) const {
while (1) {
if (x == frag_t()) return x; // root
x = x.parent();
if (get_split(x)) return x; // found it!
}
}
/**
* get_branch_or_leaf -- get branch or leaf point parent for frag @a x
* - may be @a x itself, if @a x is a split or leaf
* - may be root (frag_t())
*/
frag_t get_branch_or_leaf(frag_t x) const {
frag_t branch = get_branch(x);
int nb = get_split(branch);
if (nb > 0 && // if branch is a split, and
branch.bits() + nb <= x.bits()) // one of the children is or contains x
return frag_t(x.value(), branch.bits()+nb); // then return that child (it's a leaf)
else
return branch;
}
/**
* get_leaves_under(x, ls) -- search for any leaves fully contained by x
*/
template<typename T>
void get_leaves_under(frag_t x, T& c) const {
frag_vec_t s;
s.push_back(get_branch_or_leaf(x));
while (!s.empty()) {
frag_t t = s.back();
s.pop_back();
if (t.bits() >= x.bits() && // if t is more specific than x, and
!x.contains(t)) // x does not contain t,
continue; // then skip
int nb = get_split(t);
if (nb)
t.split(nb, s); // queue up children
else if (x.contains(t))
c.push_back(t); // not spit, it's a leaf.
}
}
/**
* contains(fg) -- does fragtree contain the specific frag @a x
*/
bool contains(frag_t x) const {
frag_vec_t s;
s.push_back(get_branch(x));
while (!s.empty()) {
frag_t t = s.back();
s.pop_back();
if (t.bits() >= x.bits() && // if t is more specific than x, and
!x.contains(t)) // x does not contain t,
continue; // then skip
int nb = get_split(t);
if (nb) {
if (t == x) return false; // it's split.
t.split(nb, s); // queue up children
} else {
if (t == x) return true; // it's there.
}
}
return false;
}
/**
* operator[] -- map a (hash?) value to a frag
*/
frag_t operator[](unsigned v) const {
frag_t t;
while (1) {
ceph_assert(t.contains(v));
int nb = get_split(t);
// is this a leaf?
if (nb == 0) return t; // done.
// pick appropriate child fragment.
unsigned nway = 1 << nb;
unsigned i;
for (i=0; i<nway; i++) {
frag_t n = t.make_child(i, nb);
if (n.contains(v)) {
t = n;
break;
}
}
ceph_assert(i < nway);
}
}
// ---------------
// modifiers
void split(frag_t x, int b, bool simplify=true) {
ceph_assert(is_leaf(x));
_splits[x] = b;
if (simplify)
try_assimilate_children(get_branch_above(x));
}
void merge(frag_t x, int b, bool simplify=true) {
ceph_assert(!is_leaf(x));
ceph_assert(_splits[x] == b);
_splits.erase(x);
if (simplify)
try_assimilate_children(get_branch_above(x));
}
/*
* if all of a given split's children are identically split,
* then the children can be assimilated.
*/
void try_assimilate_children(frag_t x) {
int nb = get_split(x);
if (!nb) return;
frag_vec_t children;
x.split(nb, children);
int childbits = 0;
for (auto& frag : children) {
int cb = get_split(frag);
if (!cb) return; // nope.
if (childbits && cb != childbits) return; // not the same
childbits = cb;
}
// all children are split with childbits!
for (auto& frag : children)
_splits.erase(frag);
_splits[x] += childbits;
}
bool force_to_leaf(CephContext *cct, frag_t x) {
if (is_leaf(x))
return false;
lgeneric_dout(cct, 10) << "force_to_leaf " << x << " on " << _splits << dendl;
frag_t parent = get_branch_or_leaf(x);
ceph_assert(parent.bits() <= x.bits());
lgeneric_dout(cct, 10) << "parent is " << parent << dendl;
// do we need to split from parent to x?
if (parent.bits() < x.bits()) {
int spread = x.bits() - parent.bits();
int nb = get_split(parent);
lgeneric_dout(cct, 10) << "spread " << spread << ", parent splits by " << nb << dendl;
if (nb == 0) {
// easy: split parent (a leaf) by the difference
lgeneric_dout(cct, 10) << "splitting parent " << parent << " by spread " << spread << dendl;
split(parent, spread);
ceph_assert(is_leaf(x));
return true;
}
ceph_assert(nb > spread);
// add an intermediary split
merge(parent, nb, false);
split(parent, spread, false);
frag_vec_t subs;
parent.split(spread, subs);
for (auto& frag : subs) {
lgeneric_dout(cct, 10) << "splitting intermediate " << frag << " by " << (nb-spread) << dendl;
split(frag, nb - spread, false);
}
}
// x is now a leaf or split.
// hoover up any children.
frag_vec_t s;
s.push_back(x);
while (!s.empty()) {
frag_t t = s.back();
s.pop_back();
int nb = get_split(t);
if (nb) {
lgeneric_dout(cct, 10) << "merging child " << t << " by " << nb << dendl;
merge(t, nb, false); // merge this point, and
t.split(nb, s); // queue up children
}
}
lgeneric_dout(cct, 10) << "force_to_leaf done" << dendl;
ceph_assert(is_leaf(x));
return true;
}
// encoding
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
encode(_splits, bl);
}
void decode(ceph::buffer::list::const_iterator& p) {
using ceph::decode;
decode(_splits, p);
}
void encode_nohead(ceph::buffer::list& bl) const {
using ceph::encode;
for (compact_map<frag_t,int32_t>::const_iterator p = _splits.begin();
p != _splits.end();
++p) {
encode(p->first, bl);
encode(p->second, bl);
}
}
void decode_nohead(int n, ceph::buffer::list::const_iterator& p) {
using ceph::decode;
_splits.clear();
while (n-- > 0) {
frag_t f;
decode(f, p);
decode(_splits[f], p);
}
}
void print(std::ostream& out) {
out << "fragtree_t(";
frag_vec_t s;
s.push_back(frag_t());
while (!s.empty()) {
frag_t t = s.back();
s.pop_back();
// newline + indent?
if (t.bits()) {
out << std::endl;
for (unsigned i=0; i<t.bits(); i++) out << ' ';
}
int nb = get_split(t);
if (nb) {
out << t << " %" << nb;
t.split(nb, s); // queue up children
} else {
out << t;
}
}
out << ")";
}
void dump(ceph::Formatter *f) const {
f->open_array_section("splits");
for (auto p = _splits.begin(); p != _splits.end(); ++p) {
f->open_object_section("split");
std::ostringstream frag_str;
frag_str << p->first;
f->dump_string("frag", frag_str.str());
f->dump_int("children", p->second);
f->close_section(); // split
}
f->close_section(); // splits
}
};
WRITE_CLASS_ENCODER(fragtree_t)
inline bool operator==(const fragtree_t& l, const fragtree_t& r) {
return l._splits == r._splits;
}
inline bool operator!=(const fragtree_t& l, const fragtree_t& r) {
return l._splits != r._splits;
}
inline std::ostream& operator<<(std::ostream& out, const fragtree_t& ft)
{
out << "fragtree_t(";
for (compact_map<frag_t,int32_t>::const_iterator p = ft._splits.begin();
p != ft._splits.end();
++p) {
if (p != ft._splits.begin())
out << " ";
out << p->first << "^" << p->second;
}
return out << ")";
}
/**
* fragset_t -- a set of fragments
*/
class fragset_t {
std::set<frag_t> _set;
public:
const std::set<frag_t> &get() const { return _set; }
std::set<frag_t>::const_iterator begin() const { return _set.begin(); }
std::set<frag_t>::const_iterator end() const { return _set.end(); }
bool empty() const { return _set.empty(); }
bool contains(frag_t f) const {
while (1) {
if (_set.count(f)) return true;
if (f.bits() == 0) return false;
f = f.parent();
}
}
void clear() {
_set.clear();
}
void insert_raw(frag_t f){
_set.insert(f);
}
void insert(frag_t f) {
_set.insert(f);
simplify();
}
void simplify() {
auto it = _set.begin();
while (it != _set.end()) {
if (!it->is_root() &&
_set.count(it->get_sibling())) {
_set.erase(it->get_sibling());
auto ret = _set.insert(it->parent());
_set.erase(it);
it = ret.first;
} else {
++it;
}
}
}
void encode(ceph::buffer::list& bl) const {
ceph::encode(_set, bl);
}
void decode(ceph::buffer::list::const_iterator& p) {
ceph::decode(_set, p);
}
};
WRITE_CLASS_ENCODER(fragset_t)
inline std::ostream& operator<<(std::ostream& out, const fragset_t& fs)
{
return out << "fragset_t(" << fs.get() << ")";
}
#endif
| 16,190 | 25.284091 | 95 | h |
null | ceph-main/src/include/fs_types.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_INCLUDE_FS_TYPES_H
#define CEPH_INCLUDE_FS_TYPES_H
#include "types.h"
class JSONObj;
#define CEPHFS_EBLOCKLISTED 108
#define CEPHFS_EPERM 1
#define CEPHFS_ESTALE 116
#define CEPHFS_ENOSPC 28
#define CEPHFS_ETIMEDOUT 110
#define CEPHFS_EIO 5
#define CEPHFS_ENOTCONN 107
#define CEPHFS_EEXIST 17
#define CEPHFS_EINTR 4
#define CEPHFS_EINVAL 22
#define CEPHFS_EBADF 9
#define CEPHFS_EROFS 30
#define CEPHFS_EAGAIN 11
#define CEPHFS_EACCES 13
#define CEPHFS_ELOOP 40
#define CEPHFS_EISDIR 21
#define CEPHFS_ENOENT 2
#define CEPHFS_ENOTDIR 20
#define CEPHFS_ENAMETOOLONG 36
#define CEPHFS_EBUSY 16
#define CEPHFS_EDQUOT 122
#define CEPHFS_EFBIG 27
#define CEPHFS_ERANGE 34
#define CEPHFS_ENXIO 6
#define CEPHFS_ECANCELED 125
#define CEPHFS_ENODATA 61
#define CEPHFS_EOPNOTSUPP 95
#define CEPHFS_EXDEV 18
#define CEPHFS_ENOMEM 12
#define CEPHFS_ENOTRECOVERABLE 131
#define CEPHFS_ENOSYS 38
#define CEPHFS_EWOULDBLOCK CEPHFS_EAGAIN
#define CEPHFS_ENOTEMPTY 39
#define CEPHFS_EDEADLK 35
#define CEPHFS_EDEADLOCK CEPHFS_EDEADLK
#define CEPHFS_EDOM 33
#define CEPHFS_EMLINK 31
#define CEPHFS_ETIME 62
#define CEPHFS_EOLDSNAPC 85
#define CEPHFS_EFAULT 14
#define CEPHFS_EISCONN 106
#define CEPHFS_EMULTIHOP 72
// taken from linux kernel: include/uapi/linux/fcntl.h
#define CEPHFS_AT_FDCWD -100 /* Special value used to indicate
openat should use the current
working directory. */
// --------------------------------------
// ino
typedef uint64_t _inodeno_t;
struct inodeno_t {
_inodeno_t val;
inodeno_t() : val(0) {}
// cppcheck-suppress noExplicitConstructor
inodeno_t(_inodeno_t v) : val(v) {}
inodeno_t operator+=(inodeno_t o) { val += o.val; return *this; }
operator _inodeno_t() const { return val; }
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
encode(val, bl);
}
void decode(ceph::buffer::list::const_iterator& p) {
using ceph::decode;
decode(val, p);
}
} __attribute__ ((__may_alias__));
WRITE_CLASS_ENCODER(inodeno_t)
template<>
struct denc_traits<inodeno_t> {
static constexpr bool supported = true;
static constexpr bool featured = false;
static constexpr bool bounded = true;
static constexpr bool need_contiguous = true;
static void bound_encode(const inodeno_t &o, size_t& p) {
denc(o.val, p);
}
static void encode(const inodeno_t &o, ceph::buffer::list::contiguous_appender& p) {
denc(o.val, p);
}
static void decode(inodeno_t& o, ceph::buffer::ptr::const_iterator &p) {
denc(o.val, p);
}
};
inline std::ostream& operator<<(std::ostream& out, const inodeno_t& ino) {
return out << std::hex << "0x" << ino.val << std::dec;
}
namespace std {
template<>
struct hash<inodeno_t> {
size_t operator()( const inodeno_t& x ) const {
static rjhash<uint64_t> H;
return H(x.val);
}
};
} // namespace std
// file modes
inline bool file_mode_is_readonly(int mode) {
return (mode & CEPH_FILE_MODE_WR) == 0;
}
// dentries
#define MAX_DENTRY_LEN 255
// --
namespace ceph {
class Formatter;
}
void dump(const ceph_file_layout& l, ceph::Formatter *f);
void dump(const ceph_dir_layout& l, ceph::Formatter *f);
// file_layout_t
struct file_layout_t {
// file -> object mapping
uint32_t stripe_unit; ///< stripe unit, in bytes,
uint32_t stripe_count; ///< over this many objects
uint32_t object_size; ///< until objects are this big
int64_t pool_id; ///< rados pool id
std::string pool_ns; ///< rados pool namespace
file_layout_t(uint32_t su=0, uint32_t sc=0, uint32_t os=0)
: stripe_unit(su),
stripe_count(sc),
object_size(os),
pool_id(-1) {
}
bool operator==(const file_layout_t&) const = default;
static file_layout_t get_default() {
return file_layout_t(1<<22, 1, 1<<22);
}
uint64_t get_period() const {
return static_cast<uint64_t>(stripe_count) * object_size;
}
void from_legacy(const ceph_file_layout& fl);
void to_legacy(ceph_file_layout *fl) const;
bool is_valid() const;
void encode(ceph::buffer::list& bl, uint64_t features) const;
void decode(ceph::buffer::list::const_iterator& p);
void dump(ceph::Formatter *f) const;
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<file_layout_t*>& o);
};
WRITE_CLASS_ENCODER_FEATURES(file_layout_t)
std::ostream& operator<<(std::ostream& out, const file_layout_t &layout);
#endif
| 4,912 | 26.914773 | 86 | h |
null | ceph-main/src/include/hash.h | #ifndef CEPH_HASH_H
#define CEPH_HASH_H
#include "acconfig.h"
// Robert Jenkins' function for mixing 32-bit values
// http://burtleburtle.net/bob/hash/evahash.html
// a, b = random bits, c = input and output
#define hashmix(a,b,c) \
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);
//namespace ceph {
template <class _Key> struct rjhash { };
inline uint64_t rjhash64(uint64_t key) {
key = (~key) + (key << 21); // key = (key << 21) - key - 1;
key = key ^ (key >> 24);
key = (key + (key << 3)) + (key << 8); // key * 265
key = key ^ (key >> 14);
key = (key + (key << 2)) + (key << 4); // key * 21
key = key ^ (key >> 28);
key = key + (key << 31);
return key;
}
inline uint32_t rjhash32(uint32_t a) {
a = (a+0x7ed55d16) + (a<<12);
a = (a^0xc761c23c) ^ (a>>19);
a = (a+0x165667b1) + (a<<5);
a = (a+0xd3a2646c) ^ (a<<9);
a = (a+0xfd7046c5) + (a<<3);
a = (a^0xb55a4f09) ^ (a>>16);
return a;
}
template<> struct rjhash<uint32_t> {
inline size_t operator()(const uint32_t x) const {
return rjhash32(x);
}
};
template<> struct rjhash<uint64_t> {
inline size_t operator()(const uint64_t x) const {
return rjhash64(x);
}
};
//}
#endif
| 1,422 | 20.892308 | 61 | h |
null | ceph-main/src/include/health.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <ostream>
#include <string>
#include "include/encoding.h"
// health_status_t
enum health_status_t {
HEALTH_ERR = 0,
HEALTH_WARN = 1,
HEALTH_OK = 2,
};
inline void encode(health_status_t hs, ceph::buffer::list& bl) {
using ceph::encode;
uint8_t v = hs;
encode(v, bl);
}
inline void decode(health_status_t& hs, ceph::buffer::list::const_iterator& p) {
using ceph::decode;
uint8_t v;
decode(v, p);
hs = health_status_t(v);
}
template<>
struct denc_traits<health_status_t> {
static constexpr bool supported = true;
static constexpr bool featured = false;
static constexpr bool bounded = true;
static constexpr bool need_contiguous = false;
static void bound_encode(const ceph::buffer::ptr& v, size_t& p, uint64_t f=0) {
p++;
}
static void encode(const health_status_t& v,
ceph::buffer::list::contiguous_appender& p,
uint64_t f=0) {
::denc((uint8_t)v, p);
}
static void decode(health_status_t& v, ceph::buffer::ptr::const_iterator& p,
uint64_t f=0) {
uint8_t tmp;
::denc(tmp, p);
v = health_status_t(tmp);
}
static void decode(health_status_t& v, ceph::buffer::list::const_iterator& p,
uint64_t f=0) {
uint8_t tmp;
::denc(tmp, p);
v = health_status_t(tmp);
}
};
inline std::ostream& operator<<(std::ostream &oss, const health_status_t status) {
switch (status) {
case HEALTH_ERR:
oss << "HEALTH_ERR";
break;
case HEALTH_WARN:
oss << "HEALTH_WARN";
break;
case HEALTH_OK:
oss << "HEALTH_OK";
break;
}
return oss;
}
inline const char *short_health_string(const health_status_t status) {
switch (status) {
case HEALTH_ERR:
return "ERR";
case HEALTH_WARN:
return "WRN";
case HEALTH_OK:
return "OK";
default:
return "???";
}
}
| 1,930 | 21.988095 | 82 | h |
null | ceph-main/src/include/inline_memory.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_INLINE_MEMORY_H
#define CEPH_INLINE_MEMORY_H
#if defined(__GNUC__)
// optimize for the common case, which is very small copies
static inline void *maybe_inline_memcpy(void *dest, const void *src, size_t l,
size_t inline_len)
__attribute__((always_inline));
void *maybe_inline_memcpy(void *dest, const void *src, size_t l,
size_t inline_len)
{
if (l > inline_len) {
return memcpy(dest, src, l);
}
switch (l) {
case 8:
return __builtin_memcpy(dest, src, 8);
case 4:
return __builtin_memcpy(dest, src, 4);
case 3:
return __builtin_memcpy(dest, src, 3);
case 2:
return __builtin_memcpy(dest, src, 2);
case 1:
return __builtin_memcpy(dest, src, 1);
default:
int cursor = 0;
while (l >= sizeof(uint64_t)) {
__builtin_memcpy((char*)dest + cursor, (char*)src + cursor,
sizeof(uint64_t));
cursor += sizeof(uint64_t);
l -= sizeof(uint64_t);
}
while (l >= sizeof(uint32_t)) {
__builtin_memcpy((char*)dest + cursor, (char*)src + cursor,
sizeof(uint32_t));
cursor += sizeof(uint32_t);
l -= sizeof(uint32_t);
}
while (l > 0) {
*((char*)dest + cursor) = *((char*)src + cursor);
cursor++;
l--;
}
}
return dest;
}
#else
#define maybe_inline_memcpy(d, s, l, x) memcpy(d, s, l)
#endif
#if defined(__GNUC__) && defined(__x86_64__)
namespace ceph {
typedef unsigned uint128_t __attribute__ ((mode (TI)));
}
using ceph::uint128_t;
static inline bool mem_is_zero(const char *data, size_t len)
__attribute__((always_inline));
bool mem_is_zero(const char *data, size_t len)
{
// we do have XMM registers in x86-64, so if we need to check at least
// 16 bytes, make use of them
if (len / sizeof(uint128_t) > 0) {
// align data pointer to 16 bytes, otherwise it'll segfault due to bug
// in (at least some) GCC versions (using MOVAPS instead of MOVUPS).
// check up to 15 first bytes while at it.
while (((unsigned long long)data) & 15) {
if (*(uint8_t*)data != 0) {
return false;
}
data += sizeof(uint8_t);
--len;
}
const char* data_start = data;
const char* max128 = data + (len / sizeof(uint128_t))*sizeof(uint128_t);
while (data < max128) {
if (*(uint128_t*)data != 0) {
return false;
}
data += sizeof(uint128_t);
}
len -= (data - data_start);
}
const char* max = data + len;
const char* max32 = data + (len / sizeof(uint32_t))*sizeof(uint32_t);
while (data < max32) {
if (*(uint32_t*)data != 0) {
return false;
}
data += sizeof(uint32_t);
}
while (data < max) {
if (*(uint8_t*)data != 0) {
return false;
}
data += sizeof(uint8_t);
}
return true;
}
#else // gcc and x86_64
static inline bool mem_is_zero(const char *data, size_t len) {
const char *end = data + len;
const char* end64 = data + (len / sizeof(uint64_t))*sizeof(uint64_t);
while (data < end64) {
if (*(uint64_t*)data != 0) {
return false;
}
data += sizeof(uint64_t);
}
while (data < end) {
if (*data != 0) {
return false;
}
++data;
}
return true;
}
#endif // !x86_64
#endif
| 3,634 | 23.072848 | 78 | h |
null | ceph-main/src/include/intarith.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_INTARITH_H
#define CEPH_INTARITH_H
#include <bit>
#include <climits>
#include <concepts>
#include <type_traits>
template<typename T, typename U>
constexpr inline std::make_unsigned_t<std::common_type_t<T, U>> div_round_up(T n, U d) {
return (n + d - 1) / d;
}
template<typename T, typename U>
constexpr inline std::make_unsigned_t<std::common_type_t<T, U>> round_up_to(T n, U d) {
return (n % d ? (n + d - n % d) : n);
}
template<typename T, typename U>
constexpr inline std::make_unsigned_t<std::common_type_t<T, U>> shift_round_up(T x, U y) {
return (x + (1 << y) - 1) >> y;
}
/*
* Wrappers for various sorts of alignment and rounding. The "align" must
* be a power of 2. Often times it is a block, sector, or page.
*/
/*
* return x rounded down to an align boundary
* eg, p2align(1200, 1024) == 1024 (1*align)
* eg, p2align(1024, 1024) == 1024 (1*align)
* eg, p2align(0x1234, 0x100) == 0x1200 (0x12*align)
* eg, p2align(0x5600, 0x100) == 0x5600 (0x56*align)
*/
template<typename T>
constexpr inline T p2align(T x, T align) {
return x & -align;
}
/*
* return x % (mod) align
* eg, p2phase(0x1234, 0x100) == 0x34 (x-0x12*align)
* eg, p2phase(0x5600, 0x100) == 0x00 (x-0x56*align)
*/
template<typename T>
constexpr inline T p2phase(T x, T align) {
return x & (align - 1);
}
/*
* return how much space is left in this block (but if it's perfectly
* aligned, return 0).
* eg, p2nphase(0x1234, 0x100) == 0xcc (0x13*align-x)
* eg, p2nphase(0x5600, 0x100) == 0x00 (0x56*align-x)
*/
template<typename T>
constexpr inline T p2nphase(T x, T align) {
return -x & (align - 1);
}
/*
* return x rounded up to an align boundary
* eg, p2roundup(0x1234, 0x100) == 0x1300 (0x13*align)
* eg, p2roundup(0x5600, 0x100) == 0x5600 (0x56*align)
*/
template<typename T>
constexpr inline T p2roundup(T x, T align) {
return -(-x & -align);
}
// count bits (set + any 0's that follow)
template<std::integral T>
unsigned cbits(T v) {
return (sizeof(v) * CHAR_BIT) - std::countl_zero(std::make_unsigned_t<T>(v));
}
#endif
| 2,485 | 25.446809 | 90 | h |
null | ceph-main/src/include/interval_set.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_INTERVAL_SET_H
#define CEPH_INTERVAL_SET_H
#include <iterator>
#include <map>
#include <ostream>
#include "encoding.h"
/*
* *** NOTE ***
*
* This class is written to work with a variety of map-like containers,
* *include* ones that invalidate iterators when they are modified (e.g.,
* flat_map and btree_map).
*/
template<typename T, template<typename, typename, typename ...> class C = std::map>
class interval_set {
public:
using Map = C<T, T>;
using value_type = typename Map::value_type;
using offset_type = T;
using length_type = T;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = typename Map::size_type;
class const_iterator;
class iterator
{
public:
using difference_type = ssize_t;
using value_type = typename Map::value_type;
using pointer = typename Map::value_type*;
using reference = typename Map::value_type&;
using iterator_category = std::forward_iterator_tag;
explicit iterator(typename Map::iterator iter)
: _iter(iter)
{ }
// For the copy constructor and assignment operator, the compiler-generated functions, which
// perform simple bitwise copying, should be fine.
bool operator==(const iterator& rhs) const {
return (_iter == rhs._iter);
}
bool operator!=(const iterator& rhs) const {
return (_iter != rhs._iter);
}
// Dereference this iterator to get a pair.
reference operator*() const {
return *_iter;
}
// Return the interval start.
offset_type get_start() const {
return _iter->first;
}
// Return the interval length.
length_type get_len() const {
return _iter->second;
}
offset_type get_end() const {
return _iter->first + _iter->second;
}
// Set the interval length.
void set_len(const length_type& len) {
_iter->second = len;
}
// Preincrement
iterator& operator++()
{
++_iter;
return *this;
}
// Postincrement
iterator operator++(int)
{
iterator prev(_iter);
++_iter;
return prev;
}
// Predecrement
iterator& operator--()
{
--_iter;
return *this;
}
// Postdecrement
iterator operator--(int)
{
iterator prev(_iter);
--_iter;
return prev;
}
friend class interval_set::const_iterator;
protected:
typename Map::iterator _iter;
friend class interval_set;
};
class const_iterator
{
public:
using difference_type = ssize_t;
using value_type = const typename Map::value_type;
using pointer = const typename Map::value_type*;
using reference = const typename Map::value_type&;
using iterator_category = std::forward_iterator_tag;
explicit const_iterator(typename Map::const_iterator iter)
: _iter(iter)
{ }
const_iterator(const iterator &i)
: _iter(i._iter)
{ }
// For the copy constructor and assignment operator, the compiler-generated functions, which
// perform simple bitwise copying, should be fine.
bool operator==(const const_iterator& rhs) const {
return (_iter == rhs._iter);
}
bool operator!=(const const_iterator& rhs) const {
return (_iter != rhs._iter);
}
// Dereference this iterator to get a pair.
reference operator*() const {
return *_iter;
}
// Return the interval start.
offset_type get_start() const {
return _iter->first;
}
offset_type get_end() const {
return _iter->first + _iter->second;
}
// Return the interval length.
length_type get_len() const {
return _iter->second;
}
// Preincrement
const_iterator& operator++()
{
++_iter;
return *this;
}
// Postincrement
const_iterator operator++(int)
{
const_iterator prev(_iter);
++_iter;
return prev;
}
// Predecrement
iterator& operator--()
{
--_iter;
return *this;
}
// Postdecrement
iterator operator--(int)
{
iterator prev(_iter);
--_iter;
return prev;
}
protected:
typename Map::const_iterator _iter;
};
interval_set() = default;
interval_set(Map&& other) {
m.swap(other);
for (const auto& p : m) {
_size += p.second;
}
}
size_type num_intervals() const
{
return m.size();
}
iterator begin() {
return iterator(m.begin());
}
iterator lower_bound(T start) {
return iterator(find_inc_m(start));
}
iterator end() {
return iterator(m.end());
}
const_iterator begin() const {
return const_iterator(m.begin());
}
const_iterator lower_bound(T start) const {
return const_iterator(find_inc(start));
}
const_iterator end() const {
return const_iterator(m.end());
}
// helpers
private:
auto find_inc(T start) const {
auto p = m.lower_bound(start); // p->first >= start
if (p != m.begin() &&
(p == m.end() || p->first > start)) {
--p; // might overlap?
if (p->first + p->second <= start)
++p; // it doesn't.
}
return p;
}
auto find_inc_m(T start) {
auto p = m.lower_bound(start);
if (p != m.begin() &&
(p == m.end() || p->first > start)) {
--p; // might overlap?
if (p->first + p->second <= start)
++p; // it doesn't.
}
return p;
}
auto find_adj(T start) const {
auto p = m.lower_bound(start);
if (p != m.begin() &&
(p == m.end() || p->first > start)) {
--p; // might touch?
if (p->first + p->second < start)
++p; // it doesn't.
}
return p;
}
auto find_adj_m(T start) {
auto p = m.lower_bound(start);
if (p != m.begin() &&
(p == m.end() || p->first > start)) {
--p; // might touch?
if (p->first + p->second < start)
++p; // it doesn't.
}
return p;
}
void intersection_size_asym(const interval_set &s, const interval_set &l) {
auto ps = s.m.begin();
ceph_assert(ps != s.m.end());
auto offset = ps->first;
bool first = true;
auto mi = m.begin();
while (1) {
if (first)
first = false;
auto pl = l.find_inc(offset);
if (pl == l.m.end())
break;
while (ps != s.m.end() && ps->first + ps->second <= pl->first)
++ps;
if (ps == s.m.end())
break;
offset = pl->first + pl->second;
if (offset <= ps->first) {
offset = ps->first;
continue;
}
if (*ps == *pl) {
do {
mi = m.insert(mi, *ps);
_size += ps->second;
++ps;
++pl;
} while (ps != s.m.end() && pl != l.m.end() && *ps == *pl);
if (ps == s.m.end())
break;
offset = ps->first;
continue;
}
auto start = std::max<T>(ps->first, pl->first);
auto en = std::min<T>(ps->first + ps->second, offset);
ceph_assert(en > start);
mi = m.emplace_hint(mi, start, en - start);
_size += mi->second;
if (ps->first + ps->second <= offset) {
++ps;
if (ps == s.m.end())
break;
offset = ps->first;
}
}
}
bool subset_size_sym(const interval_set &b) const {
auto pa = m.begin(), pb = b.m.begin();
const auto a_end = m.end(), b_end = b.m.end();
while (pa != a_end && pb != b_end) {
while (pb->first + pb->second <= pa->first) {
++pb;
if (pb == b_end)
return false;
}
if (*pa == *pb) {
do {
++pa;
++pb;
} while (pa != a_end && pb != b_end && *pa == *pb);
continue;
}
// interval begins before other
if (pa->first < pb->first)
return false;
// interval is longer than other
if (pa->first + pa->second > pb->first + pb->second)
return false;
++pa;
}
return pa == a_end;
}
public:
bool operator==(const interval_set& other) const {
return _size == other._size && m == other.m;
}
uint64_t size() const {
return _size;
}
void bound_encode(size_t& p) const {
denc_traits<Map>::bound_encode(m, p);
}
void encode(ceph::buffer::list::contiguous_appender& p) const {
denc(m, p);
}
void decode(ceph::buffer::ptr::const_iterator& p) {
denc(m, p);
_size = 0;
for (const auto& p : m) {
_size += p.second;
}
}
void decode(ceph::buffer::list::iterator& p) {
denc(m, p);
_size = 0;
for (const auto& p : m) {
_size += p.second;
}
}
void encode_nohead(ceph::buffer::list::contiguous_appender& p) const {
denc_traits<Map>::encode_nohead(m, p);
}
void decode_nohead(int n, ceph::buffer::ptr::const_iterator& p) {
denc_traits<Map>::decode_nohead(n, m, p);
_size = 0;
for (const auto& p : m) {
_size += p.second;
}
}
void clear() {
m.clear();
_size = 0;
}
bool contains(T i, T *pstart=0, T *plen=0) const {
auto p = find_inc(i);
if (p == m.end()) return false;
if (p->first > i) return false;
if (p->first+p->second <= i) return false;
ceph_assert(p->first <= i && p->first+p->second > i);
if (pstart)
*pstart = p->first;
if (plen)
*plen = p->second;
return true;
}
bool contains(T start, T len) const {
auto p = find_inc(start);
if (p == m.end()) return false;
if (p->first > start) return false;
if (p->first+p->second <= start) return false;
ceph_assert(p->first <= start && p->first+p->second > start);
if (p->first+p->second < start+len) return false;
return true;
}
bool intersects(T start, T len) const {
interval_set a;
a.insert(start, len);
interval_set i;
i.intersection_of( *this, a );
if (i.empty()) return false;
return true;
}
// outer range of set
bool empty() const {
return m.empty();
}
offset_type range_start() const {
ceph_assert(!empty());
auto p = m.begin();
return p->first;
}
offset_type range_end() const {
ceph_assert(!empty());
auto p = m.rbegin();
return p->first + p->second;
}
// interval start after p (where p not in set)
bool starts_after(T i) const {
ceph_assert(!contains(i));
auto p = find_inc(i);
if (p == m.end()) return false;
return true;
}
offset_type start_after(T i) const {
ceph_assert(!contains(i));
auto p = find_inc(i);
return p->first;
}
// interval end that contains start
offset_type end_after(T start) const {
ceph_assert(contains(start));
auto p = find_inc(start);
return p->first+p->second;
}
void insert(T val) {
insert(val, 1);
}
void insert(T start, T len, T *pstart=0, T *plen=0) {
//cout << "insert " << start << "~" << len << endl;
ceph_assert(len > 0);
_size += len;
auto p = find_adj_m(start);
if (p == m.end()) {
m[start] = len; // new interval
if (pstart)
*pstart = start;
if (plen)
*plen = len;
} else {
if (p->first < start) {
if (p->first + p->second != start) {
//cout << "p is " << p->first << "~" << p->second << ", start is " << start << ", len is " << len << endl;
ceph_abort();
}
p->second += len; // append to end
auto n = p;
++n;
if (pstart)
*pstart = p->first;
if (n != m.end() &&
start+len == n->first) { // combine with next, too!
p->second += n->second;
if (plen)
*plen = p->second;
m.erase(n);
} else {
if (plen)
*plen = p->second;
}
} else {
if (start+len == p->first) {
if (pstart)
*pstart = start;
if (plen)
*plen = len + p->second;
T psecond = p->second;
m.erase(p);
m[start] = len + psecond; // append to front
} else {
ceph_assert(p->first > start+len);
if (pstart)
*pstart = start;
if (plen)
*plen = len;
m[start] = len; // new interval
}
}
}
}
void swap(interval_set& other) {
m.swap(other.m);
std::swap(_size, other._size);
}
void erase(const iterator &i) {
_size -= i.get_len();
m.erase(i._iter);
}
void erase(T val) {
erase(val, 1);
}
void erase(T start, T len,
std::function<bool(T, T)> claim = {}) {
auto p = find_inc_m(start);
_size -= len;
ceph_assert(p != m.end());
ceph_assert(p->first <= start);
T before = start - p->first;
ceph_assert(p->second >= before+len);
T after = p->second - before - len;
if (before) {
if (claim && claim(p->first, before)) {
_size -= before;
m.erase(p);
} else {
p->second = before; // shorten bit before
}
} else {
m.erase(p);
}
if (after) {
if (claim && claim(start + len, after)) {
_size -= after;
} else {
m[start + len] = after;
}
}
}
void subtract(const interval_set &a) {
for (const auto& [start, len] : a.m) {
erase(start, len);
}
}
void insert(const interval_set &a) {
for (const auto& [start, len] : a.m) {
insert(start, len);
}
}
void intersection_of(const interval_set &a, const interval_set &b) {
ceph_assert(&a != this);
ceph_assert(&b != this);
clear();
const interval_set *s, *l;
if (a.size() < b.size()) {
s = &a;
l = &b;
} else {
s = &b;
l = &a;
}
if (!s->size())
return;
/*
* Use the lower_bound algorithm for larger size ratios
* where it performs better, but not for smaller size
* ratios where sequential search performs better.
*/
if (l->size() / s->size() >= 10) {
intersection_size_asym(*s, *l);
return;
}
auto pa = a.m.begin();
auto pb = b.m.begin();
auto mi = m.begin();
while (pa != a.m.end() && pb != b.m.end()) {
// passing?
if (pa->first + pa->second <= pb->first)
{ pa++; continue; }
if (pb->first + pb->second <= pa->first)
{ pb++; continue; }
if (*pa == *pb) {
do {
mi = m.insert(mi, *pa);
_size += pa->second;
++pa;
++pb;
} while (pa != a.m.end() && pb != b.m.end() && *pa == *pb);
continue;
}
T start = std::max(pa->first, pb->first);
T en = std::min(pa->first+pa->second, pb->first+pb->second);
ceph_assert(en > start);
mi = m.emplace_hint(mi, start, en - start);
_size += mi->second;
if (pa->first+pa->second > pb->first+pb->second)
pb++;
else
pa++;
}
}
void intersection_of(const interval_set& b) {
interval_set a;
swap(a);
intersection_of(a, b);
}
void union_of(const interval_set &a, const interval_set &b) {
ceph_assert(&a != this);
ceph_assert(&b != this);
clear();
//cout << "union_of" << endl;
// a
m = a.m;
_size = a._size;
// - (a*b)
interval_set ab;
ab.intersection_of(a, b);
subtract(ab);
// + b
insert(b);
return;
}
void union_of(const interval_set &b) {
interval_set a;
swap(a);
union_of(a, b);
}
void union_insert(T off, T len) {
interval_set a;
a.insert(off, len);
union_of(a);
}
bool subset_of(const interval_set &big) const {
if (!size())
return true;
if (size() > big.size())
return false;
if (range_end() > big.range_end())
return false;
/*
* Use the lower_bound algorithm for larger size ratios
* where it performs better, but not for smaller size
* ratios where sequential search performs better.
*/
if (big.size() / size() < 10)
return subset_size_sym(big);
for (const auto& [start, len] : m) {
if (!big.contains(start, len)) return false;
}
return true;
}
/*
* build a subset of @other, starting at or after @start, and including
* @len worth of values, skipping holes. e.g.,
* span_of([5~10,20~5], 8, 5) -> [8~2,20~3]
*/
void span_of(const interval_set &other, T start, T len) {
clear();
auto p = other.find_inc(start);
if (p == other.m.end())
return;
if (p->first < start) {
if (p->first + p->second < start)
return;
if (p->first + p->second < start + len) {
T howmuch = p->second - (start - p->first);
insert(start, howmuch);
len -= howmuch;
p++;
} else {
insert(start, len);
return;
}
}
while (p != other.m.end() && len > 0) {
if (p->second < len) {
insert(p->first, p->second);
len -= p->second;
p++;
} else {
insert(p->first, len);
return;
}
}
}
/*
* Move contents of m into another Map. Use that instead of
* encoding interval_set into bufferlist then decoding it back into Map.
*/
Map detach() && {
return std::move(m);
}
private:
// data
uint64_t _size = 0;
Map m; // map start -> len
};
// declare traits explicitly because (1) it's templatized, and (2) we
// want to include _nohead variants.
template<typename T, template<typename, typename, typename ...> class C>
struct denc_traits<interval_set<T, C>> {
private:
using container_t = interval_set<T, C>;
public:
static constexpr bool supported = true;
static constexpr bool bounded = false;
static constexpr bool featured = false;
static constexpr bool need_contiguous = denc_traits<T, C<T,T>>::need_contiguous;
static void bound_encode(const container_t& v, size_t& p) {
v.bound_encode(p);
}
static void encode(const container_t& v,
ceph::buffer::list::contiguous_appender& p) {
v.encode(p);
}
static void decode(container_t& v, ceph::buffer::ptr::const_iterator& p) {
v.decode(p);
}
template<typename U=T>
static typename std::enable_if<sizeof(U) && !need_contiguous>::type
decode(container_t& v, ceph::buffer::list::iterator& p) {
v.decode(p);
}
static void encode_nohead(const container_t& v,
ceph::buffer::list::contiguous_appender& p) {
v.encode_nohead(p);
}
static void decode_nohead(size_t n, container_t& v,
ceph::buffer::ptr::const_iterator& p) {
v.decode_nohead(n, p);
}
};
template<typename T, template<typename, typename, typename ...> class C>
inline std::ostream& operator<<(std::ostream& out, const interval_set<T,C> &s) {
out << "[";
bool first = true;
for (const auto& [start, len] : s) {
if (!first) out << ",";
out << start << "~" << len;
first = false;
}
out << "]";
return out;
}
#endif
| 19,553 | 22.701818 | 116 | h |
null | ceph-main/src/include/ipaddr.h | #ifndef CEPH_IPADDR_H
#define CEPH_IPADDR_H
class entity_addr_t;
/*
* Check if an IP address that is in the wanted subnet.
*/
bool matches_ipv4_in_subnet(const struct ifaddrs& addrs,
const struct sockaddr_in* net,
unsigned int prefix_len);
bool matches_ipv6_in_subnet(const struct ifaddrs& addrs,
const struct sockaddr_in6* net,
unsigned int prefix_len);
/*
* Validate and parse IPv4 or IPv6 network
*
* Given a network (e.g. "192.168.0.0/24") and pointers to a sockaddr_storage
* struct and an unsigned int:
*
* if the network string is valid, return true and populate sockaddr_storage
* and prefix_len;
*
* if the network string is invalid, return false.
*/
bool parse_network(const char *s,
struct sockaddr_storage *network,
unsigned int *prefix_len);
bool parse_network(const char *s,
entity_addr_t *network,
unsigned int *prefix_len);
void netmask_ipv6(const struct in6_addr *addr,
unsigned int prefix_len,
struct in6_addr *out);
void netmask_ipv4(const struct in_addr *addr,
unsigned int prefix_len,
struct in_addr *out);
bool network_contains(
const struct entity_addr_t& network,
unsigned int prefix_len,
const struct entity_addr_t& addr);
#endif
| 1,325 | 26.625 | 77 | h |
null | ceph-main/src/include/krbd.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Inktank Storage, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_KRBD_H
#define CEPH_KRBD_H
#include "rados/librados.h"
/*
* Don't wait for udev add uevents in krbd_map() and udev remove
* uevents in krbd_unmap*(). Instead, make do with the respective
* kernel uevents and return as soon as they are received.
*
* systemd-udevd sends out udev uevents after it finishes processing
* the respective kernel uevents, which mostly boils down to executing
* all matching udev rules. With this flag set, on return from
* krbd_map() systemd-udevd may still be poking at the device: it
* may still be open with tools such as blkid and various ioctls to
* be run against it, none of the persistent symlinks to the device
* node may be there, etc. udev used to be responsible for creating
* the device node as well, but that has been handled by devtmpfs in
* the kernel for many years now, so the device node (as returned
* through @pdevnode) is guaranteed to be there.
*
* If set, krbd_map() and krbd_unmap*() can be invoked from any
* network namespace that is owned by the initial user namespace
* (which is a formality because things like loading kernel modules
* and creating block devices are not namespaced and require global
* privileges, i.e. capabilities in the initial user namespace).
* Otherwise, krbd_map() and krbd_unmap*() must be invoked from
* the initial network namespace.
*
* If set, krbd_unmap*() doesn't attempt to settle the udev queue
* before retrying unmap for the last time. Some EBUSY errors due
* to systemd-udevd poking at the device at the time krbd_unmap*()
* is invoked that are otherwise covered by the retry logic may be
* returned.
*/
#define KRBD_CTX_F_NOUDEV (1U << 0)
#ifdef __cplusplus
extern "C" {
#endif
struct krbd_ctx;
int krbd_create_from_context(rados_config_t cct, uint32_t flags,
struct krbd_ctx **pctx);
void krbd_destroy(struct krbd_ctx *ctx);
int krbd_map(struct krbd_ctx *ctx,
const char *pool_name,
const char *nspace_name,
const char *image_name,
const char *snap_name,
const char *options,
char **pdevnode);
int krbd_is_mapped(struct krbd_ctx *ctx,
const char *pool_name,
const char *nspace_name,
const char *image_name,
const char *snap_name,
char **pdevnode);
int krbd_unmap(struct krbd_ctx *ctx, const char *devnode,
const char *options);
int krbd_unmap_by_spec(struct krbd_ctx *ctx,
const char *pool_name,
const char *nspace_name,
const char *image_name,
const char *snap_name,
const char *options);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
namespace ceph {
class Formatter;
}
int krbd_showmapped(struct krbd_ctx *ctx, ceph::Formatter *f);
#endif /* __cplusplus */
#endif /* CEPH_KRBD_H */
| 3,294 | 32.622449 | 70 | h |
null | ceph-main/src/include/libcephsqlite.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2021 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License version 2.1, as published by
* the Free Software Foundation. See file COPYING.
*
*/
#ifndef LIBCEPHSQLITE_H
#define LIBCEPHSQLITE_H
/* This loadable extension does not generally require using this header. It is
* here to allow controlling which version of the library is linked in. See
* also sqlite3_cephsqlite_init below. Additionally, you may specify which
* CephContext to use rather than the library instantiating its own and using
* whatever the default credential is.
*/
#include <sqlite3.h>
#ifdef _WIN32
# define LIBCEPHSQLITE_API __declspec(dllexport)
#else
# define LIBCEPHSQLITE_API [[gnu::visibility("default")]]
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* This is the SQLite entry point when loaded as a dynamic library. You also
* need to ensure SQLite calls this method when using libcephsqlite as a static
* library or a dynamic library linked at compile time. For the latter case,
* you can do this by:
*
* sqlite3_auto_extension((void (*)())sqlite3_cephsqlite_init);
* sqlite3* db = nullptr;
* int rc = sqlite3_open_v2(":memory:", &db, SQLITE_OPEN_READWRITE, nullptr);
* if (rc == SQLITE_DONE) {
* sqlite3_close(db);
* } else {
* // failure
* }
*
* The throwaway database created (name == "") is a memory database opened so
* that SQLite runs the libcephsqlite initialization routine to register the
* VFS. AFter that's done, the VFS is available for a future database open with
* the VFS set to "ceph":
*
* sqlite3_open_v2("foo:bar/baz.db", &db, SQLITE_OPEN_READWRITE, "ceph");
*
* You MUST do this before calling any other libcephsqlite routine so that
* sqlite3 can pass its API routines to the libcephsqlite extension.
*/
LIBCEPHSQLITE_API int sqlite3_cephsqlite_init(sqlite3* db, char** err, const sqlite3_api_routines* api);
/* If you prefer to have libcephsqlite use a CephContext managed by your
* application, use this routine to set that. libcephsqlite can only have one
* context globally.
*/
LIBCEPHSQLITE_API int cephsqlite_setcct(class CephContext* cct, char** ident);
#ifdef __cplusplus
}
#endif
#endif
| 2,424 | 31.77027 | 104 | h |
null | ceph-main/src/include/linux_fiemap.h | /*
* FS_IOC_FIEMAP ioctl infrastructure.
*
* Some portions copyright (C) 2007 Cluster File Systems, Inc
*
* Authors: Mark Fasheh <[email protected]>
* Kalpak Shah <[email protected]>
* Andreas Dilger <[email protected]>
*/
#ifndef _LINUX_FIEMAP_H
#define _LINUX_FIEMAP_H
#if defined(__linux__)
#include <linux/types.h>
#elif defined(__FreeBSD_)
#include <sys/types.h>
#endif
#include "include/int_types.h"
struct fiemap_extent {
__u64 fe_logical; /* logical offset in bytes for the start of
* the extent from the beginning of the file */
__u64 fe_physical; /* physical offset in bytes for the start
* of the extent from the beginning of the disk */
__u64 fe_length; /* length in bytes for this extent */
__u64 fe_reserved64[2];
__u32 fe_flags; /* FIEMAP_EXTENT_* flags for this extent */
__u32 fe_reserved[3];
};
struct fiemap {
__u64 fm_start; /* logical offset (inclusive) at
* which to start mapping (in) */
__u64 fm_length; /* logical length of mapping which
* userspace wants (in) */
__u32 fm_flags; /* FIEMAP_FLAG_* flags for request (in/out) */
__u32 fm_mapped_extents;/* number of extents that were mapped (out) */
__u32 fm_extent_count; /* size of fm_extents array (in) */
__u32 fm_reserved;
struct fiemap_extent fm_extents[0]; /* array of mapped extents (out) */
};
#define FIEMAP_MAX_OFFSET (~0ULL)
#define FIEMAP_FLAG_SYNC 0x00000001 /* sync file data before map */
#define FIEMAP_FLAG_XATTR 0x00000002 /* map extended attribute tree */
#define FIEMAP_FLAGS_COMPAT (FIEMAP_FLAG_SYNC | FIEMAP_FLAG_XATTR)
#define FIEMAP_EXTENT_LAST 0x00000001 /* Last extent in file. */
#define FIEMAP_EXTENT_UNKNOWN 0x00000002 /* Data location unknown. */
#define FIEMAP_EXTENT_DELALLOC 0x00000004 /* Location still pending.
* Sets EXTENT_UNKNOWN. */
#define FIEMAP_EXTENT_ENCODED 0x00000008 /* Data can not be read
* while fs is unmounted */
#define FIEMAP_EXTENT_DATA_ENCRYPTED 0x00000080 /* Data is encrypted by fs.
* Sets EXTENT_NO_BYPASS. */
#define FIEMAP_EXTENT_NOT_ALIGNED 0x00000100 /* Extent offsets may not be
* block aligned. */
#define FIEMAP_EXTENT_DATA_INLINE 0x00000200 /* Data mixed with metadata.
* Sets EXTENT_NOT_ALIGNED.*/
#define FIEMAP_EXTENT_DATA_TAIL 0x00000400 /* Multiple files in block.
* Sets EXTENT_NOT_ALIGNED.*/
#define FIEMAP_EXTENT_UNWRITTEN 0x00000800 /* Space allocated, but
* no data (i.e. zero). */
#define FIEMAP_EXTENT_MERGED 0x00001000 /* File does not natively
* support extents. Result
* merged for efficiency. */
#define FIEMAP_EXTENT_SHARED 0x00002000 /* Space shared with other
* files. */
#endif /* _LINUX_FIEMAP_H */
| 2,748 | 36.148649 | 75 | h |
null | ceph-main/src/include/mempool.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 Allen Samuels <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _CEPH_INCLUDE_MEMPOOL_H
#define _CEPH_INCLUDE_MEMPOOL_H
#include <cstddef>
#include <map>
#include <unordered_map>
#include <set>
#include <vector>
#include <list>
#include <mutex>
#include <typeinfo>
#include <boost/container/flat_set.hpp>
#include <boost/container/flat_map.hpp>
#include "common/Formatter.h"
#include "common/ceph_atomic.h"
#include "include/ceph_assert.h"
#include "include/compact_map.h"
#include "include/compact_set.h"
#include "include/compat.h"
/*
Memory Pools
============
A memory pool is a method for accounting the consumption of memory of
a set of containers.
Memory pools are statically declared (see pool_index_t).
Each memory pool tracks the number of bytes and items it contains.
Allocators can be declared and associated with a type so that they are
tracked independently of the pool total. This additional accounting
is optional and only incurs an overhead if the debugging is enabled at
runtime. This allows developers to see what types are consuming the
pool resources.
Declaring
---------
Using memory pools is very easy.
To create a new memory pool, simply add a new name into the list of
memory pools that's defined in "DEFINE_MEMORY_POOLS_HELPER". That's
it. :)
For each memory pool that's created a C++ namespace is also
automatically created (name is same as in DEFINE_MEMORY_POOLS_HELPER).
That namespace contains a set of common STL containers that are predefined
with the appropriate allocators.
Thus for mempool "osd" we have automatically available to us:
mempool::osd::map
mempool::osd::multimap
mempool::osd::set
mempool::osd::multiset
mempool::osd::list
mempool::osd::vector
mempool::osd::unordered_map
Putting objects in a mempool
----------------------------
In order to use a memory pool with a particular type, a few additional
declarations are needed.
For a class:
struct Foo {
MEMPOOL_CLASS_HELPERS();
...
};
Then, in an appropriate .cc file,
MEMPOOL_DEFINE_OBJECT_FACTORY(Foo, foo, osd);
The second argument can generally be identical to the first, except
when the type contains a nested scope. For example, for
BlueStore::Onode, we need to do
MEMPOOL_DEFINE_OBJECT_FACTORY(BlueStore::Onode, bluestore_onode,
bluestore_meta);
(This is just because we need to name some static variables and we
can't use :: in a variable name.)
XXX Note: the new operator hard-codes the allocation size to the size of the
object given in MEMPOOL_DEFINE_OBJECT_FACTORY. For this reason, you cannot
incorporate mempools into a base class without also defining a helper/factory
for the child class as well (as the base class is usually smaller than the
child class).
In order to use the STL containers, simply use the namespaced variant
of the container type. For example,
mempool::osd::map<int> myvec;
Introspection
-------------
The simplest way to interrogate the process is with
Formater *f = ...
mempool::dump(f);
This will dump information about *all* memory pools. When debug mode
is enabled, the runtime complexity of dump is O(num_shards *
num_types). When debug name is disabled it is O(num_shards).
You can also interrogate a specific pool programmatically with
size_t bytes = mempool::unittest_2::allocated_bytes();
size_t items = mempool::unittest_2::allocated_items();
The runtime complexity is O(num_shards).
Note that you cannot easily query per-type, primarily because debug
mode is optional and you should not rely on that information being
available.
*/
namespace mempool {
// --------------------------------------------------------------
// define memory pools
#define DEFINE_MEMORY_POOLS_HELPER(f) \
f(bloom_filter) \
f(bluestore_alloc) \
f(bluestore_cache_data) \
f(bluestore_cache_onode) \
f(bluestore_cache_meta) \
f(bluestore_cache_other) \
f(bluestore_cache_buffer) \
f(bluestore_extent) \
f(bluestore_blob) \
f(bluestore_shared_blob) \
f(bluestore_inline_bl) \
f(bluestore_fsck) \
f(bluestore_txc) \
f(bluestore_writing_deferred) \
f(bluestore_writing) \
f(bluefs) \
f(bluefs_file_reader) \
f(bluefs_file_writer) \
f(buffer_anon) \
f(buffer_meta) \
f(osd) \
f(osd_mapbl) \
f(osd_pglog) \
f(osdmap) \
f(osdmap_mapping) \
f(pgmap) \
f(mds_co) \
f(unittest_1) \
f(unittest_2)
// give them integer ids
#define P(x) mempool_##x,
enum pool_index_t {
DEFINE_MEMORY_POOLS_HELPER(P)
num_pools // Must be last.
};
#undef P
extern bool debug_mode;
extern void set_debug_mode(bool d);
// --------------------------------------------------------------
class pool_t;
// we shard pool stats across many shard_t's to reduce the amount
// of cacheline ping pong.
enum {
num_shard_bits = 5
};
enum {
num_shards = 1 << num_shard_bits
};
//
// Align shard to a cacheline.
//
// It would be possible to retrieve the value at runtime (for instance
// with getconf LEVEL1_DCACHE_LINESIZE or grep -m1 cache_alignment
// /proc/cpuinfo). It is easier to hard code the largest cache
// linesize for all known processors (128 bytes). If the actual cache
// linesize is smaller on a given processor, it will just waste a few
// bytes.
//
struct shard_t {
ceph::atomic<size_t> bytes = {0};
ceph::atomic<size_t> items = {0};
char __padding[128 - sizeof(ceph::atomic<size_t>)*2];
} __attribute__ ((aligned (128)));
static_assert(sizeof(shard_t) == 128, "shard_t should be cacheline-sized");
struct stats_t {
ssize_t items = 0;
ssize_t bytes = 0;
void dump(ceph::Formatter *f) const {
f->dump_int("items", items);
f->dump_int("bytes", bytes);
}
stats_t& operator+=(const stats_t& o) {
items += o.items;
bytes += o.bytes;
return *this;
}
};
pool_t& get_pool(pool_index_t ix);
const char *get_pool_name(pool_index_t ix);
struct type_t {
const char *type_name;
size_t item_size;
ceph::atomic<ssize_t> items = {0}; // signed
};
struct type_info_hash {
std::size_t operator()(const std::type_info& k) const {
return k.hash_code();
}
};
class pool_t {
shard_t shard[num_shards];
mutable std::mutex lock; // only used for types list
std::unordered_map<const char *, type_t> type_map;
public:
//
// How much this pool consumes. O(<num_shards>)
//
size_t allocated_bytes() const;
size_t allocated_items() const;
void adjust_count(ssize_t items, ssize_t bytes);
static size_t pick_a_shard_int() {
// Dirt cheap, see:
// https://fossies.org/dox/glibc-2.32/pthread__self_8c_source.html
size_t me = (size_t)pthread_self();
size_t i = (me >> CEPH_PAGE_SHIFT) & ((1 << num_shard_bits) - 1);
return i;
}
shard_t* pick_a_shard() {
size_t i = pick_a_shard_int();
return &shard[i];
}
type_t *get_type(const std::type_info& ti, size_t size) {
std::lock_guard<std::mutex> l(lock);
auto p = type_map.find(ti.name());
if (p != type_map.end()) {
return &p->second;
}
type_t &t = type_map[ti.name()];
t.type_name = ti.name();
t.item_size = size;
return &t;
}
// get pool stats. by_type is not populated if !debug
void get_stats(stats_t *total,
std::map<std::string, stats_t> *by_type) const;
void dump(ceph::Formatter *f, stats_t *ptotal=0) const;
};
void dump(ceph::Formatter *f);
// STL allocator for use with containers. All actual state
// is stored in the static pool_allocator_base_t, which saves us from
// passing the allocator to container constructors.
template<pool_index_t pool_ix, typename T>
class pool_allocator {
pool_t *pool;
type_t *type = nullptr;
public:
typedef pool_allocator<pool_ix, T> allocator_type;
typedef T value_type;
typedef value_type *pointer;
typedef const value_type * const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
template<typename U> struct rebind {
typedef pool_allocator<pool_ix,U> other;
};
void init(bool force_register) {
pool = &get_pool(pool_ix);
if (debug_mode || force_register) {
type = pool->get_type(typeid(T), sizeof(T));
}
}
pool_allocator(bool force_register=false) {
init(force_register);
}
template<typename U>
pool_allocator(const pool_allocator<pool_ix,U>&) {
init(false);
}
T* allocate(size_t n, void *p = nullptr) {
size_t total = sizeof(T) * n;
shard_t *shard = pool->pick_a_shard();
shard->bytes += total;
shard->items += n;
if (type) {
type->items += n;
}
T* r = reinterpret_cast<T*>(new char[total]);
return r;
}
void deallocate(T* p, size_t n) {
size_t total = sizeof(T) * n;
shard_t *shard = pool->pick_a_shard();
shard->bytes -= total;
shard->items -= n;
if (type) {
type->items -= n;
}
delete[] reinterpret_cast<char*>(p);
}
T* allocate_aligned(size_t n, size_t align, void *p = nullptr) {
size_t total = sizeof(T) * n;
shard_t *shard = pool->pick_a_shard();
shard->bytes += total;
shard->items += n;
if (type) {
type->items += n;
}
char *ptr;
int rc = ::posix_memalign((void**)(void*)&ptr, align, total);
if (rc)
throw std::bad_alloc();
T* r = reinterpret_cast<T*>(ptr);
return r;
}
void deallocate_aligned(T* p, size_t n) {
size_t total = sizeof(T) * n;
shard_t *shard = pool->pick_a_shard();
shard->bytes -= total;
shard->items -= n;
if (type) {
type->items -= n;
}
aligned_free(p);
}
void destroy(T* p) {
p->~T();
}
template<class U>
void destroy(U *p) {
p->~U();
}
void construct(T* p, const T& val) {
::new ((void *)p) T(val);
}
template<class U, class... Args> void construct(U* p,Args&&... args) {
::new((void *)p) U(std::forward<Args>(args)...);
}
bool operator==(const pool_allocator&) const { return true; }
bool operator!=(const pool_allocator&) const { return false; }
};
// Namespace mempool
#define P(x) \
namespace x { \
static const mempool::pool_index_t id = mempool::mempool_##x; \
template<typename v> \
using pool_allocator = mempool::pool_allocator<id,v>; \
\
using string = std::basic_string<char,std::char_traits<char>, \
pool_allocator<char>>; \
\
template<typename k,typename v, typename cmp = std::less<k> > \
using map = std::map<k, v, cmp, \
pool_allocator<std::pair<const k,v>>>; \
\
template<typename k,typename v, typename cmp = std::less<k> > \
using compact_map = compact_map<k, v, cmp, \
pool_allocator<std::pair<const k,v>>>; \
\
template<typename k,typename v, typename cmp = std::less<k> > \
using compact_multimap = compact_multimap<k, v, cmp, \
pool_allocator<std::pair<const k,v>>>; \
\
template<typename k, typename cmp = std::less<k> > \
using compact_set = compact_set<k, cmp, pool_allocator<k>>; \
\
template<typename k,typename v, typename cmp = std::less<k> > \
using multimap = std::multimap<k,v,cmp, \
pool_allocator<std::pair<const k, \
v>>>; \
\
template<typename k, typename cmp = std::less<k> > \
using set = std::set<k,cmp,pool_allocator<k>>; \
\
template<typename k, typename cmp = std::less<k> > \
using flat_set = boost::container::flat_set<k,cmp,pool_allocator<k>>; \
\
template<typename k, typename v, typename cmp = std::less<k> > \
using flat_map = boost::container::flat_map<k,v,cmp, \
pool_allocator<std::pair<k,v>>>; \
\
template<typename v> \
using list = std::list<v,pool_allocator<v>>; \
\
template<typename v> \
using vector = std::vector<v,pool_allocator<v>>; \
\
template<typename k, typename v, \
typename h=std::hash<k>, \
typename eq = std::equal_to<k>> \
using unordered_map = \
std::unordered_map<k,v,h,eq,pool_allocator<std::pair<const k,v>>>;\
\
inline size_t allocated_bytes() { \
return mempool::get_pool(id).allocated_bytes(); \
} \
inline size_t allocated_items() { \
return mempool::get_pool(id).allocated_items(); \
} \
};
DEFINE_MEMORY_POOLS_HELPER(P)
#undef P
};
// the elements allocated by mempool is in the same memory space as the ones
// allocated by the default allocator. so compare them in an efficient way:
// libstdc++'s std::equal is specialized to use memcmp if T is integer or
// pointer. this is good enough for our usecase. use
// std::is_trivially_copyable<T> to expand the support to more types if
// nececssary.
template<typename T, mempool::pool_index_t pool_index>
bool operator==(const std::vector<T, std::allocator<T>>& lhs,
const std::vector<T, mempool::pool_allocator<pool_index, T>>& rhs)
{
return (lhs.size() == rhs.size() &&
std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
template<typename T, mempool::pool_index_t pool_index>
bool operator!=(const std::vector<T, std::allocator<T>>& lhs,
const std::vector<T, mempool::pool_allocator<pool_index, T>>& rhs)
{
return !(lhs == rhs);
}
template<typename T, mempool::pool_index_t pool_index>
bool operator==(const std::vector<T, mempool::pool_allocator<pool_index, T>>& lhs,
const std::vector<T, std::allocator<T>>& rhs)
{
return rhs == lhs;
}
template<typename T, mempool::pool_index_t pool_index>
bool operator!=(const std::vector<T, mempool::pool_allocator<pool_index, T>>& lhs,
const std::vector<T, std::allocator<T>>& rhs)
{
return !(lhs == rhs);
}
// Use this for any type that is contained by a container (unless it
// is a class you defined; see below).
#define MEMPOOL_DECLARE_FACTORY(obj, factoryname, pool) \
namespace mempool { \
namespace pool { \
extern pool_allocator<obj> alloc_##factoryname; \
} \
}
#define MEMPOOL_DEFINE_FACTORY(obj, factoryname, pool) \
namespace mempool { \
namespace pool { \
pool_allocator<obj> alloc_##factoryname = {true}; \
} \
}
// Use this for each class that belongs to a mempool. For example,
//
// class T {
// MEMPOOL_CLASS_HELPERS();
// ...
// };
//
#define MEMPOOL_CLASS_HELPERS() \
void *operator new(size_t size); \
void *operator new[](size_t size) noexcept { \
ceph_abort_msg("no array new"); \
return nullptr; } \
void operator delete(void *); \
void operator delete[](void *) { ceph_abort_msg("no array delete"); }
// Use this in some particular .cc file to match each class with a
// MEMPOOL_CLASS_HELPERS().
#define MEMPOOL_DEFINE_OBJECT_FACTORY(obj,factoryname,pool) \
MEMPOOL_DEFINE_FACTORY(obj, factoryname, pool) \
void *obj::operator new(size_t size) { \
return mempool::pool::alloc_##factoryname.allocate(1); \
} \
void obj::operator delete(void *p) { \
return mempool::pool::alloc_##factoryname.deallocate((obj*)p, 1); \
}
#endif
| 16,597 | 28.74552 | 82 | h |
null | ceph-main/src/include/msgr.h | #ifndef CEPH_MSGR_H
#define CEPH_MSGR_H
#ifndef __KERNEL__
#include <sys/socket.h> // for struct sockaddr_storage
#endif
#include "include/int_types.h"
/* See comment in ceph_fs.h. */
#ifndef __KERNEL__
#include "byteorder.h"
#define __le16 ceph_le16
#define __le32 ceph_le32
#define __le64 ceph_le64
#endif
/*
* Data types for message passing layer used by Ceph.
*/
#define CEPH_MON_PORT_LEGACY 6789 /* legacy default monitor port */
#define CEPH_MON_PORT_IANA 3300 /* IANA monitor port */
/*
* tcp connection banner. include a protocol version. and adjust
* whenever the wire protocol changes. try to keep this string length
* constant.
*/
#define CEPH_BANNER "ceph v027"
/*
* messenger V2 connection banner prefix.
* The full banner string should have the form: "ceph v2\n<le16>"
* the 2 bytes are the length of the remaining banner.
*/
#define CEPH_BANNER_V2_PREFIX "ceph v2\n"
/*
* messenger V2 features
*/
#define CEPH_MSGR2_INCARNATION_1 (0ull)
#define DEFINE_MSGR2_FEATURE(bit, incarnation, name) \
const static uint64_t CEPH_MSGR2_FEATURE_##name = (1ULL << bit); \
const static uint64_t CEPH_MSGR2_FEATUREMASK_##name = \
(1ULL << bit | CEPH_MSGR2_INCARNATION_##incarnation);
#define HAVE_MSGR2_FEATURE(x, name) \
(((x) & (CEPH_MSGR2_FEATUREMASK_##name)) == (CEPH_MSGR2_FEATUREMASK_##name))
DEFINE_MSGR2_FEATURE(0, 1, REVISION_1) // msgr2.1
DEFINE_MSGR2_FEATURE(1, 1, COMPRESSION) // on-wire compression
/*
* Features supported. Should be everything above.
*/
#define CEPH_MSGR2_SUPPORTED_FEATURES \
(CEPH_MSGR2_FEATURE_REVISION_1 | \
CEPH_MSGR2_FEATURE_COMPRESSION | \
0ULL)
#define CEPH_MSGR2_REQUIRED_FEATURES (0ULL)
/*
* Rollover-safe type and comparator for 32-bit sequence numbers.
* Comparator returns -1, 0, or 1.
*/
typedef __u32 ceph_seq_t;
static inline __s32 ceph_seq_cmp(__u32 a, __u32 b)
{
return (__s32)a - (__s32)b;
}
/*
* entity_name -- logical name for a process participating in the
* network, e.g. 'mds0' or 'osd3'.
*/
struct ceph_entity_name {
__u8 type; /* CEPH_ENTITY_TYPE_* */
__le64 num;
} __attribute__ ((packed));
#define CEPH_ENTITY_TYPE_MON 0x01
#define CEPH_ENTITY_TYPE_MDS 0x02
#define CEPH_ENTITY_TYPE_OSD 0x04
#define CEPH_ENTITY_TYPE_CLIENT 0x08
#define CEPH_ENTITY_TYPE_MGR 0x10
#define CEPH_ENTITY_TYPE_AUTH 0x20
#define CEPH_ENTITY_TYPE_ANY 0xFF
extern const char *ceph_entity_type_name(int type);
/*
* entity_addr -- network address
*/
struct ceph_entity_addr {
__le32 type;
__le32 nonce; /* unique id for process (e.g. pid) */
struct sockaddr_storage in_addr;
} __attribute__ ((packed));
struct ceph_entity_inst {
struct ceph_entity_name name;
struct ceph_entity_addr addr;
} __attribute__ ((packed));
/* used by message exchange protocol */
#define CEPH_MSGR_TAG_READY 1 /* server->client: ready for messages */
#define CEPH_MSGR_TAG_RESETSESSION 2 /* server->client: reset, try again */
#define CEPH_MSGR_TAG_WAIT 3 /* server->client: wait for racing
incoming connection */
#define CEPH_MSGR_TAG_RETRY_SESSION 4 /* server->client + cseq: try again
with higher cseq */
#define CEPH_MSGR_TAG_RETRY_GLOBAL 5 /* server->client + gseq: try again
with higher gseq */
#define CEPH_MSGR_TAG_CLOSE 6 /* closing pipe */
#define CEPH_MSGR_TAG_MSG 7 /* message */
#define CEPH_MSGR_TAG_ACK 8 /* message ack */
#define CEPH_MSGR_TAG_KEEPALIVE 9 /* just a keepalive byte! */
#define CEPH_MSGR_TAG_BADPROTOVER 10 /* bad protocol version */
#define CEPH_MSGR_TAG_BADAUTHORIZER 11 /* bad authorizer */
#define CEPH_MSGR_TAG_FEATURES 12 /* insufficient features */
#define CEPH_MSGR_TAG_SEQ 13 /* 64-bit int follows with seen seq number */
#define CEPH_MSGR_TAG_KEEPALIVE2 14
#define CEPH_MSGR_TAG_KEEPALIVE2_ACK 15 /* keepalive reply */
#define CEPH_MSGR_TAG_CHALLENGE_AUTHORIZER 16 /* ceph v2 doing server challenge */
/*
* connection negotiation
*/
struct ceph_msg_connect {
__le64 features; /* supported feature bits */
__le32 host_type; /* CEPH_ENTITY_TYPE_* */
__le32 global_seq; /* count connections initiated by this host */
__le32 connect_seq; /* count connections initiated in this session */
__le32 protocol_version;
__le32 authorizer_protocol;
__le32 authorizer_len;
__u8 flags; /* CEPH_MSG_CONNECT_* */
} __attribute__ ((packed));
struct ceph_msg_connect_reply {
__u8 tag;
__le64 features; /* feature bits for this session */
__le32 global_seq;
__le32 connect_seq;
__le32 protocol_version;
__le32 authorizer_len;
__u8 flags;
} __attribute__ ((packed));
#define CEPH_MSG_CONNECT_LOSSY 1 /* messages i send may be safely dropped */
/*
* message header
*/
struct ceph_msg_header_old {
__le64 seq; /* message seq# for this session */
__le64 tid; /* transaction id */
__le16 type; /* message type */
__le16 priority; /* priority. higher value == higher priority */
__le16 version; /* version of message encoding */
__le32 front_len; /* bytes in main payload */
__le32 middle_len;/* bytes in middle payload */
__le32 data_len; /* bytes of data payload */
__le16 data_off; /* sender: include full offset;
receiver: mask against ~PAGE_MASK */
struct ceph_entity_inst src, orig_src;
__le32 reserved;
__le32 crc; /* header crc32c */
} __attribute__ ((packed));
struct ceph_msg_header {
__le64 seq; /* message seq# for this session */
__le64 tid; /* transaction id */
__le16 type; /* message type */
__le16 priority; /* priority. higher value == higher priority */
__le16 version; /* version of message encoding */
__le32 front_len; /* bytes in main payload */
__le32 middle_len;/* bytes in middle payload */
__le32 data_len; /* bytes of data payload */
__le16 data_off; /* sender: include full offset;
receiver: mask against ~PAGE_MASK */
struct ceph_entity_name src;
/* oldest code we think can decode this. unknown if zero. */
__le16 compat_version;
__le16 reserved;
__le32 crc; /* header crc32c */
} __attribute__ ((packed));
struct ceph_msg_header2 {
__le64 seq; /* message seq# for this session */
__le64 tid; /* transaction id */
__le16 type; /* message type */
__le16 priority; /* priority. higher value == higher priority */
__le16 version; /* version of message encoding */
__le32 data_pre_padding_len;
__le16 data_off; /* sender: include full offset;
receiver: mask against ~PAGE_MASK */
__le64 ack_seq;
__u8 flags;
/* oldest code we think can decode this. unknown if zero. */
__le16 compat_version;
__le16 reserved;
} __attribute__ ((packed));
#define CEPH_MSG_PRIO_LOW 64
#define CEPH_MSG_PRIO_DEFAULT 127
#define CEPH_MSG_PRIO_HIGH 196
#define CEPH_MSG_PRIO_HIGHEST 255
/*
* follows data payload
* ceph_msg_footer_old does not support digital signatures on messages PLR
*/
struct ceph_msg_footer_old {
__le32 front_crc, middle_crc, data_crc;
__u8 flags;
} __attribute__ ((packed));
struct ceph_msg_footer {
__le32 front_crc, middle_crc, data_crc;
// sig holds the 64 bits of the digital signature for the message PLR
__le64 sig;
__u8 flags;
} __attribute__ ((packed));
#define CEPH_MSG_FOOTER_COMPLETE (1<<0) /* msg wasn't aborted */
#define CEPH_MSG_FOOTER_NOCRC (1<<1) /* no data crc */
#define CEPH_MSG_FOOTER_SIGNED (1<<2) /* msg was signed */
#ifndef __KERNEL__
#undef __le16
#undef __le32
#undef __le64
#endif
#endif
| 7,552 | 28.503906 | 84 | h |
null | ceph-main/src/include/object.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_OBJECT_H
#define CEPH_OBJECT_H
#include <cstdint>
#include <cstdio>
#include <iomanip>
#include <iosfwd>
#include <string>
#include <string>
#include <string_view>
#include "include/rados.h"
#include "include/unordered_map.h"
#include "hash.h"
#include "encoding.h"
#include "ceph_hash.h"
struct object_t {
std::string name;
object_t() {}
// cppcheck-suppress noExplicitConstructor
object_t(const char *s) : name(s) {}
// cppcheck-suppress noExplicitConstructor
object_t(const std::string& s) : name(s) {}
object_t(std::string&& s) : name(std::move(s)) {}
object_t(std::string_view s) : name(s) {}
auto operator<=>(const object_t&) const noexcept = default;
void swap(object_t& o) {
name.swap(o.name);
}
void clear() {
name.clear();
}
void encode(ceph::buffer::list &bl) const {
using ceph::encode;
encode(name, bl);
}
void decode(ceph::buffer::list::const_iterator &bl) {
using ceph::decode;
decode(name, bl);
}
};
WRITE_CLASS_ENCODER(object_t)
inline std::ostream& operator<<(std::ostream& out, const object_t& o) {
return out << o.name;
}
namespace std {
template<> struct hash<object_t> {
size_t operator()(const object_t& r) const {
//static hash<string> H;
//return H(r.name);
return ceph_str_hash_linux(r.name.c_str(), r.name.length());
}
};
} // namespace std
struct file_object_t {
uint64_t ino, bno;
mutable char buf[34];
file_object_t(uint64_t i=0, uint64_t b=0) : ino(i), bno(b) {
buf[0] = 0;
}
const char *c_str() const {
if (!buf[0])
snprintf(buf, sizeof(buf), "%llx.%08llx", (long long unsigned)ino, (long long unsigned)bno);
return buf;
}
operator object_t() {
return object_t(c_str());
}
};
// ---------------------------
// snaps
struct snapid_t {
uint64_t val;
// cppcheck-suppress noExplicitConstructor
snapid_t(uint64_t v=0) : val(v) {}
snapid_t operator+=(snapid_t o) { val += o.val; return *this; }
snapid_t operator++() { ++val; return *this; }
operator uint64_t() const { return val; }
};
inline void encode(snapid_t i, ceph::buffer::list &bl) {
using ceph::encode;
encode(i.val, bl);
}
inline void decode(snapid_t &i, ceph::buffer::list::const_iterator &p) {
using ceph::decode;
decode(i.val, p);
}
template<>
struct denc_traits<snapid_t> {
static constexpr bool supported = true;
static constexpr bool featured = false;
static constexpr bool bounded = true;
static constexpr bool need_contiguous = true;
static void bound_encode(const snapid_t& o, size_t& p) {
denc(o.val, p);
}
static void encode(const snapid_t &o, ceph::buffer::list::contiguous_appender& p) {
denc(o.val, p);
}
static void decode(snapid_t& o, ceph::buffer::ptr::const_iterator &p) {
denc(o.val, p);
}
};
inline std::ostream& operator<<(std::ostream& out, const snapid_t& s) {
if (s == CEPH_NOSNAP)
return out << "head";
else if (s == CEPH_SNAPDIR)
return out << "snapdir";
else
return out << std::hex << s.val << std::dec;
}
struct sobject_t {
object_t oid;
snapid_t snap;
sobject_t() : snap(0) {}
sobject_t(object_t o, snapid_t s) : oid(o), snap(s) {}
auto operator<=>(const sobject_t&) const noexcept = default;
void swap(sobject_t& o) {
oid.swap(o.oid);
snapid_t t = snap;
snap = o.snap;
o.snap = t;
}
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
encode(oid, bl);
encode(snap, bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
using ceph::decode;
decode(oid, bl);
decode(snap, bl);
}
};
WRITE_CLASS_ENCODER(sobject_t)
inline std::ostream& operator<<(std::ostream& out, const sobject_t &o) {
return out << o.oid << "/" << o.snap;
}
namespace std {
template<> struct hash<sobject_t> {
size_t operator()(const sobject_t &r) const {
static hash<object_t> H;
static rjhash<uint64_t> I;
return H(r.oid) ^ I(r.snap);
}
};
} // namespace std
#endif
| 4,408 | 22.205263 | 98 | h |
null | ceph-main/src/include/object_fmt.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
/**
* \file fmtlib formatters for some object.h structs
*/
#include <fmt/format.h>
#include "object.h"
template <>
struct fmt::formatter<snapid_t> {
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const snapid_t& snp, FormatContext& ctx) const
{
if (snp == CEPH_NOSNAP) {
return fmt::format_to(ctx.out(), "head");
}
if (snp == CEPH_SNAPDIR) {
return fmt::format_to(ctx.out(), "snapdir");
}
return fmt::format_to(ctx.out(), "{:x}", snp.val);
}
};
| 677 | 21.6 | 73 | h |
null | ceph-main/src/include/rados.h | #ifndef CEPH_RADOS_H
#define CEPH_RADOS_H
/*
* Data types for the Ceph distributed object storage layer RADOS
* (Reliable Autonomic Distributed Object Store).
*/
#include <string.h>
#include <stdbool.h>
#include "msgr.h"
/* See comment in ceph_fs.h. */
#ifndef __KERNEL__
#include "byteorder.h"
#define __le16 ceph_le16
#define __le32 ceph_le32
#define __le64 ceph_le64
#endif
/*
* fs id
*/
struct ceph_fsid {
unsigned char fsid[16];
};
static inline int ceph_fsid_compare(const struct ceph_fsid *a,
const struct ceph_fsid *b)
{
return memcmp(a, b, sizeof(*a));
}
/*
* ino, object, etc.
*/
typedef __le64 ceph_snapid_t;
#define CEPH_SNAPDIR ((__u64)(-1)) /* reserved for hidden .snap dir */
#define CEPH_NOSNAP ((__u64)(-2)) /* "head", "live" revision */
#define CEPH_MAXSNAP ((__u64)(-3)) /* largest valid snapid */
struct ceph_timespec {
__le32 tv_sec;
__le32 tv_nsec;
} __attribute__ ((packed));
/*
* object layout - how objects are mapped into PGs
*/
#define CEPH_OBJECT_LAYOUT_HASH 1
#define CEPH_OBJECT_LAYOUT_LINEAR 2
#define CEPH_OBJECT_LAYOUT_HASHINO 3
/*
* pg layout -- how PGs are mapped onto (sets of) OSDs
*/
#define CEPH_PG_LAYOUT_CRUSH 0
#define CEPH_PG_LAYOUT_HASH 1
#define CEPH_PG_LAYOUT_LINEAR 2
#define CEPH_PG_LAYOUT_HYBRID 3
#define CEPH_PG_MAX_SIZE 16 /* max # osds in a single pg */
/*
* placement group.
* we encode this into one __le64.
*/
struct ceph_pg {
__le16 preferred; /* preferred primary osd */
__le16 ps; /* placement seed */
__le32 pool; /* object pool */
} __attribute__ ((packed));
/*
* pg pool types
*
* NOTE: These map 1:1 on to the pg_pool_t::TYPE_* values. They are
* duplicated here only for CrushCompiler's benefit.
*/
#define CEPH_PG_TYPE_REPLICATED 1
/* #define CEPH_PG_TYPE_RAID4 2 never implemented */
#define CEPH_PG_TYPE_ERASURE 3
/*
* stable_mod func is used to control number of placement groups.
* similar to straight-up modulo, but produces a stable mapping as b
* increases over time. b is the number of bins, and bmask is the
* containing power of 2 minus 1.
*
* b <= bmask and bmask=(2**n)-1
* e.g., b=12 -> bmask=15, b=123 -> bmask=127
*
* ** This function is released to the public domain by the author. **
*/
static inline int ceph_stable_mod(int x, int b, int bmask)
{
if ((x & bmask) < b)
return x & bmask;
else
return x & (bmask >> 1);
}
/*
* object layout - how a given object should be stored.
*/
struct ceph_object_layout {
struct ceph_pg ol_pgid; /* raw pg, with _full_ ps precision. */
__le32 ol_stripe_unit; /* for per-object parity, if any */
} __attribute__ ((packed));
/*
* compound epoch+version, used by storage layer to serialize mutations
*/
struct ceph_eversion {
__le32 epoch;
__le64 version;
} __attribute__ ((packed));
/*
* osd map bits
*/
/* status bits */
#define CEPH_OSD_EXISTS (1<<0)
#define CEPH_OSD_UP (1<<1)
#define CEPH_OSD_AUTOOUT (1<<2) /* osd was automatically marked out */
#define CEPH_OSD_NEW (1<<3) /* osd is new, never marked in */
#define CEPH_OSD_FULL (1<<4) /* osd is at or above full threshold */
#define CEPH_OSD_NEARFULL (1<<5) /* osd is at or above nearfull threshold */
#define CEPH_OSD_BACKFILLFULL (1<<6) /* osd is at or above backfillfull threshold */
#define CEPH_OSD_DESTROYED (1<<7) /* osd has been destroyed */
#define CEPH_OSD_NOUP (1<<8) /* osd can not be marked up */
#define CEPH_OSD_NODOWN (1<<9) /* osd can not be marked down */
#define CEPH_OSD_NOIN (1<<10) /* osd can not be marked in */
#define CEPH_OSD_NOOUT (1<<11) /* osd can not be marked out */
#define CEPH_OSD_STOP (1<<12) /* osd has been stopped by admin */
extern const char *ceph_osd_state_name(int s);
/* osd weights. fixed point value: 0x10000 == 1.0 ("in"), 0 == "out" */
#define CEPH_OSD_IN 0x10000
#define CEPH_OSD_OUT 0
#define CEPH_OSD_MAX_PRIMARY_AFFINITY 0x10000
#define CEPH_OSD_DEFAULT_PRIMARY_AFFINITY 0x10000
/*
* osd map flag bits
*/
#define CEPH_OSDMAP_NEARFULL (1<<0) /* sync writes (near ENOSPC), deprecated since mimic*/
#define CEPH_OSDMAP_FULL (1<<1) /* no data writes (ENOSPC), deprecated since mimic */
#define CEPH_OSDMAP_PAUSERD (1<<2) /* pause all reads */
#define CEPH_OSDMAP_PAUSEWR (1<<3) /* pause all writes */
#define CEPH_OSDMAP_PAUSEREC (1<<4) /* pause recovery */
#define CEPH_OSDMAP_NOUP (1<<5) /* block osd boot */
#define CEPH_OSDMAP_NODOWN (1<<6) /* block osd mark-down/failure */
#define CEPH_OSDMAP_NOOUT (1<<7) /* block osd auto mark-out */
#define CEPH_OSDMAP_NOIN (1<<8) /* block osd auto mark-in */
#define CEPH_OSDMAP_NOBACKFILL (1<<9) /* block osd backfill */
#define CEPH_OSDMAP_NORECOVER (1<<10) /* block osd recovery and backfill */
#define CEPH_OSDMAP_NOSCRUB (1<<11) /* block periodic scrub */
#define CEPH_OSDMAP_NODEEP_SCRUB (1<<12) /* block periodic deep-scrub */
#define CEPH_OSDMAP_NOTIERAGENT (1<<13) /* disable tiering agent */
#define CEPH_OSDMAP_NOREBALANCE (1<<14) /* block osd backfill unless pg is degraded */
#define CEPH_OSDMAP_SORTBITWISE (1<<15) /* use bitwise hobject_t sort */
#define CEPH_OSDMAP_REQUIRE_JEWEL (1<<16) /* require jewel for booting osds */
#define CEPH_OSDMAP_REQUIRE_KRAKEN (1<<17) /* require kraken for booting osds */
#define CEPH_OSDMAP_REQUIRE_LUMINOUS (1<<18) /* require l for booting osds */
#define CEPH_OSDMAP_RECOVERY_DELETES (1<<19) /* deletes performed during recovery instead of peering */
#define CEPH_OSDMAP_PURGED_SNAPDIRS (1<<20) /* osds have converted snapsets */
#define CEPH_OSDMAP_NOSNAPTRIM (1<<21) /* disable snap trimming */
#define CEPH_OSDMAP_PGLOG_HARDLIMIT (1<<22) /* put a hard limit on pg log length */
/* these are hidden in 'ceph status' view */
#define CEPH_OSDMAP_SEMIHIDDEN_FLAGS (CEPH_OSDMAP_REQUIRE_JEWEL| \
CEPH_OSDMAP_REQUIRE_KRAKEN | \
CEPH_OSDMAP_REQUIRE_LUMINOUS | \
CEPH_OSDMAP_RECOVERY_DELETES | \
CEPH_OSDMAP_SORTBITWISE | \
CEPH_OSDMAP_PURGED_SNAPDIRS | \
CEPH_OSDMAP_PGLOG_HARDLIMIT)
#define CEPH_OSDMAP_LEGACY_REQUIRE_FLAGS (CEPH_OSDMAP_REQUIRE_JEWEL | \
CEPH_OSDMAP_REQUIRE_KRAKEN | \
CEPH_OSDMAP_REQUIRE_LUMINOUS)
/*
* major ceph release numbers
*/
#define CEPH_RELEASE_ARGONAUT 1
#define CEPH_RELEASE_BOBTAIL 2
#define CEPH_RELEASE_CUTTLEFISH 3
#define CEPH_RELEASE_DUMPLING 4
#define CEPH_RELEASE_EMPEROR 5
#define CEPH_RELEASE_FIREFLY 6
#define CEPH_RELEASE_GIANT 7
#define CEPH_RELEASE_HAMMER 8
#define CEPH_RELEASE_INFERNALIS 9
#define CEPH_RELEASE_JEWEL 10
#define CEPH_RELEASE_KRAKEN 11
#define CEPH_RELEASE_LUMINOUS 12
#define CEPH_RELEASE_MIMIC 13
#define CEPH_RELEASE_NAUTILUS 14
#define CEPH_RELEASE_OCTOPUS 15
#define CEPH_RELEASE_PACIFIC 16
#define CEPH_RELEASE_QUINCY 17
#define CEPH_RELEASE_REEF 18
#define CEPH_RELEASE_MAX 19 /* highest + 1 */
/*
* The error code to return when an OSD can't handle a write
* because it is too large.
*/
#define OSD_WRITETOOBIG EMSGSIZE
/*
* osd ops
*
* WARNING: do not use these op codes directly. Use the helpers
* defined below instead. In certain cases, op code behavior was
* redefined, resulting in special-cases in the helpers.
*/
#define CEPH_OSD_OP_MODE 0xf000
#define CEPH_OSD_OP_MODE_RD 0x1000
#define CEPH_OSD_OP_MODE_WR 0x2000
#define CEPH_OSD_OP_MODE_RMW 0x3000
#define CEPH_OSD_OP_MODE_SUB 0x4000
#define CEPH_OSD_OP_MODE_CACHE 0x8000
#define CEPH_OSD_OP_TYPE 0x0f00
#define CEPH_OSD_OP_TYPE_DATA 0x0200
#define CEPH_OSD_OP_TYPE_ATTR 0x0300
#define CEPH_OSD_OP_TYPE_EXEC 0x0400
#define CEPH_OSD_OP_TYPE_PG 0x0500
// LEAVE UNUSED 0x0600 used to be multiobject ops
#define __CEPH_OSD_OP1(mode, nr) \
(CEPH_OSD_OP_MODE_##mode | (nr))
#define __CEPH_OSD_OP(mode, type, nr) \
(CEPH_OSD_OP_MODE_##mode | CEPH_OSD_OP_TYPE_##type | (nr))
#define __CEPH_FORALL_OSD_OPS(f) \
/** data **/ \
/* read */ \
f(READ, __CEPH_OSD_OP(RD, DATA, 1), "read") \
f(STAT, __CEPH_OSD_OP(RD, DATA, 2), "stat") \
f(MAPEXT, __CEPH_OSD_OP(RD, DATA, 3), "mapext") \
f(CHECKSUM, __CEPH_OSD_OP(RD, DATA, 31), "checksum") \
\
/* fancy read */ \
f(MASKTRUNC, __CEPH_OSD_OP(RD, DATA, 4), "masktrunc") \
f(SPARSE_READ, __CEPH_OSD_OP(RD, DATA, 5), "sparse-read") \
\
f(NOTIFY, __CEPH_OSD_OP(RD, DATA, 6), "notify") \
f(NOTIFY_ACK, __CEPH_OSD_OP(RD, DATA, 7), "notify-ack") \
\
/* versioning */ \
f(ASSERT_VER, __CEPH_OSD_OP(RD, DATA, 8), "assert-version") \
\
f(LIST_WATCHERS, __CEPH_OSD_OP(RD, DATA, 9), "list-watchers") \
\
f(LIST_SNAPS, __CEPH_OSD_OP(RD, DATA, 10), "list-snaps") \
\
/* sync */ \
f(SYNC_READ, __CEPH_OSD_OP(RD, DATA, 11), "sync_read") \
\
/* write */ \
f(WRITE, __CEPH_OSD_OP(WR, DATA, 1), "write") \
f(WRITEFULL, __CEPH_OSD_OP(WR, DATA, 2), "writefull") \
f(TRUNCATE, __CEPH_OSD_OP(WR, DATA, 3), "truncate") \
f(ZERO, __CEPH_OSD_OP(WR, DATA, 4), "zero") \
f(DELETE, __CEPH_OSD_OP(WR, DATA, 5), "delete") \
\
/* fancy write */ \
f(APPEND, __CEPH_OSD_OP(WR, DATA, 6), "append") \
f(STARTSYNC, __CEPH_OSD_OP(WR, DATA, 7), "startsync") \
f(SETTRUNC, __CEPH_OSD_OP(WR, DATA, 8), "settrunc") \
f(TRIMTRUNC, __CEPH_OSD_OP(WR, DATA, 9), "trimtrunc") \
\
f(TMAPUP, __CEPH_OSD_OP(RMW, DATA, 10), "tmapup") \
f(TMAPPUT, __CEPH_OSD_OP(WR, DATA, 11), "tmapput") \
f(TMAPGET, __CEPH_OSD_OP(RD, DATA, 12), "tmapget") \
\
f(CREATE, __CEPH_OSD_OP(WR, DATA, 13), "create") \
f(ROLLBACK, __CEPH_OSD_OP(WR, DATA, 14), "rollback") \
\
f(WATCH, __CEPH_OSD_OP(WR, DATA, 15), "watch") \
\
/* omap */ \
f(OMAPGETKEYS, __CEPH_OSD_OP(RD, DATA, 17), "omap-get-keys") \
f(OMAPGETVALS, __CEPH_OSD_OP(RD, DATA, 18), "omap-get-vals") \
f(OMAPGETHEADER, __CEPH_OSD_OP(RD, DATA, 19), "omap-get-header") \
f(OMAPGETVALSBYKEYS, __CEPH_OSD_OP(RD, DATA, 20), "omap-get-vals-by-keys") \
f(OMAPSETVALS, __CEPH_OSD_OP(WR, DATA, 21), "omap-set-vals") \
f(OMAPSETHEADER, __CEPH_OSD_OP(WR, DATA, 22), "omap-set-header") \
f(OMAPCLEAR, __CEPH_OSD_OP(WR, DATA, 23), "omap-clear") \
f(OMAPRMKEYS, __CEPH_OSD_OP(WR, DATA, 24), "omap-rm-keys") \
f(OMAPRMKEYRANGE, __CEPH_OSD_OP(WR, DATA, 44), "omap-rm-key-range") \
f(OMAP_CMP, __CEPH_OSD_OP(RD, DATA, 25), "omap-cmp") \
\
/* tiering */ \
f(COPY_FROM, __CEPH_OSD_OP(WR, DATA, 26), "copy-from") \
f(COPY_FROM2, __CEPH_OSD_OP(WR, DATA, 45), "copy-from2") \
/* was copy-get-classic */ \
f(UNDIRTY, __CEPH_OSD_OP(WR, DATA, 28), "undirty") \
f(ISDIRTY, __CEPH_OSD_OP(RD, DATA, 29), "isdirty") \
f(COPY_GET, __CEPH_OSD_OP(RD, DATA, 30), "copy-get") \
f(CACHE_FLUSH, __CEPH_OSD_OP(CACHE, DATA, 31), "cache-flush") \
f(CACHE_EVICT, __CEPH_OSD_OP(CACHE, DATA, 32), "cache-evict") \
f(CACHE_TRY_FLUSH, __CEPH_OSD_OP(CACHE, DATA, 33), "cache-try-flush") \
\
/* convert tmap to omap */ \
f(TMAP2OMAP, __CEPH_OSD_OP(RMW, DATA, 34), "tmap2omap") \
\
/* hints */ \
f(SETALLOCHINT, __CEPH_OSD_OP(WR, DATA, 35), "set-alloc-hint") \
\
/* cache pin/unpin */ \
f(CACHE_PIN, __CEPH_OSD_OP(WR, DATA, 36), "cache-pin") \
f(CACHE_UNPIN, __CEPH_OSD_OP(WR, DATA, 37), "cache-unpin") \
\
/* ESX/SCSI */ \
f(WRITESAME, __CEPH_OSD_OP(WR, DATA, 38), "write-same") \
f(CMPEXT, __CEPH_OSD_OP(RD, DATA, 32), "cmpext") \
\
/* Extensible */ \
f(SET_REDIRECT, __CEPH_OSD_OP(WR, DATA, 39), "set-redirect") \
f(SET_CHUNK, __CEPH_OSD_OP(CACHE, DATA, 40), "set-chunk") \
f(TIER_PROMOTE, __CEPH_OSD_OP(WR, DATA, 41), "tier-promote") \
f(UNSET_MANIFEST, __CEPH_OSD_OP(WR, DATA, 42), "unset-manifest") \
f(TIER_FLUSH, __CEPH_OSD_OP(CACHE, DATA, 43), "tier-flush") \
f(TIER_EVICT, __CEPH_OSD_OP(CACHE, DATA, 44), "tier-evict") \
\
/** attrs **/ \
/* read */ \
f(GETXATTR, __CEPH_OSD_OP(RD, ATTR, 1), "getxattr") \
f(GETXATTRS, __CEPH_OSD_OP(RD, ATTR, 2), "getxattrs") \
f(CMPXATTR, __CEPH_OSD_OP(RD, ATTR, 3), "cmpxattr") \
\
/* write */ \
f(SETXATTR, __CEPH_OSD_OP(WR, ATTR, 1), "setxattr") \
f(SETXATTRS, __CEPH_OSD_OP(WR, ATTR, 2), "setxattrs") \
f(RESETXATTRS, __CEPH_OSD_OP(WR, ATTR, 3), "resetxattrs") \
f(RMXATTR, __CEPH_OSD_OP(WR, ATTR, 4), "rmxattr") \
\
/** subop **/ \
f(PULL, __CEPH_OSD_OP1(SUB, 1), "pull") \
f(PUSH, __CEPH_OSD_OP1(SUB, 2), "push") \
f(BALANCEREADS, __CEPH_OSD_OP1(SUB, 3), "balance-reads") \
f(UNBALANCEREADS, __CEPH_OSD_OP1(SUB, 4), "unbalance-reads") \
f(SCRUB, __CEPH_OSD_OP1(SUB, 5), "scrub") \
f(SCRUB_RESERVE, __CEPH_OSD_OP1(SUB, 6), "scrub-reserve") \
f(SCRUB_UNRESERVE, __CEPH_OSD_OP1(SUB, 7), "scrub-unreserve") \
/* 8 used to be scrub-stop */ \
f(SCRUB_MAP, __CEPH_OSD_OP1(SUB, 9), "scrub-map") \
\
/** exec **/ \
/* note: the RD bit here is wrong; see special-case below in helper */ \
f(CALL, __CEPH_OSD_OP(RD, EXEC, 1), "call") \
\
/** pg **/ \
f(PGLS, __CEPH_OSD_OP(RD, PG, 1), "pgls") \
f(PGLS_FILTER, __CEPH_OSD_OP(RD, PG, 2), "pgls-filter") \
f(PG_HITSET_LS, __CEPH_OSD_OP(RD, PG, 3), "pg-hitset-ls") \
f(PG_HITSET_GET, __CEPH_OSD_OP(RD, PG, 4), "pg-hitset-get") \
f(PGNLS, __CEPH_OSD_OP(RD, PG, 5), "pgnls") \
f(PGNLS_FILTER, __CEPH_OSD_OP(RD, PG, 6), "pgnls-filter") \
f(SCRUBLS, __CEPH_OSD_OP(RD, PG, 7), "scrubls")
enum {
#define GENERATE_ENUM_ENTRY(op, opcode, str) CEPH_OSD_OP_##op = (opcode),
__CEPH_FORALL_OSD_OPS(GENERATE_ENUM_ENTRY)
#undef GENERATE_ENUM_ENTRY
};
static inline int ceph_osd_op_type_data(int op)
{
return (op & CEPH_OSD_OP_TYPE) == CEPH_OSD_OP_TYPE_DATA;
}
static inline int ceph_osd_op_type_attr(int op)
{
return (op & CEPH_OSD_OP_TYPE) == CEPH_OSD_OP_TYPE_ATTR;
}
static inline int ceph_osd_op_type_exec(int op)
{
return (op & CEPH_OSD_OP_TYPE) == CEPH_OSD_OP_TYPE_EXEC;
}
static inline int ceph_osd_op_type_pg(int op)
{
return (op & CEPH_OSD_OP_TYPE) == CEPH_OSD_OP_TYPE_PG;
}
static inline int ceph_osd_op_mode_subop(int op)
{
return (op & CEPH_OSD_OP_MODE) == CEPH_OSD_OP_MODE_SUB;
}
static inline int ceph_osd_op_mode_read(int op)
{
return (op & CEPH_OSD_OP_MODE_RD) &&
op != CEPH_OSD_OP_CALL;
}
static inline int ceph_osd_op_mode_modify(int op)
{
return op & CEPH_OSD_OP_MODE_WR;
}
static inline int ceph_osd_op_mode_cache(int op)
{
return op & CEPH_OSD_OP_MODE_CACHE;
}
static inline bool ceph_osd_op_uses_extent(int op)
{
switch(op) {
case CEPH_OSD_OP_READ:
case CEPH_OSD_OP_MAPEXT:
case CEPH_OSD_OP_MASKTRUNC:
case CEPH_OSD_OP_SPARSE_READ:
case CEPH_OSD_OP_SYNC_READ:
case CEPH_OSD_OP_WRITE:
case CEPH_OSD_OP_WRITEFULL:
case CEPH_OSD_OP_TRUNCATE:
case CEPH_OSD_OP_ZERO:
case CEPH_OSD_OP_APPEND:
case CEPH_OSD_OP_TRIMTRUNC:
case CEPH_OSD_OP_CMPEXT:
return true;
default:
return false;
}
}
/*
* note that the following tmap stuff is also defined in the ceph librados.h
* and objclass.h. Any modification here needs to be updated there
*/
#define CEPH_OSD_TMAP_HDR 'h'
#define CEPH_OSD_TMAP_SET 's'
#define CEPH_OSD_TMAP_CREATE 'c' /* create key */
#define CEPH_OSD_TMAP_RM 'r'
#define CEPH_OSD_TMAP_RMSLOPPY 'R'
extern const char *ceph_osd_op_name(int op);
/*
* osd op flags
*
* An op may be READ, WRITE, or READ|WRITE.
*/
enum {
CEPH_OSD_FLAG_ACK = 0x0001, /* want (or is) "ack" ack */
CEPH_OSD_FLAG_ONNVRAM = 0x0002, /* want (or is) "onnvram" ack */
CEPH_OSD_FLAG_ONDISK = 0x0004, /* want (or is) "ondisk" ack */
CEPH_OSD_FLAG_RETRY = 0x0008, /* resend attempt */
CEPH_OSD_FLAG_READ = 0x0010, /* op may read */
CEPH_OSD_FLAG_WRITE = 0x0020, /* op may write */
CEPH_OSD_FLAG_ORDERSNAP = 0x0040, /* EOLDSNAP if snapc is out of order */
CEPH_OSD_FLAG_PEERSTAT_OLD = 0x0080, /* DEPRECATED msg includes osd_peer_stat */
CEPH_OSD_FLAG_BALANCE_READS = 0x0100,
CEPH_OSD_FLAG_PARALLELEXEC = 0x0200, /* execute op in parallel */
CEPH_OSD_FLAG_PGOP = 0x0400, /* pg op, no object */
CEPH_OSD_FLAG_EXEC = 0x0800, /* op may exec */
CEPH_OSD_FLAG_EXEC_PUBLIC = 0x1000, /* DEPRECATED op may exec (public) */
CEPH_OSD_FLAG_LOCALIZE_READS = 0x2000, /* read from nearby replica, if any */
CEPH_OSD_FLAG_RWORDERED = 0x4000, /* order wrt concurrent reads */
CEPH_OSD_FLAG_IGNORE_CACHE = 0x8000, /* ignore cache logic */
CEPH_OSD_FLAG_SKIPRWLOCKS = 0x10000, /* skip rw locks */
CEPH_OSD_FLAG_IGNORE_OVERLAY =0x20000, /* ignore pool overlay */
CEPH_OSD_FLAG_FLUSH = 0x40000, /* this is part of flush */
CEPH_OSD_FLAG_MAP_SNAP_CLONE =0x80000, /* map snap direct to clone id
*/
CEPH_OSD_FLAG_ENFORCE_SNAPC =0x100000, /* use snapc provided even if
pool uses pool snaps */
CEPH_OSD_FLAG_REDIRECTED = 0x200000, /* op has been redirected */
CEPH_OSD_FLAG_KNOWN_REDIR = 0x400000, /* redirect bit is authoritative */
CEPH_OSD_FLAG_FULL_TRY = 0x800000, /* try op despite full flag */
CEPH_OSD_FLAG_FULL_FORCE = 0x1000000, /* force op despite full flag */
CEPH_OSD_FLAG_IGNORE_REDIRECT = 0x2000000, /* ignore redirection */
CEPH_OSD_FLAG_RETURNVEC = 0x4000000, /* allow overall result >= 0, and return >= 0 and buffer for each op in opvec */
CEPH_OSD_FLAG_SUPPORTSPOOLEIO = 0x8000000, /* client understands pool EIO flag */
};
enum {
CEPH_OSD_OP_FLAG_EXCL = 0x1, /* EXCL object create */
CEPH_OSD_OP_FLAG_FAILOK = 0x2, /* continue despite failure */
CEPH_OSD_OP_FLAG_FADVISE_RANDOM = 0x4, /* the op is random */
CEPH_OSD_OP_FLAG_FADVISE_SEQUENTIAL = 0x8, /* the op is sequential */
CEPH_OSD_OP_FLAG_FADVISE_WILLNEED = 0x10,/* data will be accessed in the near future */
CEPH_OSD_OP_FLAG_FADVISE_DONTNEED = 0x20,/* data will not be accessed in the near future */
CEPH_OSD_OP_FLAG_FADVISE_NOCACHE = 0x40, /* data will be accessed only once by this client */
CEPH_OSD_OP_FLAG_WITH_REFERENCE = 0x80, /* need reference couting */
CEPH_OSD_OP_FLAG_BYPASS_CLEAN_CACHE = 0x100, /* bypass ObjectStore cache, mainly for deep-scrub */
};
#define EOLDSNAPC 85 /* ORDERSNAP flag set; writer has old snapc*/
#define EBLOCKLISTED 108 /* blocklisted */
#define EBLACKLISTED 108 /* deprecated */
/* xattr comparison */
enum {
CEPH_OSD_CMPXATTR_OP_EQ = 1,
CEPH_OSD_CMPXATTR_OP_NE = 2,
CEPH_OSD_CMPXATTR_OP_GT = 3,
CEPH_OSD_CMPXATTR_OP_GTE = 4,
CEPH_OSD_CMPXATTR_OP_LT = 5,
CEPH_OSD_CMPXATTR_OP_LTE = 6
};
enum {
CEPH_OSD_CMPXATTR_MODE_STRING = 1,
CEPH_OSD_CMPXATTR_MODE_U64 = 2
};
enum {
CEPH_OSD_COPY_FROM_FLAG_FLUSH = 1, /* part of a flush operation */
CEPH_OSD_COPY_FROM_FLAG_IGNORE_OVERLAY = 2, /* ignore pool overlay */
CEPH_OSD_COPY_FROM_FLAG_IGNORE_CACHE = 4, /* ignore osd cache logic */
CEPH_OSD_COPY_FROM_FLAG_MAP_SNAP_CLONE = 8, /* map snap direct to
* cloneid */
CEPH_OSD_COPY_FROM_FLAG_RWORDERED = 16, /* order with write */
CEPH_OSD_COPY_FROM_FLAG_TRUNCATE_SEQ = 32, /* use provided truncate_{seq,size} (copy-from2 only) */
};
#define CEPH_OSD_COPY_FROM_FLAGS \
(CEPH_OSD_COPY_FROM_FLAG_FLUSH | \
CEPH_OSD_COPY_FROM_FLAG_IGNORE_OVERLAY | \
CEPH_OSD_COPY_FROM_FLAG_IGNORE_CACHE | \
CEPH_OSD_COPY_FROM_FLAG_MAP_SNAP_CLONE | \
CEPH_OSD_COPY_FROM_FLAG_RWORDERED | \
CEPH_OSD_COPY_FROM_FLAG_TRUNCATE_SEQ)
enum {
CEPH_OSD_TMAP2OMAP_NULLOK = 1,
};
enum {
CEPH_OSD_WATCH_OP_UNWATCH = 0,
CEPH_OSD_WATCH_OP_LEGACY_WATCH = 1,
/* note: use only ODD ids to prevent pre-giant code from
interpreting the op as UNWATCH */
CEPH_OSD_WATCH_OP_WATCH = 3,
CEPH_OSD_WATCH_OP_RECONNECT = 5,
CEPH_OSD_WATCH_OP_PING = 7,
};
enum {
CEPH_OSD_CHECKSUM_OP_TYPE_XXHASH32 = 0,
CEPH_OSD_CHECKSUM_OP_TYPE_XXHASH64 = 1,
CEPH_OSD_CHECKSUM_OP_TYPE_CRC32C = 2
};
const char *ceph_osd_watch_op_name(int o);
enum {
CEPH_OSD_ALLOC_HINT_FLAG_SEQUENTIAL_WRITE = 1,
CEPH_OSD_ALLOC_HINT_FLAG_RANDOM_WRITE = 2,
CEPH_OSD_ALLOC_HINT_FLAG_SEQUENTIAL_READ = 4,
CEPH_OSD_ALLOC_HINT_FLAG_RANDOM_READ = 8,
CEPH_OSD_ALLOC_HINT_FLAG_APPEND_ONLY = 16,
CEPH_OSD_ALLOC_HINT_FLAG_IMMUTABLE = 32,
CEPH_OSD_ALLOC_HINT_FLAG_SHORTLIVED = 64,
CEPH_OSD_ALLOC_HINT_FLAG_LONGLIVED = 128,
CEPH_OSD_ALLOC_HINT_FLAG_COMPRESSIBLE = 256,
CEPH_OSD_ALLOC_HINT_FLAG_INCOMPRESSIBLE = 512,
};
const char *ceph_osd_alloc_hint_flag_name(int f);
enum {
CEPH_OSD_BACKOFF_OP_BLOCK = 1,
CEPH_OSD_BACKOFF_OP_ACK_BLOCK = 2,
CEPH_OSD_BACKOFF_OP_UNBLOCK = 3,
};
const char *ceph_osd_backoff_op_name(int op);
/*
* an individual object operation. each may be accompanied by some data
* payload
*/
struct ceph_osd_op {
__le16 op; /* CEPH_OSD_OP_* */
__le32 flags; /* CEPH_OSD_OP_FLAG_* */
union {
struct {
__le64 offset, length;
__le64 truncate_size;
__le32 truncate_seq;
} __attribute__ ((packed)) extent;
struct {
__le32 name_len;
__le32 value_len;
__u8 cmp_op; /* CEPH_OSD_CMPXATTR_OP_* */
__u8 cmp_mode; /* CEPH_OSD_CMPXATTR_MODE_* */
} __attribute__ ((packed)) xattr;
struct {
__u8 class_len;
__u8 method_len;
__u8 argc;
__le32 indata_len;
} __attribute__ ((packed)) cls;
struct {
__le64 count;
__le32 start_epoch; /* for the pgls sequence */
} __attribute__ ((packed)) pgls;
struct {
__le64 snapid;
} __attribute__ ((packed)) snap;
struct {
__le64 cookie;
__le64 ver; /* no longer used */
__u8 op; /* CEPH_OSD_WATCH_OP_* */
__u32 gen; /* registration generation */
__u32 timeout; /* connection timeout */
} __attribute__ ((packed)) watch;
struct {
__le64 cookie;
} __attribute__ ((packed)) notify;
struct {
__le64 unused;
__le64 ver;
} __attribute__ ((packed)) assert_ver;
struct {
__le64 offset, length;
__le64 src_offset;
} __attribute__ ((packed)) clonerange;
struct {
__le64 max; /* max data in reply */
} __attribute__ ((packed)) copy_get;
struct {
__le64 snapid;
__le64 src_version;
__u8 flags; /* CEPH_OSD_COPY_FROM_FLAG_* */
/*
* CEPH_OSD_OP_FLAG_FADVISE_*: fadvise flags
* for src object, flags for dest object are in
* ceph_osd_op::flags.
*/
__le32 src_fadvise_flags;
} __attribute__ ((packed)) copy_from;
struct {
struct ceph_timespec stamp;
} __attribute__ ((packed)) hit_set_get;
struct {
__u8 flags;
} __attribute__ ((packed)) tmap2omap;
struct {
__le64 expected_object_size;
__le64 expected_write_size;
__le32 flags; /* CEPH_OSD_OP_ALLOC_HINT_FLAG_* */
} __attribute__ ((packed)) alloc_hint;
struct {
__le64 offset;
__le64 length;
__le64 data_length;
} __attribute__ ((packed)) writesame;
struct {
__le64 offset;
__le64 length;
__le32 chunk_size;
__u8 type; /* CEPH_OSD_CHECKSUM_OP_TYPE_* */
} __attribute__ ((packed)) checksum;
} __attribute__ ((packed));
__le32 payload_len;
} __attribute__ ((packed));
/*
* Check the compatibility of struct ceph_osd_op
* (2+4+(2*8+8+4)+4) = (sizeof(ceph_osd_op::op) +
* sizeof(ceph_osd_op::flags) +
* sizeof(ceph_osd_op::extent) +
* sizeof(ceph_osd_op::payload_len))
*/
#ifdef __cplusplus
static_assert(sizeof(ceph_osd_op) == (2+4+(2*8+8+4)+4),
"sizeof(ceph_osd_op) breaks the compatibility");
#endif
struct ceph_osd_reply_head {
__le32 client_inc; /* client incarnation */
__le32 flags;
struct ceph_object_layout layout;
__le32 osdmap_epoch;
struct ceph_eversion reassert_version; /* for replaying uncommitted */
__le32 result; /* result code */
__le32 object_len; /* length of object name */
__le32 num_ops;
struct ceph_osd_op ops[0]; /* ops[], object */
} __attribute__ ((packed));
#ifndef __KERNEL__
#undef __le16
#undef __le32
#undef __le64
#endif
#endif
| 24,587 | 34.125714 | 118 | h |
null | ceph-main/src/include/random.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 SUSE 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_RANDOM_H
#define CEPH_RANDOM_H 1
#include <mutex>
#include <random>
#include <type_traits>
#include <boost/optional.hpp>
// Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85494
#ifdef __MINGW32__
#include <boost/random/random_device.hpp>
using random_device_t = boost::random::random_device;
#else
using random_device_t = std::random_device;
#endif
// Basic random number facility (see N3551 for inspiration):
namespace ceph::util {
inline namespace version_1_0_3 {
namespace detail {
template <typename T0, typename T1>
using larger_of = typename std::conditional<
sizeof(T0) >= sizeof(T1),
T0, T1>
::type;
// avoid mixing floating point and integers:
template <typename NumberT0, typename NumberT1>
using has_compatible_numeric_types =
std::disjunction<
std::conjunction<
std::is_floating_point<NumberT0>, std::is_floating_point<NumberT1>
>,
std::conjunction<
std::is_integral<NumberT0>, std::is_integral<NumberT1>
>
>;
// Select the larger of type compatible numeric types:
template <typename NumberT0, typename NumberT1>
using select_number_t = std::enable_if_t<detail::has_compatible_numeric_types<NumberT0, NumberT1>::value,
detail::larger_of<NumberT0, NumberT1>>;
} // namespace detail
namespace detail {
// Choose default distribution for appropriate types:
template <typename NumberT,
bool IsIntegral>
struct select_distribution
{
using type = std::uniform_int_distribution<NumberT>;
};
template <typename NumberT>
struct select_distribution<NumberT, false>
{
using type = std::uniform_real_distribution<NumberT>;
};
template <typename NumberT>
using default_distribution = typename
select_distribution<NumberT, std::is_integral<NumberT>::value>::type;
} // namespace detail
namespace detail {
template <typename EngineT>
EngineT& engine();
template <typename MutexT, typename EngineT,
typename SeedT = typename EngineT::result_type>
void randomize_rng(const SeedT seed, MutexT& m, EngineT& e)
{
std::lock_guard<MutexT> lg(m);
e.seed(seed);
}
template <typename MutexT, typename EngineT>
void randomize_rng(MutexT& m, EngineT& e)
{
random_device_t rd;
std::lock_guard<MutexT> lg(m);
e.seed(rd());
}
template <typename EngineT = std::default_random_engine,
typename SeedT = typename EngineT::result_type>
void randomize_rng(const SeedT n)
{
detail::engine<EngineT>().seed(n);
}
template <typename EngineT = std::default_random_engine>
void randomize_rng()
{
random_device_t rd;
detail::engine<EngineT>().seed(rd());
}
template <typename EngineT>
EngineT& engine()
{
thread_local boost::optional<EngineT> rng_engine;
if (!rng_engine) {
rng_engine.emplace(EngineT());
randomize_rng<EngineT>();
}
return *rng_engine;
}
} // namespace detail
namespace detail {
template <typename NumberT,
typename DistributionT = detail::default_distribution<NumberT>,
typename EngineT>
NumberT generate_random_number(const NumberT min, const NumberT max,
EngineT& e)
{
DistributionT d { min, max };
using param_type = typename DistributionT::param_type;
return d(e, param_type { min, max });
}
template <typename NumberT,
typename MutexT,
typename DistributionT = detail::default_distribution<NumberT>,
typename EngineT>
NumberT generate_random_number(const NumberT min, const NumberT max,
MutexT& m, EngineT& e)
{
DistributionT d { min, max };
using param_type = typename DistributionT::param_type;
std::lock_guard<MutexT> lg(m);
return d(e, param_type { min, max });
}
template <typename NumberT,
typename DistributionT = detail::default_distribution<NumberT>,
typename EngineT>
NumberT generate_random_number(const NumberT min, const NumberT max)
{
return detail::generate_random_number<NumberT, DistributionT, EngineT>
(min, max, detail::engine<EngineT>());
}
template <typename MutexT,
typename EngineT,
typename NumberT = int,
typename DistributionT = detail::default_distribution<NumberT>>
NumberT generate_random_number(MutexT& m, EngineT& e)
{
return detail::generate_random_number<NumberT, MutexT, DistributionT, EngineT>
(0, std::numeric_limits<NumberT>::max(), m, e);
}
template <typename NumberT, typename MutexT, typename EngineT>
NumberT generate_random_number(const NumberT max, MutexT& m, EngineT& e)
{
return generate_random_number<NumberT>(0, max, m, e);
}
} // namespace detail
template <typename EngineT = std::default_random_engine>
void randomize_rng()
{
detail::randomize_rng<EngineT>();
}
template <typename NumberT = int,
typename DistributionT = detail::default_distribution<NumberT>,
typename EngineT = std::default_random_engine>
NumberT generate_random_number()
{
return detail::generate_random_number<NumberT, DistributionT, EngineT>
(0, std::numeric_limits<NumberT>::max());
}
template <typename NumberT0, typename NumberT1,
typename NumberT = detail::select_number_t<NumberT0, NumberT1>
>
NumberT generate_random_number(const NumberT0 min, const NumberT1 max)
{
return detail::generate_random_number<NumberT,
detail::default_distribution<NumberT>,
std::default_random_engine>
(static_cast<NumberT>(min), static_cast<NumberT>(max));
}
template <typename NumberT0, typename NumberT1,
typename DistributionT,
typename EngineT,
typename NumberT = detail::select_number_t<NumberT0, NumberT1>
>
NumberT generate_random_number(const NumberT min, const NumberT max,
EngineT& e)
{
return detail::generate_random_number<NumberT,
DistributionT,
EngineT>(static_cast<NumberT>(min), static_cast<NumberT>(max), e);
}
template <typename NumberT>
NumberT generate_random_number(const NumberT max)
{
return generate_random_number<NumberT>(0, max);
}
// Function object:
template <typename NumberT>
class random_number_generator final
{
std::mutex l;
random_device_t rd;
std::default_random_engine e;
using seed_type = typename decltype(e)::result_type;
public:
using number_type = NumberT;
using random_engine_type = decltype(e);
using random_device_type = decltype(rd);
public:
random_device_type& random_device() noexcept { return rd; }
random_engine_type& random_engine() noexcept { return e; }
public:
random_number_generator() {
detail::randomize_rng(l, e);
}
explicit random_number_generator(const seed_type seed) {
detail::randomize_rng(seed, l, e);
}
random_number_generator(random_number_generator&& rhs)
: e(std::move(rhs.e))
{}
public:
random_number_generator(const random_number_generator&) = delete;
random_number_generator& operator=(const random_number_generator&) = delete;
public:
NumberT operator()() {
return detail::generate_random_number(l, e);
}
NumberT operator()(const NumberT max) {
return detail::generate_random_number<NumberT>(max, l, e);
}
NumberT operator()(const NumberT min, const NumberT max) {
return detail::generate_random_number<NumberT>(min, max, l, e);
}
public:
void seed(const seed_type n) {
detail::randomize_rng(n, l, e);
}
};
template <typename NumberT>
random_number_generator(const NumberT max) -> random_number_generator<NumberT>;
} // inline namespace version_*
} // namespace ceph::util
#endif
| 8,256 | 26.34106 | 105 | h |
null | ceph-main/src/include/rbd_types.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2010 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_RBD_TYPES_H
#define CEPH_RBD_TYPES_H
#include "include/types.h"
#include "rbd/features.h"
/* New-style rbd image 'foo' consists of objects
* rbd_id.foo - id of image
* rbd_header.<id> - image metadata
* rbd_object_map.<id> - optional image object map
* rbd_data.<id>.00000000
* rbd_data.<id>.00000001
* ... - data
*/
#define RBD_HEADER_PREFIX "rbd_header."
#define RBD_OBJECT_MAP_PREFIX "rbd_object_map."
#define RBD_DATA_PREFIX "rbd_data."
#define RBD_ID_PREFIX "rbd_id."
/*
* old-style rbd image 'foo' consists of objects
* foo.rbd - image metadata
* rb.<idhi>.<idlo>.00000000
* rb.<idhi>.<idlo>.00000001
* ... - data
*/
#define RBD_SUFFIX ".rbd"
#define RBD_DIRECTORY "rbd_directory"
#define RBD_INFO "rbd_info"
#define RBD_NAMESPACE "rbd_namespace"
#define RBD_TASK "rbd_task"
/*
* rbd_children object in each pool contains omap entries
* that map parent (poolid, imageid, snapid) to a list of children
* (imageids; snapids aren't required because we get all the snapshot
* info from a read of the child's header object anyway).
*
* The clone operation writes a new item to this child list, and rm or
* flatten removes an item, and may remove the whole entry if no children
* exist after the rm/flatten.
*
* When attempting to remove a parent, all pools are searched for
* rbd_children objects with entries referring to that parent; if any
* exist (and those children exist), the parent removal is prevented.
*/
#define RBD_CHILDREN "rbd_children"
#define RBD_LOCK_NAME "rbd_lock"
/**
* rbd_mirroring object in each pool contains pool-specific settings
* for configuring mirroring.
*/
#define RBD_MIRRORING "rbd_mirroring"
/**
* rbd_mirror_leader and rbd_mirror_instance.<instance id> objects are used
* for pool-level coordination between rbd-mirror daemons.
*/
#define RBD_MIRROR_LEADER "rbd_mirror_leader"
#define RBD_MIRROR_INSTANCE_PREFIX "rbd_mirror_instance."
#define RBD_MAX_OBJ_NAME_SIZE 96
#define RBD_MAX_BLOCK_NAME_SIZE 24
/**
* Maximum string length of the RBD v2 image id (not including
* null termination). This limit was derived from the existing
* RBD_MAX_BLOCK_NAME_SIZE limit which needs to hold the "rbd_data."
* prefix and null termination.
*/
#define RBD_MAX_IMAGE_ID_LENGTH 14
/**
* Maximum string length of the RBD block object name prefix (not including
* null termination).
*
* v1 format: rb.<max 8-byte high id>.<max 8-byte low id>.<max 8-byte extra>
* v2 format: rbd_data.[<max 19-byte pool id>.]<max 14-byte image id>
*
* Note: new features might require increasing this maximum prefix length.
*/
#define RBD_MAX_BLOCK_NAME_PREFIX_LENGTH 43
#define RBD_COMP_NONE 0
#define RBD_CRYPT_NONE 0
#define RBD_HEADER_TEXT "<<< Rados Block Device Image >>>\n"
#define RBD_MIGRATE_HEADER_TEXT "<<< Migrating RBD Image >>>\n"
#define RBD_HEADER_SIGNATURE "RBD"
#define RBD_HEADER_VERSION "001.005"
#define RBD_GROUP_INVALID_POOL (-1)
#define RBD_GROUP_HEADER_PREFIX "rbd_group_header."
#define RBD_GROUP_DIRECTORY "rbd_group_directory"
#define RBD_TRASH "rbd_trash"
/**
* MON config-key prefix for storing optional remote cluster connectivity
* parameters
*/
#define RBD_MIRROR_CONFIG_KEY_PREFIX "rbd/mirror/"
#define RBD_MIRROR_SITE_NAME_CONFIG_KEY RBD_MIRROR_CONFIG_KEY_PREFIX "site_name"
#define RBD_MIRROR_PEER_CLIENT_ID_CONFIG_KEY RBD_MIRROR_CONFIG_KEY_PREFIX "peer_client_id"
#define RBD_MIRROR_PEER_CONFIG_KEY_PREFIX RBD_MIRROR_CONFIG_KEY_PREFIX "peer/"
struct rbd_info {
ceph_le64 max_id;
} __attribute__ ((packed));
struct rbd_obj_snap_ondisk {
ceph_le64 id;
ceph_le64 image_size;
} __attribute__((packed));
struct rbd_obj_header_ondisk {
char text[40];
char block_name[RBD_MAX_BLOCK_NAME_SIZE];
char signature[4];
char version[8];
struct {
__u8 order;
__u8 crypt_type;
__u8 comp_type;
__u8 unused;
} __attribute__((packed)) options;
ceph_le64 image_size;
ceph_le64 snap_seq;
ceph_le32 snap_count;
ceph_le32 reserved;
ceph_le64 snap_names_len;
struct rbd_obj_snap_ondisk snaps[0];
} __attribute__((packed));
enum {
RBD_PROTECTION_STATUS_UNPROTECTED = 0,
RBD_PROTECTION_STATUS_UNPROTECTING = 1,
RBD_PROTECTION_STATUS_PROTECTED = 2,
RBD_PROTECTION_STATUS_LAST = 3
};
#endif
| 4,766 | 28.79375 | 91 | h |
null | ceph-main/src/include/scope_guard.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 Red Hat
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef SCOPE_GUARD
#define SCOPE_GUARD
#include <utility>
template <typename F>
struct scope_guard {
F f;
scope_guard() = delete;
scope_guard(const scope_guard &) = delete;
scope_guard(scope_guard &&) = default;
scope_guard & operator=(const scope_guard &) = delete;
scope_guard & operator=(scope_guard &&) = default;
scope_guard(const F& f) : f(f) {}
scope_guard(F &&f) : f(std::move(f)) {}
template<typename... Args>
scope_guard(std::in_place_t, Args&& ...args) : f(std::forward<Args>(args)...) {}
~scope_guard() {
std::move(f)(); // Support at-most-once functions
}
};
template <typename F>
[[nodiscard("Unassigned scope guards will execute immediately")]]
scope_guard<F> make_scope_guard(F &&f) {
return scope_guard<F>(std::forward<F>(f));
}
template<typename F, typename... Args>
[[nodiscard("Unassigned scope guards will execute immediately")]]
scope_guard<F> make_scope_guard(std::in_place_type_t<F>, Args&& ...args) {
return { std::in_place, std::forward<Args>(args)... };
}
#endif
| 1,427 | 27.56 | 82 | h |
null | ceph-main/src/include/sock_compat.h | /*
* 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_SOCK_COMPAT_H
#define CEPH_SOCK_COMPAT_H
#include "include/compat.h"
#include <sys/socket.h>
/*
* This optimization may not be available on all platforms (e.g. OSX).
* Apparently a similar approach based on TCP_CORK can be used.
*/
#ifndef MSG_MORE
# define MSG_MORE 0
#endif
/*
* On BSD SO_NOSIGPIPE can be set via setsockopt to block SIGPIPE.
*/
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
# ifdef SO_NOSIGPIPE
# define CEPH_USE_SO_NOSIGPIPE
# else
# define CEPH_USE_SIGPIPE_BLOCKER
# warning "Using SIGPIPE blocking instead of suppression; this is not well-tested upstream!"
# endif
#endif
int socket_cloexec(int domain, int type, int protocol);
int socketpair_cloexec(int domain, int type, int protocol, int sv[2]);
int accept_cloexec(int sockfd, struct sockaddr* addr, socklen_t* addrlen);
#endif
| 1,133 | 24.772727 | 93 | h |
null | ceph-main/src/include/statlite.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_STATLITE_H
#define CEPH_STATLITE_H
extern "C" {
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include "include/compat.h"
struct statlite {
dev_t st_dev; /* device */
ino_t st_ino; /* inode */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device type (if inode device)*/
unsigned long st_litemask; /* bit mask for optional fields */
/***************************************************************/
/**** Remaining fields are optional according to st_litemask ***/
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
struct timespec st_atim; /* Time of last access. */
struct timespec st_mtim; /* Time of last modification. */
struct timespec st_ctim; /* Time of last status change. */
//time_t st_atime; /* time of last access */
//time_t st_mtime; /* time of last modification */
//time_t st_ctime; /* time of last change */
};
#define S_STATLITE_SIZE 1
#define S_STATLITE_BLKSIZE 2
#define S_STATLITE_BLOCKS 4
#define S_STATLITE_ATIME 8
#define S_STATLITE_MTIME 16
#define S_STATLITE_CTIME 32
#define S_REQUIRESIZE(m) (m | S_STATLITE_SIZE)
#define S_REQUIREBLKSIZE(m) (m | S_STATLITE_BLKSIZE)
#define S_REQUIREBLOCKS(m) (m | S_STATLITE_BLOCKS)
#define S_REQUIREATIME(m) (m | S_STATLITE_ATIME)
#define S_REQUIREMTIME(m) (m | S_STATLITE_MTIME)
#define S_REQUIRECTIME(m) (m | S_STATLITE_CTIME)
#define S_ISVALIDSIZE(m) (m & S_STATLITE_SIZE)
#define S_ISVALIDBLKSIZE(m) (m & S_STATLITE_BLKSIZE)
#define S_ISVALIDBLOCKS(m) (m & S_STATLITE_BLOCKS)
#define S_ISVALIDATIME(m) (m & S_STATLITE_ATIME)
#define S_ISVALIDMTIME(m) (m & S_STATLITE_MTIME)
#define S_ISVALIDCTIME(m) (m & S_STATLITE_CTIME)
// readdirplus etc.
struct dirent_plus {
struct dirent d_dirent; /* dirent struct for this entry */
struct stat d_stat; /* attributes for this entry */
int d_stat_err;/* errno for d_stat, or 0 */
};
struct dirent_lite {
struct dirent d_dirent; /* dirent struct for this entry */
struct statlite d_stat; /* attributes for this entry */
int d_stat_err;/* errno for d_stat, or 0 */
};
}
#endif
| 2,750 | 35.68 | 72 | h |
null | ceph-main/src/include/str_list.h | #ifndef CEPH_STRLIST_H
#define CEPH_STRLIST_H
#include <list>
#include <set>
#include <string>
#include <string_view>
#include <vector>
namespace ceph {
/// Split a string using the given delimiters, passing each piece as a
/// (non-null-terminated) std::string_view to the callback.
template <typename Func> // where Func(std::string_view) is a valid call
void for_each_substr(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); // trim delims from the front
auto end = s.find_first_of(delims);
f(s.substr(0, end));
pos = s.find_first_not_of(delims, end);
}
}
} // namespace ceph
/**
* Split **str** into a list of strings, using the ";,= \t" delimiters and output the result in **str_list**.
*
* @param [in] str String to split and save as list
* @param [out] str_list List modified containing str after it has been split
**/
extern void get_str_list(const std::string& str,
std::list<std::string>& str_list);
/**
* Split **str** into a list of strings, using the **delims** delimiters and output the result in **str_list**.
*
* @param [in] str String to split and save as list
* @param [in] delims characters used to split **str**
* @param [out] str_list List modified containing str after it has been split
**/
extern void get_str_list(const std::string& str,
const char *delims,
std::list<std::string>& str_list);
std::list<std::string> get_str_list(const std::string& str,
const char *delims = ";,= \t");
/**
* Split **str** into a vector of strings, using the ";,= \t" delimiters and output the result in **str_vec**.
*
* @param [in] str String to split and save as Vector
* @param [out] str_vec Vector modified containing str after it has been split
**/
void get_str_vec(std::string_view str, std::vector<std::string>& str_vec);
/**
* Split **str** into a vector of strings, using the **delims** delimiters and output the result in **str_vec**.
*
* @param [in] str String to split and save as Vector
* @param [in] delims characters used to split **str**
* @param [out] str_vec Vector modified containing str after it has been split
**/
void get_str_vec(std::string_view str,
const char *delims,
std::vector<std::string>& str_vec);
std::vector<std::string> get_str_vec(std::string_view str,
const char *delims = ";,= \t");
/**
* Return a String containing the vector **v** joined with **sep**
*
* If **v** is empty, the function returns an empty string
* For each element in **v**,
* it will concatenate this element and **sep** with result
*
* @param [in] v Vector to join as a String
* @param [in] sep String used to join each element from **v**
* @return empty string if **v** is empty or concatenated string
**/
inline std::string str_join(const std::vector<std::string>& v, const std::string& sep)
{
if (v.empty())
return std::string();
auto i = v.cbegin();
std::string r = *i;
for (++i; i != v.cend(); ++i) {
r += sep;
r += *i;
}
return r;
}
#endif
| 3,179 | 31.44898 | 112 | h |
null | ceph-main/src/include/str_map.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Cloudwatt <[email protected]>
*
* Author: Loic Dachary <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
#ifndef CEPH_STRMAP_H
#define CEPH_STRMAP_H
#define CONST_DELIMS ",;\t\n "
#include <map>
#include <string>
#include <sstream>
template <typename Func>
void for_each_pair(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); // trim delims from the front
auto end = s.find_first_of(delims);
auto kv = s.substr(0, end);
if (auto equal = kv.find('='); equal != kv.npos) {
f(kv.substr(0, equal), kv.substr(equal + 1));
} else {
f(kv.substr(0, equal), std::string_view());
}
pos = s.find_first_not_of(delims, end);
}
}
using str_map_t = std::map<std::string,std::string>;
/**
* Parse **str** and set **str_map** with the key/value pairs read
* from it. The format of **str** is either a well formed JSON object
* or a custom key[=value] plain text format.
*
* JSON is tried first. If successfully parsed into a JSON object, it
* is copied into **str_map** verbatim. If it is not a JSON object ( a
* string, integer etc. ), -EINVAL is returned and **ss** is set to
* a human readable error message.
*
* If **str** is no valid JSON and if **fallback_to_plain** is set to true
* (default: true) it is assumed to be a string containing white space
* separated key=value pairs. A white space is either space, tab or newline.
* Function **get_str_map** will be leveraged to parse the plain-text
* key/value pairs.
*
* @param [in] str JSON or plain text key/value pairs
* @param [out] ss human readable message on error
* @param [out] str_map key/value pairs read from str
* @param [in] fallback_to_plain attempt parsing as plain-text if json fails
* @return **0** on success or a -EINVAL on error.
*/
int get_json_str_map(
const std::string &str,
std::ostream &ss,
str_map_t* str_map,
bool fallback_to_plain = true);
/**
* Parse **str** and set **str_map** with the key/value pairs read from
* it. The format of **str** is a number of custom key[=value] pairs in
* plain text format.
*
* The string will be parsed taking **delims** as field delimiters for
* key/values. The value is optional resulting in an empty string when
* not provided. For example, using white space as delimiters:
*
* insert your own=political/ideological statement=here
*
* will be parsed into:
*
* { "insert": "",
* "your": "",
* "own": "political/ideological",
* "statement": "here" }
*
* Alternative delimiters may be provided. For instance, specifying
* "white space and slash", for the above statement, would be parsed
* into:
*
* { "insert": "",
* "your": "",
* "own": "political",
* "ideological": "",
* "statement": "here" }
*
* See how adding '/' to the delimiters field will spawn a new key without
* a set value.
*
* Always returns 0, as there is no condition for failure.
*
* @param [in] str plain text key/value pairs
* @param [in] delims field delimiters to be used for parsing str
* @param [out] str_map key/value pairs parsed from str
* @return **0**
*/
int get_str_map(
const std::string &str,
str_map_t* str_map,
const char *delims = CONST_DELIMS);
// an alternate form (as we never fail):
str_map_t get_str_map(
const std::string& str,
const char* delim = CONST_DELIMS);
/**
* Returns the value of **key** in **str_map** if available.
*
* If **key** is not available in **str_map**, and if **def_val** is
* not-NULL then returns **def_val**. Otherwise checks if the value of
* **key** is an empty string and if so will return **key**.
* If the map contains **key**, the function returns the value of **key**.
*
* @param[in] str_map Map to obtain **key** from
* @param[in] key The key to search for in the map
* @param[in] def_val The value to return in case **key** is not present
*/
std::string get_str_map_value(
const str_map_t& str_map,
const std::string &key,
const std::string *def_val = nullptr);
/**
* Returns the value of **key** in **str_map** if available.
*
* If **key** is available in **str_map** returns the value of **key**.
*
* If **key** is not available in **str_map**, and if **def_key**
* is not-NULL and available in **str_map**, then returns the value
* of **def_key**.
*
* Otherwise returns an empty string.
*
* @param[in] str_map Map to obtain **key** or **def_key** from
* @param[in] key Key to obtain the value of from **str_map**
* @param[in] def_key Key to fallback to if **key** is not present
* in **str_map**
*/
std::string get_str_map_key(
const str_map_t& str_map,
const std::string &key,
const std::string *fallback_key = nullptr);
// This function's only purpose is to check whether a given map has only
// ONE key with an empty value (which would mean that 'get_str_map()' read
// a map in the form of 'VALUE', without any KEY/VALUE pairs) and, in such
// event, to assign said 'VALUE' to a given 'def_key', such that we end up
// with a map of the form "m = { 'def_key' : 'VALUE' }" instead of the
// original "m = { 'VALUE' : '' }".
int get_conf_str_map_helper(
const std::string &str,
std::ostringstream &oss,
str_map_t* str_map,
const std::string &default_key);
std::string get_value_via_strmap(
const std::string& conf_string,
std::string_view default_key);
std::string get_value_via_strmap(
const std::string& conf_string,
const std::string& key,
std::string_view default_key);
#endif
| 6,044 | 32.39779 | 76 | h |
null | ceph-main/src/include/timegm.h | // (C) Copyright Howard Hinnant
// (C) Copyright 2010-2011 Vicente J. Botet Escriba
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//===-------------------------- locale ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This code was adapted by Vicente from Howard Hinnant's experimental work
// on chrono i/o to Boost and some functions from libc++/locale to emulate the missing time_get::get()
#ifndef BOOST_CHRONO_IO_TIME_POINT_IO_H
#define BOOST_CHRONO_IO_TIME_POINT_IO_H
#include <time.h>
static int32_t is_leap(int32_t year) {
if(year % 400 == 0)
return 1;
if(year % 100 == 0)
return 0;
if(year % 4 == 0)
return 1;
return 0;
}
static int32_t days_from_0(int32_t year) {
year--;
return 365 * year + (year / 400) - (year/100) + (year / 4);
}
int32_t static days_from_1970(int32_t year) {
static const int days_from_0_to_1970 = days_from_0(1970);
return days_from_0(year) - days_from_0_to_1970;
}
static int32_t days_from_1jan(int32_t year,int32_t month,int32_t day) {
static const int32_t days[2][12] =
{
{ 0,31,59,90,120,151,181,212,243,273,304,334},
{ 0,31,60,91,121,152,182,213,244,274,305,335}
};
return days[is_leap(year)][month-1] + day - 1;
}
static time_t internal_timegm(tm const *t) {
int year = t->tm_year + 1900;
int month = t->tm_mon;
if(month > 11)
{
year += month/12;
month %= 12;
}
else if(month < 0)
{
int years_diff = (-month + 11)/12;
year -= years_diff;
month+=12 * years_diff;
}
month++;
int day = t->tm_mday;
int day_of_year = days_from_1jan(year,month,day);
int days_since_epoch = days_from_1970(year) + day_of_year ;
time_t seconds_in_day = 3600 * 24;
time_t result = seconds_in_day * days_since_epoch + 3600 * t->tm_hour + 60 * t->tm_min + t->tm_sec;
return result;
}
#endif
| 2,229 | 26.875 | 102 | h |
null | ceph-main/src/include/types.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_TYPES_H
#define CEPH_TYPES_H
// this is needed for ceph_fs to compile in userland
#include "int_types.h"
#include "byteorder.h"
#include "uuid.h"
#include <netinet/in.h>
#include <fcntl.h>
#include <string.h>
#include "ceph_fs.h"
#include "ceph_frag.h"
#include "rbd_types.h"
#ifdef __cplusplus
#ifndef _BACKWARD_BACKWARD_WARNING_H
#define _BACKWARD_BACKWARD_WARNING_H // make gcc 4.3 shut up about hash_*
#endif
#endif
extern "C" {
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "statlite.h"
}
#include <string>
#include <list>
#include <set>
#include <boost/container/flat_set.hpp>
#include <boost/container/flat_map.hpp>
#include <map>
#include <vector>
#include <optional>
#include <ostream>
#include <iomanip>
#include "include/unordered_map.h"
#include "object.h"
#include "intarith.h"
#include "acconfig.h"
#include "assert.h"
// DARWIN compatibility
#ifdef __APPLE__
typedef long long loff_t;
typedef long long off64_t;
#define O_DIRECT 00040000
#endif
// FreeBSD compatibility
#ifdef __FreeBSD__
typedef off_t loff_t;
typedef off_t off64_t;
#endif
#if defined(__sun) || defined(_AIX)
typedef off_t loff_t;
#endif
// -- io helpers --
// Forward declare all the I/O helpers so strict ADL can find them in
// the case of containers of containers. I'm tempted to abstract this
// stuff using template templates like I did for denc.
namespace std {
template<class A, class B>
inline std::ostream& operator<<(std::ostream&out, const std::pair<A,B>& v);
template<class A, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::vector<A,Alloc>& v);
template<class A, std::size_t N, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const boost::container::small_vector<A,N,Alloc>& v);
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::deque<A,Alloc>& v);
template<typename... Ts>
inline std::ostream& operator<<(std::ostream& out, const std::tuple<Ts...> &t);
template<typename T>
inline std::ostream& operator<<(std::ostream& out, const std::optional<T> &t);
template<class A, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::list<A,Alloc>& ilist);
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::set<A, Comp, Alloc>& iset);
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::multiset<A,Comp,Alloc>& iset);
template<class A, class B, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::map<A,B,Comp,Alloc>& m);
template<class A, class B, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::multimap<A,B,Comp,Alloc>& m);
}
namespace boost {
template<typename... Ts>
inline std::ostream& operator<<(std::ostream& out, const boost::tuple<Ts...> &t);
namespace container {
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const boost::container::flat_set<A, Comp, Alloc>& iset);
template<class A, class B, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const boost::container::flat_map<A, B, Comp, Alloc>& iset);
}
}
namespace std {
template<class A, class B>
inline std::ostream& operator<<(std::ostream& out, const std::pair<A,B>& v) {
return out << v.first << "," << v.second;
}
template<class A, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::vector<A,Alloc>& v) {
bool first = true;
out << "[";
for (const auto& p : v) {
if (!first) out << ",";
out << p;
first = false;
}
out << "]";
return out;
}
template<class A, std::size_t N, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const boost::container::small_vector<A,N,Alloc>& v) {
bool first = true;
out << "[";
for (const auto& p : v) {
if (!first) out << ",";
out << p;
first = false;
}
out << "]";
return out;
}
template<class A, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::deque<A,Alloc>& v) {
out << "<";
for (auto p = v.begin(); p != v.end(); ++p) {
if (p != v.begin()) out << ",";
out << *p;
}
out << ">";
return out;
}
template<typename... Ts>
inline std::ostream& operator<<(std::ostream& out, const std::tuple<Ts...> &t) {
auto f = [n = sizeof...(Ts), i = 0U, &out](const auto& e) mutable {
out << e;
if (++i != n)
out << ",";
};
ceph::for_each(t, f);
return out;
}
// Mimics boost::optional
template<typename T>
inline std::ostream& operator<<(std::ostream& out, const std::optional<T> &t) {
if (!t)
out << "--" ;
else
out << ' ' << *t ;
return out;
}
template<class A, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::list<A,Alloc>& ilist) {
for (auto it = ilist.begin();
it != ilist.end();
++it) {
if (it != ilist.begin()) out << ",";
out << *it;
}
return out;
}
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::set<A, Comp, Alloc>& iset) {
for (auto it = iset.begin();
it != iset.end();
++it) {
if (it != iset.begin()) out << ",";
out << *it;
}
return out;
}
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::multiset<A,Comp,Alloc>& iset) {
for (auto it = iset.begin();
it != iset.end();
++it) {
if (it != iset.begin()) out << ",";
out << *it;
}
return out;
}
template<class A, class B, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::map<A,B,Comp,Alloc>& m)
{
out << "{";
for (auto it = m.begin();
it != m.end();
++it) {
if (it != m.begin()) out << ",";
out << it->first << "=" << it->second;
}
out << "}";
return out;
}
template<class A, class B, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const std::multimap<A,B,Comp,Alloc>& m)
{
out << "{{";
for (auto it = m.begin();
it != m.end();
++it) {
if (it != m.begin()) out << ",";
out << it->first << "=" << it->second;
}
out << "}}";
return out;
}
} // namespace std
namespace boost {
namespace tuples {
template<typename A, typename B, typename C>
inline std::ostream& operator<<(std::ostream& out, const boost::tuples::tuple<A, B, C> &t) {
return out << boost::get<0>(t) << ","
<< boost::get<1>(t) << ","
<< boost::get<2>(t);
}
}
namespace container {
template<class A, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const boost::container::flat_set<A, Comp, Alloc>& iset) {
for (auto it = iset.begin();
it != iset.end();
++it) {
if (it != iset.begin()) out << ",";
out << *it;
}
return out;
}
template<class A, class B, class Comp, class Alloc>
inline std::ostream& operator<<(std::ostream& out, const boost::container::flat_map<A, B, Comp, Alloc>& m) {
for (auto it = m.begin();
it != m.end();
++it) {
if (it != m.begin()) out << ",";
out << it->first << "=" << it->second;
}
return out;
}
}
} // namespace boost
/*
* comparators for stl containers
*/
// for ceph::unordered_map:
// ceph::unordered_map<const char*, long, hash<const char*>, eqstr> vals;
struct eqstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};
// for set, map
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
namespace ceph {
class Formatter;
}
#include "encoding.h"
WRITE_RAW_ENCODER(ceph_fsid)
WRITE_RAW_ENCODER(ceph_file_layout)
WRITE_RAW_ENCODER(ceph_dir_layout)
WRITE_RAW_ENCODER(ceph_mds_session_head)
WRITE_RAW_ENCODER(ceph_mds_request_head_legacy)
WRITE_RAW_ENCODER(ceph_mds_request_release)
WRITE_RAW_ENCODER(ceph_filelock)
WRITE_RAW_ENCODER(ceph_mds_caps_head)
WRITE_RAW_ENCODER(ceph_mds_caps_export_body)
WRITE_RAW_ENCODER(ceph_mds_caps_non_export_body)
WRITE_RAW_ENCODER(ceph_mds_cap_peer)
WRITE_RAW_ENCODER(ceph_mds_cap_release)
WRITE_RAW_ENCODER(ceph_mds_cap_item)
WRITE_RAW_ENCODER(ceph_mds_lease)
WRITE_RAW_ENCODER(ceph_mds_snap_head)
WRITE_RAW_ENCODER(ceph_mds_snap_realm)
WRITE_RAW_ENCODER(ceph_mds_reply_head)
WRITE_RAW_ENCODER(ceph_mds_reply_cap)
WRITE_RAW_ENCODER(ceph_mds_cap_reconnect)
WRITE_RAW_ENCODER(ceph_mds_snaprealm_reconnect)
WRITE_RAW_ENCODER(ceph_frag_tree_split)
WRITE_RAW_ENCODER(ceph_osd_reply_head)
WRITE_RAW_ENCODER(ceph_osd_op)
WRITE_RAW_ENCODER(ceph_msg_header)
WRITE_RAW_ENCODER(ceph_msg_footer)
WRITE_RAW_ENCODER(ceph_msg_footer_old)
WRITE_RAW_ENCODER(ceph_mon_subscribe_item)
WRITE_RAW_ENCODER(ceph_mon_statfs)
WRITE_RAW_ENCODER(ceph_mon_statfs_reply)
// ----------------------
// some basic types
// NOTE: these must match ceph_fs.h typedefs
typedef uint64_t ceph_tid_t; // transaction id
typedef uint64_t version_t;
typedef __u32 epoch_t; // map epoch (32bits -> 13 epochs/second for 10 years)
// --------------------------------------
// identify individual mount clients by 64bit value
struct client_t {
int64_t v;
// cppcheck-suppress noExplicitConstructor
client_t(int64_t _v = -2) : v(_v) {}
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
encode(v, bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
using ceph::decode;
decode(v, bl);
}
};
WRITE_CLASS_ENCODER(client_t)
static inline bool operator==(const client_t& l, const client_t& r) { return l.v == r.v; }
static inline bool operator!=(const client_t& l, const client_t& r) { return l.v != r.v; }
static inline bool operator<(const client_t& l, const client_t& r) { return l.v < r.v; }
static inline bool operator<=(const client_t& l, const client_t& r) { return l.v <= r.v; }
static inline bool operator>(const client_t& l, const client_t& r) { return l.v > r.v; }
static inline bool operator>=(const client_t& l, const client_t& r) { return l.v >= r.v; }
static inline bool operator>=(const client_t& l, int64_t o) { return l.v >= o; }
static inline bool operator<(const client_t& l, int64_t o) { return l.v < o; }
inline std::ostream& operator<<(std::ostream& out, const client_t& c) {
return out << c.v;
}
// --
namespace {
inline std::ostream& format_u(std::ostream& out, const uint64_t v, const uint64_t n,
const int index, const uint64_t mult, const char* u)
{
char buffer[32];
if (index == 0) {
(void) snprintf(buffer, sizeof(buffer), "%" PRId64 "%s", n, u);
} else if ((v % mult) == 0) {
// If this is an even multiple of the base, always display
// without any decimal fraction.
(void) snprintf(buffer, sizeof(buffer), "%" PRId64 "%s", n, u);
} else {
// We want to choose a precision that reflects the best choice
// for fitting in 5 characters. This can get rather tricky when
// we have numbers that are very close to an order of magnitude.
// For example, when displaying 10239 (which is really 9.999K),
// we want only a single place of precision for 10.0K. We could
// develop some complex heuristics for this, but it's much
// easier just to try each combination in turn.
int i;
for (i = 2; i >= 0; i--) {
if (snprintf(buffer, sizeof(buffer), "%.*f%s", i,
static_cast<double>(v) / mult, u) <= 7)
break;
}
}
return out << buffer;
}
}
/*
* Use this struct to pretty print values that should be formatted with a
* decimal unit prefix (the classic SI units). No actual unit will be added.
*/
struct si_u_t {
uint64_t v;
explicit si_u_t(uint64_t _v) : v(_v) {};
};
inline std::ostream& operator<<(std::ostream& out, const si_u_t& b)
{
uint64_t n = b.v;
int index = 0;
uint64_t mult = 1;
const char* u[] = {"", "k", "M", "G", "T", "P", "E"};
while (n >= 1000 && index < 7) {
n /= 1000;
index++;
mult *= 1000;
}
return format_u(out, b.v, n, index, mult, u[index]);
}
/*
* Use this struct to pretty print values that should be formatted with a
* binary unit prefix (IEC units). Since binary unit prefixes are to be used for
* "multiples of units in data processing, data transmission, and digital
* information" (so bits and bytes) and so far bits are not printed, the unit
* "B" for "byte" is added besides the multiplier.
*/
struct byte_u_t {
uint64_t v;
explicit byte_u_t(uint64_t _v) : v(_v) {};
};
inline std::ostream& operator<<(std::ostream& out, const byte_u_t& b)
{
uint64_t n = b.v;
int index = 0;
const char* u[] = {" B", " KiB", " MiB", " GiB", " TiB", " PiB", " EiB"};
while (n >= 1024 && index < 7) {
n /= 1024;
index++;
}
return format_u(out, b.v, n, index, 1ULL << (10 * index), u[index]);
}
inline std::ostream& operator<<(std::ostream& out, const ceph_mon_subscribe_item& i)
{
return out << (long)i.start
<< ((i.flags & CEPH_SUBSCRIBE_ONETIME) ? "" : "+");
}
struct weightf_t {
float v;
// cppcheck-suppress noExplicitConstructor
weightf_t(float _v) : v(_v) {}
};
inline std::ostream& operator<<(std::ostream& out, const weightf_t& w)
{
if (w.v < -0.01F) {
return out << "-";
} else if (w.v < 0.000001F) {
return out << "0";
} else {
std::streamsize p = out.precision();
return out << std::fixed << std::setprecision(5) << w.v << std::setprecision(p);
}
}
struct shard_id_t {
int8_t id;
shard_id_t() : id(0) {}
constexpr explicit shard_id_t(int8_t _id) : id(_id) {}
operator int8_t() const { return id; }
const static shard_id_t NO_SHARD;
void encode(ceph::buffer::list &bl) const {
using ceph::encode;
encode(id, bl);
}
void decode(ceph::buffer::list::const_iterator &bl) {
using ceph::decode;
decode(id, bl);
}
bool operator==(const shard_id_t&) const = default;
auto operator<=>(const shard_id_t&) const = default;
};
WRITE_CLASS_ENCODER(shard_id_t)
std::ostream &operator<<(std::ostream &lhs, const shard_id_t &rhs);
#if defined(__sun) || defined(_AIX) || defined(__APPLE__) || \
defined(__FreeBSD__) || defined(_WIN32)
extern "C" {
__s32 ceph_to_hostos_errno(__s32 e);
__s32 hostos_to_ceph_errno(__s32 e);
}
#else
#define ceph_to_hostos_errno(e) (e)
#define hostos_to_ceph_errno(e) (e)
#endif
struct errorcode32_t {
int32_t code;
errorcode32_t() : code(0) {}
// cppcheck-suppress noExplicitConstructor
explicit errorcode32_t(int32_t i) : code(i) {}
operator int() const { return code; }
int* operator&() { return &code; }
errorcode32_t& operator=(int32_t i) {
code = i;
return *this;
}
bool operator==(const errorcode32_t&) const = default;
auto operator<=>(const errorcode32_t&) const = default;
void encode(ceph::buffer::list &bl) const {
using ceph::encode;
__s32 newcode = hostos_to_ceph_errno(code);
encode(newcode, bl);
}
void decode(ceph::buffer::list::const_iterator &bl) {
using ceph::decode;
decode(code, bl);
code = ceph_to_hostos_errno(code);
}
};
WRITE_CLASS_ENCODER(errorcode32_t)
template <uint8_t S>
struct sha_digest_t {
constexpr static uint32_t SIZE = S;
// TODO: we might consider std::array in the future. Avoiding it for now
// as sha_digest_t is a part of our public API.
unsigned char v[S] = {0};
std::string to_str() const {
char str[S * 2 + 1] = {0};
str[0] = '\0';
for (size_t i = 0; i < S; i++) {
::sprintf(&str[i * 2], "%02x", static_cast<int>(v[i]));
}
return std::string(str);
}
sha_digest_t(const unsigned char *_v) { memcpy(v, _v, SIZE); };
sha_digest_t() {}
bool operator==(const sha_digest_t& r) const {
return ::memcmp(v, r.v, SIZE) == 0;
}
bool operator!=(const sha_digest_t& r) const {
return ::memcmp(v, r.v, SIZE) != 0;
}
void encode(ceph::buffer::list &bl) const {
// copy to avoid reinterpret_cast, is_pod and other nasty things
using ceph::encode;
std::array<unsigned char, SIZE> tmparr;
memcpy(tmparr.data(), v, SIZE);
encode(tmparr, bl);
}
void decode(ceph::buffer::list::const_iterator &bl) {
using ceph::decode;
std::array<unsigned char, SIZE> tmparr;
decode(tmparr, bl);
memcpy(v, tmparr.data(), SIZE);
}
};
template<uint8_t S>
inline std::ostream &operator<<(std::ostream &out, const sha_digest_t<S> &b) {
std::string str = b.to_str();
return out << str;
}
#if FMT_VERSION >= 90000
template <uint8_t S> struct fmt::formatter<sha_digest_t<S>> : fmt::ostream_formatter {};
#endif
using sha1_digest_t = sha_digest_t<20>;
WRITE_CLASS_ENCODER(sha1_digest_t)
using sha256_digest_t = sha_digest_t<32>;
WRITE_CLASS_ENCODER(sha256_digest_t)
using sha512_digest_t = sha_digest_t<64>;
using md5_digest_t = sha_digest_t<16>;
WRITE_CLASS_ENCODER(md5_digest_t)
#endif
| 17,254 | 26.388889 | 110 | h |
null | ceph-main/src/include/uses_allocator.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
// Derived from:
/* uses_allocator.h -*-C++-*-
*
* Copyright (C) 2016 Pablo Halpern <[email protected]>
* Distributed under the Boost Software License - Version 1.0
*/
// Downloaded from https://github.com/phalpern/uses-allocator.git
#pragma once
#include <memory>
#include <tuple>
#include <type_traits>
#include <utility>
namespace ceph {
namespace internal {
template <class T, class Tuple, std::size_t... Indexes>
T make_from_tuple_imp(Tuple&& t, std::index_sequence<Indexes...>)
{
return T(std::get<Indexes>(std::forward<Tuple>(t))...);
}
} // namespace internal
template<class T, class Tuple>
T make_from_tuple(Tuple&& args_tuple)
{
using namespace internal;
using Indices = std::make_index_sequence<std::tuple_size_v<
std::decay_t<Tuple>>>;
return make_from_tuple_imp<T>(std::forward<Tuple>(args_tuple), Indices{});
}
////////////////////////////////////////////////////////////////////////
// Forward declaration
template <class T, class Alloc, class... Args>
auto uses_allocator_construction_args(const Alloc& a, Args&&... args);
namespace internal {
template <class T, class A>
struct has_allocator : std::uses_allocator<T, A> { };
// Specialization of `has_allocator` for `std::pair`
template <class T1, class T2, class A>
struct has_allocator<std::pair<T1, T2>, A>
: std::integral_constant<bool, has_allocator<T1, A>::value ||
has_allocator<T2, A>::value>
{
};
template <bool V> using boolean_constant = std::integral_constant<bool, V>;
template <class T> struct is_pair : std::false_type { };
template <class T1, class T2>
struct is_pair<std::pair<T1, T2>> : std::true_type { };
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload is handles types for which `has_allocator<T, Alloc>` is false.
template <class T, class Unused1, class Unused2, class Alloc, class... Args>
auto uses_allocator_args_imp(Unused1 /* is_pair */,
std::false_type /* has_allocator */,
Unused2 /* uses prefix allocator arg */,
const Alloc& /* ignored */,
Args&&... args)
{
// Allocator is ignored
return std::forward_as_tuple(std::forward<Args>(args)...);
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles non-pair `T` for which `has_allocator<T, Alloc>` is
// true and constructor `T(allocator_arg_t, a, args...)` is valid.
template <class T, class Alloc, class... Args>
auto uses_allocator_args_imp(std::false_type /* is_pair */,
std::true_type /* has_allocator */,
std::true_type /* uses prefix allocator arg */,
const Alloc& a,
Args&&... args)
{
// Allocator added to front of argument list, after `allocator_arg`.
return std::tuple<std::allocator_arg_t, const Alloc&,
Args&&...>(std::allocator_arg, a, std::forward<Args>(args)...);
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles non-pair `T` for which `has_allocator<T, Alloc>` is
// true and constructor `T(allocator_arg_t, a, args...)` NOT valid.
// This function will produce invalid results unless `T(args..., a)` is valid.
template <class T1, class Alloc, class... Args>
auto uses_allocator_args_imp(std::false_type /* is_pair */,
std::true_type /* has_allocator */,
std::false_type /* prefix allocator arg */,
const Alloc& a,
Args&&... args)
{
// Allocator added to end of argument list
return std::forward_as_tuple(std::forward<Args>(args)..., a);
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles specializations of `T` = `std::pair` for which
// `has_allocator<T, Alloc>` is true for either or both of the elements and
// piecewise_construct arguments are passed in.
template <class T, class Alloc, class Tuple1, class Tuple2>
auto uses_allocator_args_imp(std::true_type /* is_pair */,
std::true_type /* has_allocator */,
std::false_type /* prefix allocator arg */,
const Alloc& a,
std::piecewise_construct_t,
Tuple1&& x, Tuple2&& y)
{
using T1 = typename T::first_type;
using T2 = typename T::second_type;
return std::make_tuple(
std::piecewise_construct,
std::apply([&a](auto&&... args1) -> auto {
return uses_allocator_construction_args<T1>(
a, std::forward<decltype(args1)>(args1)...);
}, std::forward<Tuple1>(x)),
std::apply([&a](auto&&... args2) -> auto {
return uses_allocator_construction_args<T2>(
a, std::forward<decltype(args2)>(args2)...);
}, std::forward<Tuple2>(y))
);
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles specializations of `T` = `std::pair` for which
// `has_allocator<T, Alloc>` is true for either or both of the elements and
// no other constructor arguments are passed in.
template <class T, class Alloc>
auto uses_allocator_args_imp(std::true_type /* is_pair */,
std::true_type /* has_allocator */,
std::false_type /* prefix allocator arg */,
const Alloc& a)
{
// using T1 = typename T::first_type;
// using T2 = typename T::second_type;
// return std::make_tuple(
// piecewise_construct,
// uses_allocator_construction_args<T1>(a),
// uses_allocator_construction_args<T2>(a));
return uses_allocator_construction_args<T>(a, std::piecewise_construct,
std::tuple<>{}, std::tuple<>{});
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles specializations of `T` = `std::pair` for which
// `has_allocator<T, Alloc>` is true for either or both of the elements and
// a single argument of type const-lvalue-of-pair is passed in.
template <class T, class Alloc, class U1, class U2>
auto uses_allocator_args_imp(std::true_type /* is_pair */,
std::true_type /* has_allocator */,
std::false_type /* prefix allocator arg */,
const Alloc& a,
const std::pair<U1, U2>& arg)
{
// using T1 = typename T::first_type;
// using T2 = typename T::second_type;
// return std::make_tuple(
// piecewise_construct,
// uses_allocator_construction_args<T1>(a, arg.first),
// uses_allocator_construction_args<T2>(a, arg.second));
return uses_allocator_construction_args<T>(a, std::piecewise_construct,
std::forward_as_tuple(arg.first),
std::forward_as_tuple(arg.second));
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles specializations of `T` = `std::pair` for which
// `has_allocator<T, Alloc>` is true for either or both of the elements and
// a single argument of type rvalue-of-pair is passed in.
template <class T, class Alloc, class U1, class U2>
auto uses_allocator_args_imp(std::true_type /* is_pair */,
std::true_type /* has_allocator */,
std::false_type /* prefix allocator arg */,
const Alloc& a,
std::pair<U1, U2>&& arg)
{
// using T1 = typename T::first_type;
// using T2 = typename T::second_type;
// return std::make_tuple(
// piecewise_construct,
// uses_allocator_construction_args<T1>(a, forward<U1>(arg.first)),
// uses_allocator_construction_args<T2>(a, forward<U2>(arg.second)));
return uses_allocator_construction_args<T>(a, std::piecewise_construct,
std::forward_as_tuple(std::forward<U1>(arg.first)),
std::forward_as_tuple(std::forward<U2>(arg.second)));
}
// Return a tuple of arguments appropriate for uses-allocator construction
// with allocator `Alloc` and ctor arguments `Args`.
// This overload handles specializations of `T` = `std::pair` for which
// `has_allocator<T, Alloc>` is true for either or both of the elements and
// two additional constructor arguments are passed in.
template <class T, class Alloc, class U1, class U2>
auto uses_allocator_args_imp(std::true_type /* is_pair */,
std::true_type /* has_allocator */,
std::false_type /* prefix allocator arg */,
const Alloc& a,
U1&& arg1, U2&& arg2)
{
// using T1 = typename T::first_type;
// using T2 = typename T::second_type;
// return std::make_tuple(
// piecewise_construct,
// uses_allocator_construction_args<T1>(a, forward<U1>(arg1)),
// uses_allocator_construction_args<T2>(a, forward<U2>(arg2)));
return uses_allocator_construction_args<T>(
a, std::piecewise_construct,
std::forward_as_tuple(std::forward<U1>(arg1)),
std::forward_as_tuple(std::forward<U2>(arg2)));
}
} // close namespace internal
template <class T, class Alloc, class... Args>
auto uses_allocator_construction_args(const Alloc& a, Args&&... args)
{
using namespace internal;
return uses_allocator_args_imp<T>(is_pair<T>(),
has_allocator<T, Alloc>(),
std::is_constructible<T, std::allocator_arg_t,
Alloc, Args...>(),
a, std::forward<Args>(args)...);
}
template <class T, class Alloc, class... Args>
T make_obj_using_allocator(const Alloc& a, Args&&... args)
{
return make_from_tuple<T>(
uses_allocator_construction_args<T>(a, std::forward<Args>(args)...));
}
template <class T, class Alloc, class... Args>
T* uninitialized_construct_using_allocator(T* p,
const Alloc& a,
Args&&... args)
{
return std::apply([p](auto&&... args2){
return ::new(static_cast<void*>(p))
T(std::forward<decltype(args2)>(args2)...);
}, uses_allocator_construction_args<T>(
a, std::forward<Args>(args)...));
}
} // namespace ceph
| 11,402 | 41.707865 | 98 | h |
null | ceph-main/src/include/util.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2012 Inktank Storage, Inc.
* Copyright (C) 2014 Red Hat <[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_UTIL_H
#define CEPH_UTIL_H
#include "common/Formatter.h"
#include "include/types.h"
std::string bytes2str(uint64_t count);
struct ceph_data_stats
{
uint64_t byte_total;
uint64_t byte_used;
uint64_t byte_avail;
int avail_percent;
ceph_data_stats() :
byte_total(0),
byte_used(0),
byte_avail(0),
avail_percent(0)
{ }
void dump(ceph::Formatter *f) const {
ceph_assert(f != NULL);
f->dump_int("total", byte_total);
f->dump_int("used", byte_used);
f->dump_int("avail", byte_avail);
f->dump_int("avail_percent", avail_percent);
}
void encode(ceph::buffer::list &bl) const {
ENCODE_START(1, 1, bl);
encode(byte_total, bl);
encode(byte_used, bl);
encode(byte_avail, bl);
encode(avail_percent, bl);
ENCODE_FINISH(bl);
}
void decode(ceph::buffer::list::const_iterator &p) {
DECODE_START(1, p);
decode(byte_total, p);
decode(byte_used, p);
decode(byte_avail, p);
decode(avail_percent, p);
DECODE_FINISH(p);
}
static void generate_test_instances(std::list<ceph_data_stats*>& ls) {
ls.push_back(new ceph_data_stats);
ls.push_back(new ceph_data_stats);
ls.back()->byte_total = 1024*1024;
ls.back()->byte_used = 512*1024;
ls.back()->byte_avail = 512*1024;
ls.back()->avail_percent = 50;
}
};
typedef struct ceph_data_stats ceph_data_stats_t;
WRITE_CLASS_ENCODER(ceph_data_stats)
int get_fs_stats(ceph_data_stats_t &stats, const char *path);
/// get memory limit for the current cgroup
int get_cgroup_memory_limit(uint64_t *limit);
/// collect info from @p uname(2), @p /proc/meminfo and @p /proc/cpuinfo
void collect_sys_info(std::map<std::string, std::string> *m, CephContext *cct);
#ifdef _WIN32
/// Retrieve the actual Windows version, regardless of the app manifest.
int get_windows_version(POSVERSIONINFOEXW ver);
#endif
/// dump service ids grouped by their host to the specified formatter
/// @param f formatter for the output
/// @param services a map from hostname to a list of service id hosted by this host
/// @param type the service type of given @p services, for example @p osd or @p mon.
void dump_services(ceph::Formatter* f,
const std::map<std::string, std::list<int> >& services,
const char* type);
/// dump service names grouped by their host to the specified formatter
/// @param f formatter for the output
/// @param services a map from hostname to a list of service name hosted by this host
/// @param type the service type of given @p services, for example @p osd or @p mon.
void dump_services(ceph::Formatter* f, const std::map<std::string,
std::list<std::string> >& services, const char* type);
std::string cleanbin(ceph::buffer::list &bl, bool &b64, bool show = false);
std::string cleanbin(std::string &str);
namespace ceph::util {
// Returns true if s matches any parameters:
template <typename ...XS>
bool match_str(const std::string& s, const XS& ...xs)
{
return ((s == xs) || ...);
}
} // namespace ceph::util
#endif /* CEPH_UTIL_H */
| 3,494 | 29.391304 | 85 | h |
null | ceph-main/src/include/utime.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_UTIME_H
#define CEPH_UTIME_H
#include <math.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#if defined(WITH_SEASTAR)
#include <seastar/core/lowres_clock.hh>
#endif
#include "include/compat.h"
#include "include/types.h"
#include "include/timegm.h"
#include "common/strtol.h"
#include "common/ceph_time.h"
#include "common/safe_io.h"
#include "common/SubProcess.h"
#include "include/denc.h"
// --------
// utime_t
inline __u32 cap_to_u32_max(__u64 t) {
return std::min(t, (__u64)std::numeric_limits<uint32_t>::max());
}
/* WARNING: If add member in utime_t, please make sure the encode/decode function
* work well. For little-endian machine, we should make sure there is no padding
* in 32-bit machine and 64-bit machine.
* You should also modify the padding_check function.
*/
class utime_t {
public:
struct {
__u32 tv_sec, tv_nsec;
} tv;
public:
bool is_zero() const {
return (tv.tv_sec == 0) && (tv.tv_nsec == 0);
}
constexpr void normalize() {
if (tv.tv_nsec > 1000000000ul) {
tv.tv_sec = cap_to_u32_max(tv.tv_sec + tv.tv_nsec / (1000000000ul));
tv.tv_nsec %= 1000000000ul;
}
}
// cons
constexpr utime_t() { tv.tv_sec = 0; tv.tv_nsec = 0; }
constexpr utime_t(time_t s, int n) { tv.tv_sec = s; tv.tv_nsec = n; normalize(); }
constexpr utime_t(const struct ceph_timespec &v) {
decode_timeval(&v);
}
constexpr utime_t(const struct timespec v)
{
// NOTE: this is used by ceph_clock_now() so should be kept
// as thin as possible.
tv.tv_sec = v.tv_sec;
tv.tv_nsec = v.tv_nsec;
}
// conversion from ceph::real_time/coarse_real_time
template <typename Clock, typename std::enable_if_t<
ceph::converts_to_timespec_v<Clock>>* = nullptr>
explicit utime_t(const std::chrono::time_point<Clock>& t)
: utime_t(Clock::to_timespec(t)) {} // forward to timespec ctor
template<class Rep, class Period>
explicit utime_t(const std::chrono::duration<Rep, Period>& dur) {
using common_t = std::common_type_t<Rep, int>;
tv.tv_sec = std::max<common_t>(std::chrono::duration_cast<std::chrono::seconds>(dur).count(), 0);
tv.tv_nsec = std::max<common_t>((std::chrono::duration_cast<std::chrono::nanoseconds>(dur) %
std::chrono::seconds(1)).count(), 0);
}
#if defined(WITH_SEASTAR)
explicit utime_t(const seastar::lowres_system_clock::time_point& t) {
tv.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(
t.time_since_epoch()).count();
tv.tv_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
t.time_since_epoch() % std::chrono::seconds(1)).count();
}
explicit operator seastar::lowres_system_clock::time_point() const noexcept {
using clock_t = seastar::lowres_system_clock;
return clock_t::time_point{std::chrono::duration_cast<clock_t::duration>(
std::chrono::seconds{tv.tv_sec} + std::chrono::nanoseconds{tv.tv_nsec})};
}
#endif
utime_t(const struct timeval &v) {
set_from_timeval(&v);
}
utime_t(const struct timeval *v) {
set_from_timeval(v);
}
void to_timespec(struct timespec *ts) const {
ts->tv_sec = tv.tv_sec;
ts->tv_nsec = tv.tv_nsec;
}
void set_from_double(double d) {
tv.tv_sec = (__u32)trunc(d);
tv.tv_nsec = (__u32)((d - (double)tv.tv_sec) * 1000000000.0);
}
ceph::real_time to_real_time() const {
ceph_timespec ts;
encode_timeval(&ts);
return ceph::real_clock::from_ceph_timespec(ts);
}
// accessors
constexpr time_t sec() const { return tv.tv_sec; }
constexpr long usec() const { return tv.tv_nsec/1000; }
constexpr int nsec() const { return tv.tv_nsec; }
// ref accessors/modifiers
__u32& sec_ref() { return tv.tv_sec; }
__u32& nsec_ref() { return tv.tv_nsec; }
uint64_t to_nsec() const {
return (uint64_t)tv.tv_nsec + (uint64_t)tv.tv_sec * 1000000000ull;
}
uint64_t to_msec() const {
return (uint64_t)tv.tv_nsec / 1000000ull + (uint64_t)tv.tv_sec * 1000ull;
}
void copy_to_timeval(struct timeval *v) const {
v->tv_sec = tv.tv_sec;
v->tv_usec = tv.tv_nsec/1000;
}
void set_from_timeval(const struct timeval *v) {
tv.tv_sec = v->tv_sec;
tv.tv_nsec = v->tv_usec*1000;
}
void padding_check() {
static_assert(
sizeof(utime_t) ==
sizeof(tv.tv_sec) +
sizeof(tv.tv_nsec)
,
"utime_t have padding");
}
void encode(ceph::buffer::list &bl) const {
#if defined(CEPH_LITTLE_ENDIAN)
bl.append((char *)(this), sizeof(__u32) + sizeof(__u32));
#else
using ceph::encode;
encode(tv.tv_sec, bl);
encode(tv.tv_nsec, bl);
#endif
}
void decode(ceph::buffer::list::const_iterator &p) {
#if defined(CEPH_LITTLE_ENDIAN)
p.copy(sizeof(__u32) + sizeof(__u32), (char *)(this));
#else
using ceph::decode;
decode(tv.tv_sec, p);
decode(tv.tv_nsec, p);
#endif
}
DENC(utime_t, v, p) {
denc(v.tv.tv_sec, p);
denc(v.tv.tv_nsec, p);
}
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<utime_t*>& o);
void encode_timeval(struct ceph_timespec *t) const {
t->tv_sec = tv.tv_sec;
t->tv_nsec = tv.tv_nsec;
}
constexpr void decode_timeval(const struct ceph_timespec *t) {
tv.tv_sec = t->tv_sec;
tv.tv_nsec = t->tv_nsec;
}
utime_t round_to_minute() {
struct tm bdt;
time_t tt = sec();
localtime_r(&tt, &bdt);
bdt.tm_sec = 0;
tt = mktime(&bdt);
return utime_t(tt, 0);
}
utime_t round_to_hour() {
struct tm bdt;
time_t tt = sec();
localtime_r(&tt, &bdt);
bdt.tm_sec = 0;
bdt.tm_min = 0;
tt = mktime(&bdt);
return utime_t(tt, 0);
}
utime_t round_to_day() {
struct tm bdt;
time_t tt = sec();
localtime_r(&tt, &bdt);
bdt.tm_sec = 0;
bdt.tm_min = 0;
bdt.tm_hour = 0;
tt = mktime(&bdt);
return utime_t(tt, 0);
}
// cast to double
constexpr operator double() const {
return (double)sec() + ((double)nsec() / 1000000000.0f);
}
operator ceph_timespec() const {
ceph_timespec ts;
ts.tv_sec = sec();
ts.tv_nsec = nsec();
return ts;
}
void sleep() const {
struct timespec ts;
to_timespec(&ts);
nanosleep(&ts, NULL);
}
// output
std::ostream& gmtime(std::ostream& out, bool legacy_form=false) const {
out.setf(std::ios::right);
char oldfill = out.fill();
out.fill('0');
if (sec() < ((time_t)(60*60*24*365*10))) {
// raw seconds. this looks like a relative time.
out << (long)sec() << "." << std::setw(6) << usec();
} else {
// this looks like an absolute time.
// conform to http://en.wikipedia.org/wiki/ISO_8601
struct tm bdt;
time_t tt = sec();
gmtime_r(&tt, &bdt);
out << std::setw(4) << (bdt.tm_year+1900) // 2007 -> '07'
<< '-' << std::setw(2) << (bdt.tm_mon+1)
<< '-' << std::setw(2) << bdt.tm_mday;
if (legacy_form) {
out << ' ';
} else {
out << 'T';
}
out << std::setw(2) << bdt.tm_hour
<< ':' << std::setw(2) << bdt.tm_min
<< ':' << std::setw(2) << bdt.tm_sec;
out << "." << std::setw(6) << usec();
out << "Z";
}
out.fill(oldfill);
out.unsetf(std::ios::right);
return out;
}
// output
std::ostream& gmtime_nsec(std::ostream& out) const {
out.setf(std::ios::right);
char oldfill = out.fill();
out.fill('0');
if (sec() < ((time_t)(60*60*24*365*10))) {
// raw seconds. this looks like a relative time.
out << (long)sec() << "." << std::setw(6) << usec();
} else {
// this looks like an absolute time.
// conform to http://en.wikipedia.org/wiki/ISO_8601
struct tm bdt;
time_t tt = sec();
gmtime_r(&tt, &bdt);
out << 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;
out << "." << std::setw(9) << nsec();
out << "Z";
}
out.fill(oldfill);
out.unsetf(std::ios::right);
return out;
}
// output
std::ostream& asctime(std::ostream& out) const {
out.setf(std::ios::right);
char oldfill = out.fill();
out.fill('0');
if (sec() < ((time_t)(60*60*24*365*10))) {
// raw seconds. this looks like a relative time.
out << (long)sec() << "." << std::setw(6) << usec();
} else {
// this looks like an absolute time.
struct tm bdt;
time_t tt = sec();
gmtime_r(&tt, &bdt);
char buf[128];
asctime_r(&bdt, buf);
int len = strlen(buf);
if (buf[len - 1] == '\n')
buf[len - 1] = '\0';
out << buf;
}
out.fill(oldfill);
out.unsetf(std::ios::right);
return out;
}
std::ostream& localtime(std::ostream& out, bool legacy_form=false) const {
out.setf(std::ios::right);
char oldfill = out.fill();
out.fill('0');
if (sec() < ((time_t)(60*60*24*365*10))) {
// raw seconds. this looks like a relative time.
out << (long)sec() << "." << std::setw(6) << usec();
} else {
// this looks like an absolute time.
// conform to http://en.wikipedia.org/wiki/ISO_8601
struct tm bdt;
time_t tt = sec();
localtime_r(&tt, &bdt);
out << std::setw(4) << (bdt.tm_year+1900) // 2007 -> '07'
<< '-' << std::setw(2) << (bdt.tm_mon+1)
<< '-' << std::setw(2) << bdt.tm_mday;
if (legacy_form) {
out << ' ';
} else {
out << 'T';
}
out << std::setw(2) << bdt.tm_hour
<< ':' << std::setw(2) << bdt.tm_min
<< ':' << std::setw(2) << bdt.tm_sec;
out << "." << std::setw(6) << usec();
if (!legacy_form) {
char buf[32] = { 0 };
strftime(buf, sizeof(buf), "%z", &bdt);
out << buf;
}
}
out.fill(oldfill);
out.unsetf(std::ios::right);
return out;
}
static int invoke_date(const std::string& date_str, utime_t *result) {
char buf[256];
SubProcess bin_date("/bin/date", SubProcess::CLOSE, SubProcess::PIPE,
SubProcess::KEEP);
bin_date.add_cmd_args("-d", date_str.c_str(), "+%s %N", NULL);
int r = bin_date.spawn();
if (r < 0) return r;
ssize_t n = safe_read(bin_date.get_stdout(), buf, sizeof(buf));
r = bin_date.join();
if (r || n <= 0) return -EINVAL;
uint64_t epoch, nsec;
std::istringstream iss(buf);
iss >> epoch;
iss >> nsec;
*result = utime_t(epoch, nsec);
return 0;
}
static int parse_date(const std::string& date, uint64_t *epoch, uint64_t *nsec,
std::string *out_date=nullptr,
std::string *out_time=nullptr) {
struct tm tm;
memset(&tm, 0, sizeof(tm));
if (nsec)
*nsec = 0;
const char *p = strptime(date.c_str(), "%Y-%m-%d", &tm);
if (p) {
if (*p == ' ' || *p == 'T') {
p++;
// strptime doesn't understand fractional/decimal seconds, and
// it also only takes format chars or literals, so we have to
// get creative.
char fmt[32] = {0};
strncpy(fmt, p, sizeof(fmt) - 1);
fmt[0] = '%';
fmt[1] = 'H';
fmt[2] = ':';
fmt[3] = '%';
fmt[4] = 'M';
fmt[6] = '%';
fmt[7] = 'S';
const char *subsec = 0;
char *q = fmt + 8;
if (*q == '.') {
++q;
subsec = p + 9;
q = fmt + 9;
while (*q && isdigit(*q)) {
++q;
}
}
// look for tz...
if (*q == '-' || *q == '+') {
*q = '%';
*(q+1) = 'z';
*(q+2) = 0;
}
p = strptime(p, fmt, &tm);
if (!p) {
return -EINVAL;
}
if (nsec && subsec) {
unsigned i;
char buf[10]; /* 9 digit + null termination */
for (i = 0; (i < sizeof(buf) - 1) && isdigit(*subsec); ++i, ++subsec) {
buf[i] = *subsec;
}
for (; i < sizeof(buf) - 1; ++i) {
buf[i] = '0';
}
buf[i] = '\0';
std::string err;
*nsec = (uint64_t)strict_strtol(buf, 10, &err);
if (!err.empty()) {
return -EINVAL;
}
}
}
} else {
int sec, usec;
int r = sscanf(date.c_str(), "%d.%d", &sec, &usec);
if (r != 2) {
return -EINVAL;
}
time_t tt = sec;
gmtime_r(&tt, &tm);
if (nsec) {
*nsec = (uint64_t)usec * 1000;
}
}
#ifndef _WIN32
// apply the tm_gmtoff manually below, since none of mktime,
// gmtime, and localtime seem to do it. zero it out here just in
// case some other libc *does* apply it. :(
auto gmtoff = tm.tm_gmtoff;
tm.tm_gmtoff = 0;
#else
auto gmtoff = _timezone;
#endif /* _WIN32 */
time_t t = internal_timegm(&tm);
if (epoch)
*epoch = (uint64_t)t;
*epoch -= gmtoff;
if (out_date) {
char buf[32];
strftime(buf, sizeof(buf), "%Y-%m-%d", &tm);
*out_date = buf;
}
if (out_time) {
char buf[32];
strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
*out_time = buf;
}
return 0;
}
bool parse(const std::string& s) {
uint64_t epoch, nsec;
int r = parse_date(s, &epoch, &nsec);
if (r < 0) {
return false;
}
*this = utime_t(epoch, nsec);
return true;
}
};
WRITE_CLASS_ENCODER(utime_t)
WRITE_CLASS_DENC(utime_t)
// arithmetic operators
inline utime_t operator+(const utime_t& l, const utime_t& r) {
__u64 sec = (__u64)l.sec() + r.sec();
return utime_t(cap_to_u32_max(sec), l.nsec() + r.nsec());
}
inline utime_t& operator+=(utime_t& l, const utime_t& r) {
l.sec_ref() = cap_to_u32_max((__u64)l.sec() + r.sec());
l.nsec_ref() += r.nsec();
l.normalize();
return l;
}
inline utime_t& operator+=(utime_t& l, double f) {
double fs = trunc(f);
double ns = (f - fs) * 1000000000.0;
l.sec_ref() = cap_to_u32_max(l.sec() + (__u64)fs);
l.nsec_ref() += (long)ns;
l.normalize();
return l;
}
inline utime_t operator-(const utime_t& l, const utime_t& r) {
return utime_t( l.sec() - r.sec() - (l.nsec()<r.nsec() ? 1:0),
l.nsec() - r.nsec() + (l.nsec()<r.nsec() ? 1000000000:0) );
}
inline utime_t& operator-=(utime_t& l, const utime_t& r) {
l.sec_ref() -= r.sec();
if (l.nsec() >= r.nsec())
l.nsec_ref() -= r.nsec();
else {
l.nsec_ref() += 1000000000L - r.nsec();
l.sec_ref()--;
}
return l;
}
inline utime_t& operator-=(utime_t& l, double f) {
double fs = trunc(f);
double ns = (f - fs) * 1000000000.0;
l.sec_ref() -= (long)fs;
long nsl = (long)ns;
if (nsl) {
l.sec_ref()--;
l.nsec_ref() = 1000000000L + l.nsec_ref() - nsl;
}
l.normalize();
return l;
}
// comparators
inline bool operator>(const utime_t& a, const utime_t& b)
{
return (a.sec() > b.sec()) || (a.sec() == b.sec() && a.nsec() > b.nsec());
}
inline bool operator<=(const utime_t& a, const utime_t& b)
{
return !(operator>(a, b));
}
inline bool operator<(const utime_t& a, const utime_t& b)
{
return (a.sec() < b.sec()) || (a.sec() == b.sec() && a.nsec() < b.nsec());
}
inline bool operator>=(const utime_t& a, const utime_t& b)
{
return !(operator<(a, b));
}
inline bool operator==(const utime_t& a, const utime_t& b)
{
return a.sec() == b.sec() && a.nsec() == b.nsec();
}
inline bool operator!=(const utime_t& a, const utime_t& b)
{
return a.sec() != b.sec() || a.nsec() != b.nsec();
}
// output
// ostream
inline std::ostream& operator<<(std::ostream& out, const utime_t& t)
{
return t.localtime(out);
}
inline std::string utimespan_str(const utime_t& age) {
auto age_ts = ceph::timespan(age.nsec()) + std::chrono::seconds(age.sec());
return ceph::timespan_str(age_ts);
}
#endif
| 16,026 | 25.578773 | 101 | h |
null | ceph-main/src/include/utime_fmt.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
/**
* \file fmtlib formatter for utime_t
*/
#include <fmt/chrono.h>
#include <fmt/format.h>
#include "include/utime.h"
template <>
struct fmt::formatter<utime_t> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
auto it = ctx.begin();
if (it != ctx.end() && *it == 's') {
short_format = true;
++it;
}
return it;
}
template <typename FormatContext>
auto format(const utime_t& utime, FormatContext& ctx)
{
if (utime.sec() < ((time_t)(60 * 60 * 24 * 365 * 10))) {
// raw seconds. this looks like a relative time.
return fmt::format_to(ctx.out(), "{}.{:06}", (long)utime.sec(),
utime.usec());
}
// this looks like an absolute time.
// conform to http://en.wikipedia.org/wiki/ISO_8601
// (unless short_format is set)
auto aslocal = fmt::localtime(utime.sec());
if (short_format) {
return fmt::format_to(ctx.out(), "{:%FT%T}.{:03}", aslocal,
utime.usec() / 1000);
}
return fmt::format_to(ctx.out(), "{:%FT%T}.{:06}{:%z}", aslocal,
utime.usec(), aslocal);
}
bool short_format{false};
};
| 1,245 | 24.958333 | 70 | h |
null | ceph-main/src/include/uuid.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#ifndef _CEPH_UUID_H
#define _CEPH_UUID_H
/*
* Thin C++ wrapper around libuuid.
*/
#include "encoding.h"
#include "random.h"
#include <ostream>
#include <random>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#if FMT_VERSION >= 90000
#include <fmt/ostream.h>
#endif
namespace ceph {
class Formatter;
}
struct uuid_d {
boost::uuids::uuid uuid;
uuid_d() {
boost::uuids::nil_generator gen;
uuid = gen();
}
bool is_zero() const {
return uuid.is_nil();
}
void generate_random() {
random_device_t rng;
boost::uuids::basic_random_generator gen(rng);
uuid = gen();
}
bool parse(const char *s) {
try {
boost::uuids::string_generator gen;
uuid = gen(s);
return true;
} catch (std::runtime_error& e) {
return false;
}
}
void print(char *s) const {
memcpy(s, boost::uuids::to_string(uuid).c_str(), 37);
}
std::string to_string() const {
return boost::uuids::to_string(uuid);
}
const char *bytes() const {
return (const char*)uuid.data;
}
void encode(::ceph::buffer::list::contiguous_appender& p) const {
p.append(reinterpret_cast<const char *>(&uuid), sizeof(uuid));
}
void bound_encode(size_t& p) const {
p += sizeof(uuid);
}
void decode(::ceph::buffer::ptr::const_iterator& p) {
assert((p.get_end() - p.get_pos()) >= (int)sizeof(*this));
memcpy((char *)this, p.get_pos_add(sizeof(*this)), sizeof(*this));
}
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<uuid_d*>& o);
};
WRITE_CLASS_DENC_BOUNDED(uuid_d)
inline std::ostream& operator<<(std::ostream& out, const uuid_d& u) {
char b[37];
u.print(b);
return out << b;
}
inline bool operator==(const uuid_d& l, const uuid_d& r) {
return l.uuid == r.uuid;
}
inline bool operator!=(const uuid_d& l, const uuid_d& r) {
return l.uuid != r.uuid;
}
inline bool operator<(const uuid_d& l, const uuid_d& r) {
return l.to_string() < r.to_string();
}
inline bool operator>(const uuid_d& l, const uuid_d& r) {
return l.to_string() > r.to_string();
}
#if FMT_VERSION >= 90000
template <> struct fmt::formatter<uuid_d> : fmt::ostream_formatter {};
#endif
#endif
| 2,326 | 20.546296 | 70 | h |
null | ceph-main/src/include/xlist.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_XLIST_H
#define CEPH_XLIST_H
#include <iterator>
#include <cstdlib>
#include <ostream>
#include "include/ceph_assert.h"
template<typename T>
class xlist {
public:
class item {
public:
item(T i) : _item(i) {}
~item() {
ceph_assert(!is_on_list());
}
item(const item& other) = delete;
item(item&& other) = delete;
const item& operator= (const item& right) = delete;
item& operator= (item&& right) = delete;
xlist* get_list() { return _list; }
bool is_on_list() const { return _list ? true:false; }
bool remove_myself() {
if (_list) {
_list->remove(this);
ceph_assert(_list == 0);
return true;
} else
return false;
}
void move_to_front() {
ceph_assert(_list);
_list->push_front(this);
}
void move_to_back() {
ceph_assert(_list);
_list->push_back(this);
}
private:
friend xlist;
T _item;
item *_prev = nullptr, *_next = nullptr;
xlist *_list = nullptr;
};
typedef item* value_type;
typedef item* const_reference;
private:
item *_front, *_back;
size_t _size;
public:
xlist(const xlist& other) {
_front = other._front;
_back = other._back;
_size = other._size;
}
xlist() : _front(0), _back(0), _size(0) {}
~xlist() {
ceph_assert(_size == 0);
ceph_assert(_front == 0);
ceph_assert(_back == 0);
}
size_t size() const {
ceph_assert((bool)_front == (bool)_size);
return _size;
}
bool empty() const {
ceph_assert((bool)_front == (bool)_size);
return _front == 0;
}
void clear() {
while (_front)
remove(_front);
ceph_assert((bool)_front == (bool)_size);
}
void push_front(item *i) {
if (i->_list)
i->_list->remove(i);
i->_list = this;
i->_next = _front;
i->_prev = 0;
if (_front)
_front->_prev = i;
else
_back = i;
_front = i;
_size++;
}
void push_back(item *i) {
if (i->_list)
i->_list->remove(i);
i->_list = this;
i->_next = 0;
i->_prev = _back;
if (_back)
_back->_next = i;
else
_front = i;
_back = i;
_size++;
}
void remove(item *i) {
ceph_assert(i->_list == this);
if (i->_prev)
i->_prev->_next = i->_next;
else
_front = i->_next;
if (i->_next)
i->_next->_prev = i->_prev;
else
_back = i->_prev;
_size--;
i->_list = 0;
i->_next = i->_prev = 0;
ceph_assert((bool)_front == (bool)_size);
}
T front() { return static_cast<T>(_front->_item); }
const T front() const { return static_cast<const T>(_front->_item); }
T back() { return static_cast<T>(_back->_item); }
const T back() const { return static_cast<const T>(_back->_item); }
void pop_front() {
ceph_assert(!empty());
remove(_front);
}
void pop_back() {
ceph_assert(!empty());
remove(_back);
}
class iterator {
private:
item *cur;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
iterator(item *i = 0) : cur(i) {}
T operator*() { return static_cast<T>(cur->_item); }
iterator& operator++() {
ceph_assert(cur);
ceph_assert(cur->_list);
cur = cur->_next;
return *this;
}
bool end() const { return cur == 0; }
friend bool operator==(const iterator& lhs, const iterator& rhs) {
return lhs.cur == rhs.cur;
}
friend bool operator!=(const iterator& lhs, const iterator& rhs) {
return lhs.cur != rhs.cur;
}
};
iterator begin() { return iterator(_front); }
iterator end() { return iterator(NULL); }
class const_iterator {
private:
item *cur;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T*;
using reference = const T&;
const_iterator(item *i = 0) : cur(i) {}
const T operator*() { return static_cast<const T>(cur->_item); }
const_iterator& operator++() {
ceph_assert(cur);
ceph_assert(cur->_list);
cur = cur->_next;
return *this;
}
bool end() const { return cur == 0; }
friend bool operator==(const const_iterator& lhs,
const const_iterator& rhs) {
return lhs.cur == rhs.cur;
}
friend bool operator!=(const const_iterator& lhs,
const const_iterator& rhs) {
return lhs.cur != rhs.cur;
}
};
const_iterator begin() const { return const_iterator(_front); }
const_iterator end() const { return const_iterator(NULL); }
friend std::ostream &operator<<(std::ostream &oss, const xlist<T> &list) {
bool first = true;
for (const auto &item : list) {
if (!first) {
oss << ", ";
}
oss << *item; /* item should be a pointer */
first = false;
}
return oss;
}
};
#endif
| 5,427 | 21.806723 | 76 | h |
null | ceph-main/src/include/cephfs/ceph_ll_client.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* scalable distributed file system
*
* Copyright (C) Jeff Layton <[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_CEPH_LL_CLIENT_H
#define CEPH_CEPH_LL_CLIENT_H
#include <stdint.h>
#ifdef _WIN32
#include "include/win32/fs_compat.h"
#endif
#ifdef __cplusplus
extern "C" {
class Fh;
struct inodeno_t;
struct vinodeno_t;
typedef struct vinodeno_t vinodeno;
#else /* __cplusplus */
typedef struct Fh Fh;
typedef struct inodeno_t {
uint64_t val;
} inodeno_t;
typedef struct _snapid_t {
uint64_t val;
} snapid_t;
typedef struct vinodeno_t {
inodeno_t ino;
snapid_t snapid;
} vinodeno_t;
#endif /* __cplusplus */
/*
* Heavily borrowed from David Howells' draft statx patchset.
*
* Since the xstat patches are still a work in progress, we borrow its data
* structures and #defines to implement ceph_getattrx. Once the xstat stuff
* has been merged we should drop this and switch over to using that instead.
*/
struct ceph_statx {
uint32_t stx_mask;
uint32_t stx_blksize;
uint32_t stx_nlink;
uint32_t stx_uid;
uint32_t stx_gid;
uint16_t stx_mode;
uint64_t stx_ino;
uint64_t stx_size;
uint64_t stx_blocks;
dev_t stx_dev;
dev_t stx_rdev;
struct timespec stx_atime;
struct timespec stx_ctime;
struct timespec stx_mtime;
struct timespec stx_btime;
uint64_t stx_version;
};
#define CEPH_STATX_MODE 0x00000001U /* Want/got stx_mode */
#define CEPH_STATX_NLINK 0x00000002U /* Want/got stx_nlink */
#define CEPH_STATX_UID 0x00000004U /* Want/got stx_uid */
#define CEPH_STATX_GID 0x00000008U /* Want/got stx_gid */
#define CEPH_STATX_RDEV 0x00000010U /* Want/got stx_rdev */
#define CEPH_STATX_ATIME 0x00000020U /* Want/got stx_atime */
#define CEPH_STATX_MTIME 0x00000040U /* Want/got stx_mtime */
#define CEPH_STATX_CTIME 0x00000080U /* Want/got stx_ctime */
#define CEPH_STATX_INO 0x00000100U /* Want/got stx_ino */
#define CEPH_STATX_SIZE 0x00000200U /* Want/got stx_size */
#define CEPH_STATX_BLOCKS 0x00000400U /* Want/got stx_blocks */
#define CEPH_STATX_BASIC_STATS 0x000007ffU /* The stuff in the normal stat struct */
#define CEPH_STATX_BTIME 0x00000800U /* Want/got stx_btime */
#define CEPH_STATX_VERSION 0x00001000U /* Want/got stx_version */
#define CEPH_STATX_ALL_STATS 0x00001fffU /* All supported stats */
/*
* Compatibility macros until these defines make their way into glibc
*/
#ifndef AT_STATX_DONT_SYNC
#define AT_STATX_SYNC_TYPE 0x6000
#define AT_STATX_SYNC_AS_STAT 0x0000
#define AT_STATX_FORCE_SYNC 0x2000
#define AT_STATX_DONT_SYNC 0x4000 /* Don't sync attributes with the server */
#endif
/*
* This is deprecated and just for backwards compatibility.
* Please use AT_STATX_DONT_SYNC instead.
*/
#define AT_NO_ATTR_SYNC AT_STATX_DONT_SYNC /* Deprecated */
/*
* The statx interfaces only allow these flags. In order to allow us to add
* others in the future, we disallow setting any that aren't recognized.
*/
#define CEPH_REQ_FLAG_MASK (AT_SYMLINK_NOFOLLOW|AT_STATX_DONT_SYNC)
/* fallocate mode flags */
#ifndef FALLOC_FL_KEEP_SIZE
#define FALLOC_FL_KEEP_SIZE 0x01
#endif
#ifndef FALLOC_FL_PUNCH_HOLE
#define FALLOC_FL_PUNCH_HOLE 0x02
#endif
/** ceph_deleg_cb_t: Delegation recalls
*
* Called when there is an outstanding Delegation and there is conflicting
* access, either locally or via cap activity.
* @fh: open filehandle
* @priv: private info registered when delegation was acquired
*/
typedef void (*ceph_deleg_cb_t)(Fh *fh, void *priv);
/**
* client_ino_callback_t: Inode data/metadata invalidation
*
* Called when the client wants to invalidate the cached data for a range
* in the file.
* @handle: client callback handle
* @ino: vino of inode to be invalidated
* @off: starting offset of content to be invalidated
* @len: length of region to invalidate
*/
typedef void (*client_ino_callback_t)(void *handle, vinodeno_t ino,
int64_t off, int64_t len);
/**
* client_dentry_callback_t: Dentry invalidation
*
* Called when the client wants to purge a dentry from its cache.
* @handle: client callback handle
* @dirino: vino of directory that contains dentry to be invalidate
* @ino: vino of inode attached to dentry to be invalidated
* @name: name of dentry to be invalidated
* @len: length of @name
*/
typedef void (*client_dentry_callback_t)(void *handle, vinodeno_t dirino,
vinodeno_t ino, const char *name,
size_t len);
/**
* client_remount_callback_t: Remount entire fs
*
* Called when the client needs to purge the dentry cache and the application
* doesn't have a way to purge an individual dentry. Mostly used for ceph-fuse
* on older kernels.
* @handle: client callback handle
*/
typedef int (*client_remount_callback_t)(void *handle);
/**
* client_switch_interrupt_callback_t: Lock request interrupted
*
* Called before file lock request to set the interrupt handler while waiting
* After the wait, called with "data" set to NULL pointer.
* @handle: client callback handle
* @data: opaque data passed to interrupt before call, NULL pointer after.
*/
typedef void (*client_switch_interrupt_callback_t)(void *handle, void *data);
/**
* client_umask_callback_t: Fetch umask of actor
*
* Called when the client needs the umask of the requestor.
* @handle: client callback handle
*/
typedef mode_t (*client_umask_callback_t)(void *handle);
/**
* client_ino_release_t: Request that application release Inode references
*
* Called when the MDS wants to trim caps and Inode records.
* @handle: client callback handle
* @ino: vino of Inode being released
*/
typedef void (*client_ino_release_t)(void *handle, vinodeno_t ino);
/*
* The handle is an opaque value that gets passed to some callbacks. Any fields
* set to NULL will be left alone. There is no way to unregister callbacks.
*/
struct ceph_client_callback_args {
void *handle;
client_ino_callback_t ino_cb;
client_dentry_callback_t dentry_cb;
client_switch_interrupt_callback_t switch_intr_cb;
client_remount_callback_t remount_cb;
client_umask_callback_t umask_cb;
client_ino_release_t ino_release_cb;
};
#ifdef __cplusplus
}
#endif
#endif /* CEPH_STATX_H */
| 6,463 | 28.925926 | 88 | h |
null | ceph-main/src/include/cephfs/metrics/Types.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_INCLUDE_CEPHFS_METRICS_TYPES_H
#define CEPH_INCLUDE_CEPHFS_METRICS_TYPES_H
#include <string>
#include <boost/variant.hpp>
#include "common/Formatter.h"
#include "include/buffer_fwd.h"
#include "include/encoding.h"
#include "include/int_types.h"
#include "include/stringify.h"
#include "include/utime.h"
namespace ceph { class Formatter; }
enum ClientMetricType {
CLIENT_METRIC_TYPE_CAP_INFO,
CLIENT_METRIC_TYPE_READ_LATENCY,
CLIENT_METRIC_TYPE_WRITE_LATENCY,
CLIENT_METRIC_TYPE_METADATA_LATENCY,
CLIENT_METRIC_TYPE_DENTRY_LEASE,
CLIENT_METRIC_TYPE_OPENED_FILES,
CLIENT_METRIC_TYPE_PINNED_ICAPS,
CLIENT_METRIC_TYPE_OPENED_INODES,
CLIENT_METRIC_TYPE_READ_IO_SIZES,
CLIENT_METRIC_TYPE_WRITE_IO_SIZES,
CLIENT_METRIC_TYPE_AVG_READ_LATENCY,
CLIENT_METRIC_TYPE_STDEV_READ_LATENCY,
CLIENT_METRIC_TYPE_AVG_WRITE_LATENCY,
CLIENT_METRIC_TYPE_STDEV_WRITE_LATENCY,
CLIENT_METRIC_TYPE_AVG_METADATA_LATENCY,
CLIENT_METRIC_TYPE_STDEV_METADATA_LATENCY,
};
inline std::ostream &operator<<(std::ostream &os, const ClientMetricType &type) {
switch(type) {
case ClientMetricType::CLIENT_METRIC_TYPE_CAP_INFO:
os << "CAP_INFO";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_READ_LATENCY:
os << "READ_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_WRITE_LATENCY:
os << "WRITE_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_METADATA_LATENCY:
os << "METADATA_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_DENTRY_LEASE:
os << "DENTRY_LEASE";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_OPENED_FILES:
os << "OPENED_FILES";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_PINNED_ICAPS:
os << "PINNED_ICAPS";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_OPENED_INODES:
os << "OPENED_INODES";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_READ_IO_SIZES:
os << "READ_IO_SIZES";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_WRITE_IO_SIZES:
os << "WRITE_IO_SIZES";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_AVG_READ_LATENCY:
os << "AVG_READ_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_STDEV_READ_LATENCY:
os << "STDEV_READ_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_AVG_WRITE_LATENCY:
os << "AVG_WRITE_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_STDEV_WRITE_LATENCY:
os << "STDEV_WRITE_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_AVG_METADATA_LATENCY:
os << "AVG_METADATA_LATENCY";
break;
case ClientMetricType::CLIENT_METRIC_TYPE_STDEV_METADATA_LATENCY:
os << "STDEV_METADATA_LATENCY";
break;
default:
os << "(UNKNOWN:" << static_cast<std::underlying_type<ClientMetricType>::type>(type) << ")";
break;
}
return os;
}
struct ClientMetricPayloadBase {
ClientMetricPayloadBase(ClientMetricType type) : metric_type(type) {}
ClientMetricType get_type() const {
return metric_type;
}
void print_type(std::ostream *out) const {
*out << metric_type;
}
private:
ClientMetricType metric_type;
};
struct CapInfoPayload : public ClientMetricPayloadBase {
uint64_t cap_hits = 0;
uint64_t cap_misses = 0;
uint64_t nr_caps = 0;
CapInfoPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_CAP_INFO) { }
CapInfoPayload(uint64_t cap_hits, uint64_t cap_misses, uint64_t nr_caps)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_CAP_INFO),
cap_hits(cap_hits), cap_misses(cap_misses), nr_caps(nr_caps) {
}
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(cap_hits, bl);
encode(cap_misses, bl);
encode(nr_caps, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(cap_hits, iter);
decode(cap_misses, iter);
decode(nr_caps, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("cap_hits", cap_hits);
f->dump_int("cap_misses", cap_misses);
f->dump_int("num_caps", nr_caps);
}
void print(std::ostream *out) const {
*out << "cap_hits: " << cap_hits << " "
<< "cap_misses: " << cap_misses << " "
<< "num_caps: " << nr_caps;
}
};
struct ReadLatencyPayload : public ClientMetricPayloadBase {
utime_t lat;
utime_t mean;
uint64_t sq_sum; // sum of squares
uint64_t count; // IO count
ReadLatencyPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_READ_LATENCY) { }
ReadLatencyPayload(utime_t lat, utime_t mean, uint64_t sq_sum, uint64_t count)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_READ_LATENCY),
lat(lat),
mean(mean),
sq_sum(sq_sum),
count(count) {
}
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(2, 1, bl);
encode(lat, bl);
encode(mean, bl);
encode(sq_sum, bl);
encode(count, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(2, iter);
decode(lat, iter);
if (struct_v >= 2) {
decode(mean, iter);
decode(sq_sum, iter);
decode(count, iter);
}
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("latency", lat);
f->dump_int("avg_latency", mean);
f->dump_unsigned("sq_sum", sq_sum);
f->dump_unsigned("count", count);
}
void print(std::ostream *out) const {
*out << "latency: " << lat << ", avg_latency: " << mean
<< ", sq_sum: " << sq_sum << ", count=" << count;
}
};
struct WriteLatencyPayload : public ClientMetricPayloadBase {
utime_t lat;
utime_t mean;
uint64_t sq_sum; // sum of squares
uint64_t count; // IO count
WriteLatencyPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_WRITE_LATENCY) { }
WriteLatencyPayload(utime_t lat, utime_t mean, uint64_t sq_sum, uint64_t count)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_WRITE_LATENCY),
lat(lat),
mean(mean),
sq_sum(sq_sum),
count(count){
}
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(2, 1, bl);
encode(lat, bl);
encode(mean, bl);
encode(sq_sum, bl);
encode(count, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(2, iter);
decode(lat, iter);
if (struct_v >= 2) {
decode(mean, iter);
decode(sq_sum, iter);
decode(count, iter);
}
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("latency", lat);
f->dump_int("avg_latency", mean);
f->dump_unsigned("sq_sum", sq_sum);
f->dump_unsigned("count", count);
}
void print(std::ostream *out) const {
*out << "latency: " << lat << ", avg_latency: " << mean
<< ", sq_sum: " << sq_sum << ", count=" << count;
}
};
struct MetadataLatencyPayload : public ClientMetricPayloadBase {
utime_t lat;
utime_t mean;
uint64_t sq_sum; // sum of squares
uint64_t count; // IO count
MetadataLatencyPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_METADATA_LATENCY) { }
MetadataLatencyPayload(utime_t lat, utime_t mean, uint64_t sq_sum, uint64_t count)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_METADATA_LATENCY),
lat(lat),
mean(mean),
sq_sum(sq_sum),
count(count) {
}
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(2, 1, bl);
encode(lat, bl);
encode(mean, bl);
encode(sq_sum, bl);
encode(count, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(2, iter);
decode(lat, iter);
if (struct_v >= 2) {
decode(mean, iter);
decode(sq_sum, iter);
decode(count, iter);
}
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("latency", lat);
f->dump_int("avg_latency", mean);
f->dump_unsigned("sq_sum", sq_sum);
f->dump_unsigned("count", count);
}
void print(std::ostream *out) const {
*out << "latency: " << lat << ", avg_latency: " << mean
<< ", sq_sum: " << sq_sum << ", count=" << count;
}
};
struct DentryLeasePayload : public ClientMetricPayloadBase {
uint64_t dlease_hits = 0;
uint64_t dlease_misses = 0;
uint64_t nr_dentries = 0;
DentryLeasePayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_DENTRY_LEASE) { }
DentryLeasePayload(uint64_t dlease_hits, uint64_t dlease_misses, uint64_t nr_dentries)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_DENTRY_LEASE),
dlease_hits(dlease_hits), dlease_misses(dlease_misses), nr_dentries(nr_dentries) { }
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(dlease_hits, bl);
encode(dlease_misses, bl);
encode(nr_dentries, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(dlease_hits, iter);
decode(dlease_misses, iter);
decode(nr_dentries, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("dlease_hits", dlease_hits);
f->dump_int("dlease_misses", dlease_misses);
f->dump_int("num_dentries", nr_dentries);
}
void print(std::ostream *out) const {
*out << "dlease_hits: " << dlease_hits << " "
<< "dlease_misses: " << dlease_misses << " "
<< "num_dentries: " << nr_dentries;
}
};
struct OpenedFilesPayload : public ClientMetricPayloadBase {
uint64_t opened_files = 0;
uint64_t total_inodes = 0;
OpenedFilesPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_OPENED_FILES) { }
OpenedFilesPayload(uint64_t opened_files, uint64_t total_inodes)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_OPENED_FILES),
opened_files(opened_files), total_inodes(total_inodes) { }
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(opened_files, bl);
encode(total_inodes, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(opened_files, iter);
decode(total_inodes, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("opened_files", opened_files);
f->dump_int("total_inodes", total_inodes);
}
void print(std::ostream *out) const {
*out << "opened_files: " << opened_files << " "
<< "total_inodes: " << total_inodes;
}
};
struct PinnedIcapsPayload : public ClientMetricPayloadBase {
uint64_t pinned_icaps = 0;
uint64_t total_inodes = 0;
PinnedIcapsPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_PINNED_ICAPS) { }
PinnedIcapsPayload(uint64_t pinned_icaps, uint64_t total_inodes)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_PINNED_ICAPS),
pinned_icaps(pinned_icaps), total_inodes(total_inodes) { }
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(pinned_icaps, bl);
encode(total_inodes, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(pinned_icaps, iter);
decode(total_inodes, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("pinned_icaps", pinned_icaps);
f->dump_int("total_inodes", total_inodes);
}
void print(std::ostream *out) const {
*out << "pinned_icaps: " << pinned_icaps << " "
<< "total_inodes: " << total_inodes;
}
};
struct OpenedInodesPayload : public ClientMetricPayloadBase {
uint64_t opened_inodes = 0;
uint64_t total_inodes = 0;
OpenedInodesPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_OPENED_INODES) { }
OpenedInodesPayload(uint64_t opened_inodes, uint64_t total_inodes)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_OPENED_INODES),
opened_inodes(opened_inodes), total_inodes(total_inodes) { }
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(opened_inodes, bl);
encode(total_inodes, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(opened_inodes, iter);
decode(total_inodes, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("opened_inodes", opened_inodes);
f->dump_int("total_inodes", total_inodes);
}
void print(std::ostream *out) const {
*out << "opened_inodes: " << opened_inodes << " "
<< "total_inodes: " << total_inodes;
}
};
struct ReadIoSizesPayload : public ClientMetricPayloadBase {
uint64_t total_ops = 0;
uint64_t total_size = 0;
ReadIoSizesPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_READ_IO_SIZES) { }
ReadIoSizesPayload(uint64_t total_ops, uint64_t total_size)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_READ_IO_SIZES),
total_ops(total_ops), total_size(total_size) { }
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(total_ops, bl);
encode(total_size, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(total_ops, iter);
decode(total_size, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("total_ops", total_ops);
f->dump_int("total_size", total_size);
}
void print(std::ostream *out) const {
*out << "total_ops: " << total_ops << " total_size: " << total_size;
}
};
struct WriteIoSizesPayload : public ClientMetricPayloadBase {
uint64_t total_ops = 0;
uint64_t total_size = 0;
WriteIoSizesPayload()
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_WRITE_IO_SIZES) { }
WriteIoSizesPayload(uint64_t total_ops, uint64_t total_size)
: ClientMetricPayloadBase(ClientMetricType::CLIENT_METRIC_TYPE_WRITE_IO_SIZES),
total_ops(total_ops), total_size(total_size) {
}
void encode(bufferlist &bl) const {
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(total_ops, bl);
encode(total_size, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(1, iter);
decode(total_ops, iter);
decode(total_size, iter);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
f->dump_int("total_ops", total_ops);
f->dump_int("total_size", total_size);
}
void print(std::ostream *out) const {
*out << "total_ops: " << total_ops << " total_size: " << total_size;
}
};
struct UnknownPayload : public ClientMetricPayloadBase {
UnknownPayload()
: ClientMetricPayloadBase(static_cast<ClientMetricType>(-1)) { }
UnknownPayload(ClientMetricType metric_type)
: ClientMetricPayloadBase(metric_type) { }
void encode(bufferlist &bl) const {
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
DECODE_START(254, iter);
iter.seek(struct_len);
DECODE_FINISH(iter);
}
void dump(Formatter *f) const {
}
void print(std::ostream *out) const {
}
};
typedef boost::variant<CapInfoPayload,
ReadLatencyPayload,
WriteLatencyPayload,
MetadataLatencyPayload,
DentryLeasePayload,
OpenedFilesPayload,
PinnedIcapsPayload,
OpenedInodesPayload,
ReadIoSizesPayload,
WriteIoSizesPayload,
UnknownPayload> ClientMetricPayload;
// metric update message sent by clients
struct ClientMetricMessage {
public:
ClientMetricMessage(const ClientMetricPayload &payload = UnknownPayload())
: payload(payload) {
}
class EncodePayloadVisitor : public boost::static_visitor<void> {
public:
explicit EncodePayloadVisitor(bufferlist &bl) : m_bl(bl) {
}
template <typename ClientMetricPayload>
inline void operator()(const ClientMetricPayload &payload) const {
using ceph::encode;
encode(static_cast<uint32_t>(payload.get_type()), m_bl);
payload.encode(m_bl);
}
private:
bufferlist &m_bl;
};
class DecodePayloadVisitor : public boost::static_visitor<void> {
public:
DecodePayloadVisitor(bufferlist::const_iterator &iter) : m_iter(iter) {
}
template <typename ClientMetricPayload>
inline void operator()(ClientMetricPayload &payload) const {
using ceph::decode;
payload.decode(m_iter);
}
private:
bufferlist::const_iterator &m_iter;
};
class DumpPayloadVisitor : public boost::static_visitor<void> {
public:
explicit DumpPayloadVisitor(Formatter *formatter) : m_formatter(formatter) {
}
template <typename ClientMetricPayload>
inline void operator()(const ClientMetricPayload &payload) const {
m_formatter->dump_string("client_metric_type", stringify(payload.get_type()));
payload.dump(m_formatter);
}
private:
Formatter *m_formatter;
};
class PrintPayloadVisitor : public boost::static_visitor<void> {
public:
explicit PrintPayloadVisitor(std::ostream *out) : _out(out) {
}
template <typename ClientMetricPayload>
inline void operator()(const ClientMetricPayload &payload) const {
*_out << "[client_metric_type: ";
payload.print_type(_out);
*_out << " ";
payload.print(_out);
*_out << "]";
}
private:
std::ostream *_out;
};
void encode(bufferlist &bl) const {
boost::apply_visitor(EncodePayloadVisitor(bl), payload);
}
void decode(bufferlist::const_iterator &iter) {
using ceph::decode;
uint32_t metric_type;
decode(metric_type, iter);
switch (metric_type) {
case ClientMetricType::CLIENT_METRIC_TYPE_CAP_INFO:
payload = CapInfoPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_READ_LATENCY:
payload = ReadLatencyPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_WRITE_LATENCY:
payload = WriteLatencyPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_METADATA_LATENCY:
payload = MetadataLatencyPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_DENTRY_LEASE:
payload = DentryLeasePayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_OPENED_FILES:
payload = OpenedFilesPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_PINNED_ICAPS:
payload = PinnedIcapsPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_OPENED_INODES:
payload = OpenedInodesPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_READ_IO_SIZES:
payload = ReadIoSizesPayload();
break;
case ClientMetricType::CLIENT_METRIC_TYPE_WRITE_IO_SIZES:
payload = WriteIoSizesPayload();
break;
default:
payload = UnknownPayload(static_cast<ClientMetricType>(metric_type));
break;
}
boost::apply_visitor(DecodePayloadVisitor(iter), payload);
}
void dump(Formatter *f) const {
apply_visitor(DumpPayloadVisitor(f), payload);
}
void print(std::ostream *out) const {
apply_visitor(PrintPayloadVisitor(out), payload);
}
ClientMetricPayload payload;
};
WRITE_CLASS_ENCODER(ClientMetricMessage);
#endif // CEPH_INCLUDE_CEPHFS_METRICS_TYPES_H
| 19,934 | 27.478571 | 96 | h |
null | ceph-main/src/include/cpp-btree/btree_container.h | // Copyright 2018 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
#pragma once
#include <algorithm>
#include <initializer_list>
#include <iterator>
#include <type_traits>
#include <utility>
#include "btree.h"
namespace btree::internal {
// A common base class for btree_set, btree_map, btree_multiset, and
// btree_multimap.
template <typename Tree>
class btree_container {
using params_type = typename Tree::params_type;
protected:
// Alias used for heterogeneous lookup functions.
// `key_arg<K>` evaluates to `K` when the functors are transparent and to
// `key_type` otherwise. It permits template argument deduction on `K` for the
// transparent case.
template <class Compare>
using is_transparent_t = typename Compare::is_transparent;
template <class K>
using key_arg =
std::conditional_t<
std::experimental::is_detected_v<is_transparent_t, typename Tree::key_compare>,
K,
typename Tree::key_type>;
public:
using key_type = typename Tree::key_type;
using value_type = typename Tree::value_type;
using size_type = typename Tree::size_type;
using difference_type = typename Tree::difference_type;
using key_compare = typename Tree::key_compare;
using value_compare = typename Tree::value_compare;
using allocator_type = typename Tree::allocator_type;
using reference = typename Tree::reference;
using const_reference = typename Tree::const_reference;
using pointer = typename Tree::pointer;
using const_pointer = typename Tree::const_pointer;
using iterator = typename Tree::iterator;
using const_iterator = typename Tree::const_iterator;
using reverse_iterator = typename Tree::reverse_iterator;
using const_reverse_iterator = typename Tree::const_reverse_iterator;
// Constructors/assignments.
btree_container() : tree_(key_compare(), allocator_type()) {}
explicit btree_container(const key_compare &comp,
const allocator_type &alloc = allocator_type())
: tree_(comp, alloc) {}
btree_container(const btree_container &x) = default;
btree_container(btree_container &&x) noexcept = default;
btree_container &operator=(const btree_container &x) = default;
btree_container &operator=(btree_container &&x) noexcept(
std::is_nothrow_move_assignable<Tree>::value) = default;
// Iterator routines.
iterator begin() { return tree_.begin(); }
const_iterator begin() const { return tree_.begin(); }
const_iterator cbegin() const { return tree_.begin(); }
iterator end() { return tree_.end(); }
const_iterator end() const { return tree_.end(); }
const_iterator cend() const { return tree_.end(); }
reverse_iterator rbegin() { return tree_.rbegin(); }
const_reverse_iterator rbegin() const { return tree_.rbegin(); }
const_reverse_iterator crbegin() const { return tree_.rbegin(); }
reverse_iterator rend() { return tree_.rend(); }
const_reverse_iterator rend() const { return tree_.rend(); }
const_reverse_iterator crend() const { return tree_.rend(); }
// Lookup routines.
template <typename K = key_type>
iterator find(const key_arg<K> &key) {
return tree_.find(key);
}
template <typename K = key_type>
const_iterator find(const key_arg<K> &key) const {
return tree_.find(key);
}
template <typename K = key_type>
bool contains(const key_arg<K> &key) const {
return find(key) != end();
}
template <typename K = key_type>
iterator lower_bound(const key_arg<K> &key) {
return tree_.lower_bound(key);
}
template <typename K = key_type>
const_iterator lower_bound(const key_arg<K> &key) const {
return tree_.lower_bound(key);
}
template <typename K = key_type>
iterator upper_bound(const key_arg<K> &key) {
return tree_.upper_bound(key);
}
template <typename K = key_type>
const_iterator upper_bound(const key_arg<K> &key) const {
return tree_.upper_bound(key);
}
template <typename K = key_type>
std::pair<iterator, iterator> equal_range(const key_arg<K> &key) {
return tree_.equal_range(key);
}
template <typename K = key_type>
std::pair<const_iterator, const_iterator> equal_range(
const key_arg<K> &key) const {
return tree_.equal_range(key);
}
// Deletion routines. Note that there is also a deletion routine that is
// specific to btree_set_container/btree_multiset_container.
// Erase the specified iterator from the btree. The iterator must be valid
// (i.e. not equal to end()). Return an iterator pointing to the node after
// the one that was erased (or end() if none exists).
iterator erase(const_iterator iter) { return tree_.erase(iterator(iter)); }
iterator erase(iterator iter) { return tree_.erase(iter); }
iterator erase(const_iterator first, const_iterator last) {
return tree_.erase(iterator(first), iterator(last)).second;
}
public:
// Utility routines.
void clear() { tree_.clear(); }
void swap(btree_container &x) { tree_.swap(x.tree_); }
void verify() const { tree_.verify(); }
// Size routines.
size_type size() const { return tree_.size(); }
size_type max_size() const { return tree_.max_size(); }
bool empty() const { return tree_.empty(); }
friend bool operator==(const btree_container &x, const btree_container &y) {
if (x.size() != y.size()) return false;
return std::equal(x.begin(), x.end(), y.begin());
}
friend bool operator!=(const btree_container &x, const btree_container &y) {
return !(x == y);
}
friend bool operator<(const btree_container &x, const btree_container &y) {
return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}
friend bool operator>(const btree_container &x, const btree_container &y) {
return y < x;
}
friend bool operator<=(const btree_container &x, const btree_container &y) {
return !(y < x);
}
friend bool operator>=(const btree_container &x, const btree_container &y) {
return !(x < y);
}
// The allocator used by the btree.
allocator_type get_allocator() const { return tree_.get_allocator(); }
// The key comparator used by the btree.
key_compare key_comp() const { return tree_.key_comp(); }
value_compare value_comp() const { return tree_.value_comp(); }
protected:
Tree tree_;
};
// A common base class for btree_set and btree_map.
template <typename Tree>
class btree_set_container : public btree_container<Tree> {
using super_type = btree_container<Tree>;
using params_type = typename Tree::params_type;
using init_type = typename params_type::init_type;
using is_key_compare_to = typename params_type::is_key_compare_to;
friend class BtreeNodePeer;
protected:
template <class K>
using key_arg = typename super_type::template key_arg<K>;
public:
using key_type = typename Tree::key_type;
using value_type = typename Tree::value_type;
using size_type = typename Tree::size_type;
using key_compare = typename Tree::key_compare;
using allocator_type = typename Tree::allocator_type;
using iterator = typename Tree::iterator;
using const_iterator = typename Tree::const_iterator;
// Inherit constructors.
using super_type::super_type;
btree_set_container() {}
// Range constructor.
template <class InputIterator>
btree_set_container(InputIterator b, InputIterator e,
const key_compare &comp = key_compare(),
const allocator_type &alloc = allocator_type())
: super_type(comp, alloc) {
insert(b, e);
}
// Initializer list constructor.
btree_set_container(std::initializer_list<init_type> init,
const key_compare &comp = key_compare(),
const allocator_type &alloc = allocator_type())
: btree_set_container(init.begin(), init.end(), comp, alloc) {}
// Lookup routines.
template <typename K = key_type>
size_type count(const key_arg<K> &key) const {
return this->tree_.count_unique(key);
}
// Insertion routines.
std::pair<iterator, bool> insert(const value_type &x) {
return this->tree_.insert_unique(params_type::key(x), x);
}
std::pair<iterator, bool> insert(value_type &&x) {
return this->tree_.insert_unique(params_type::key(x), std::move(x));
}
template <typename... Args>
std::pair<iterator, bool> emplace(Args &&... args) {
init_type v(std::forward<Args>(args)...);
return this->tree_.insert_unique(params_type::key(v), std::move(v));
}
iterator insert(const_iterator position, const value_type &x) {
return this->tree_
.insert_hint_unique(iterator(position), params_type::key(x), x)
.first;
}
iterator insert(const_iterator position, value_type &&x) {
return this->tree_
.insert_hint_unique(iterator(position), params_type::key(x),
std::move(x))
.first;
}
template <typename... Args>
iterator emplace_hint(const_iterator position, Args &&... args) {
init_type v(std::forward<Args>(args)...);
return this->tree_
.insert_hint_unique(iterator(position), params_type::key(v),
std::move(v))
.first;
}
template <typename InputIterator>
void insert(InputIterator b, InputIterator e) {
this->tree_.insert_iterator_unique(b, e);
}
void insert(std::initializer_list<init_type> init) {
this->tree_.insert_iterator_unique(init.begin(), init.end());
}
// Deletion routines.
template <typename K = key_type>
size_type erase(const key_arg<K> &key) {
return this->tree_.erase_unique(key);
}
using super_type::erase;
// Merge routines.
// Moves elements from `src` into `this`. If the element already exists in
// `this`, it is left unmodified in `src`.
template <
typename T,
typename std::enable_if_t<
std::conjunction_v<
std::is_same<value_type, typename T::value_type>,
std::is_same<allocator_type, typename T::allocator_type>,
std::is_same<typename params_type::is_map_container,
typename T::params_type::is_map_container>>,
int> = 0>
void merge(btree_container<T> &src) { // NOLINT
for (auto src_it = src.begin(); src_it != src.end();) {
if (insert(std::move(*src_it)).second) {
src_it = src.erase(src_it);
} else {
++src_it;
}
}
}
template <
typename T,
typename std::enable_if_t<
std::conjunction_v<
std::is_same<value_type, typename T::value_type>,
std::is_same<allocator_type, typename T::allocator_type>,
std::is_same<typename params_type::is_map_container,
typename T::params_type::is_map_container>>,
int> = 0>
void merge(btree_container<T> &&src) {
merge(src);
}
};
// A common base class for btree_map and safe_btree_map.
// Base class for btree_map.
template <typename Tree>
class btree_map_container : public btree_set_container<Tree> {
using super_type = btree_set_container<Tree>;
using params_type = typename Tree::params_type;
protected:
template <class K>
using key_arg = typename super_type::template key_arg<K>;
public:
using key_type = typename Tree::key_type;
using mapped_type = typename params_type::mapped_type;
using value_type = typename Tree::value_type;
using key_compare = typename Tree::key_compare;
using allocator_type = typename Tree::allocator_type;
using iterator = typename Tree::iterator;
using const_iterator = typename Tree::const_iterator;
// Inherit constructors.
using super_type::super_type;
btree_map_container() {}
// Insertion routines.
template <typename... Args>
std::pair<iterator, bool> try_emplace(const key_type &k, Args &&... args) {
return this->tree_.insert_unique(
k, std::piecewise_construct, std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...));
}
template <typename... Args>
std::pair<iterator, bool> try_emplace(key_type &&k, Args &&... args) {
// Note: `key_ref` exists to avoid a ClangTidy warning about moving from `k`
// and then using `k` unsequenced. This is safe because the move is into a
// forwarding reference and insert_unique guarantees that `key` is never
// referenced after consuming `args`.
const key_type& key_ref = k;
return this->tree_.insert_unique(
key_ref, std::piecewise_construct, std::forward_as_tuple(std::move(k)),
std::forward_as_tuple(std::forward<Args>(args)...));
}
template <typename... Args>
iterator try_emplace(const_iterator hint, const key_type &k,
Args &&... args) {
return this->tree_
.insert_hint_unique(iterator(hint), k, std::piecewise_construct,
std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...))
.first;
}
template <typename... Args>
iterator try_emplace(const_iterator hint, key_type &&k, Args &&... args) {
// Note: `key_ref` exists to avoid a ClangTidy warning about moving from `k`
// and then using `k` unsequenced. This is safe because the move is into a
// forwarding reference and insert_hint_unique guarantees that `key` is
// never referenced after consuming `args`.
const key_type& key_ref = k;
return this->tree_
.insert_hint_unique(iterator(hint), key_ref, std::piecewise_construct,
std::forward_as_tuple(std::move(k)),
std::forward_as_tuple(std::forward<Args>(args)...))
.first;
}
mapped_type &operator[](const key_type &k) {
return try_emplace(k).first->second;
}
mapped_type &operator[](key_type &&k) {
return try_emplace(std::move(k)).first->second;
}
template <typename K = key_type>
mapped_type &at(const key_arg<K> &key) {
auto it = this->find(key);
if (it == this->end())
throw std::out_of_range("btree_map::at");
return it->second;
}
template <typename K = key_type>
const mapped_type &at(const key_arg<K> &key) const {
auto it = this->find(key);
if (it == this->end())
throw std::out_of_range("btree_map::at");
return it->second;
}
};
// A common base class for btree_multiset and btree_multimap.
template <typename Tree>
class btree_multiset_container : public btree_container<Tree> {
using super_type = btree_container<Tree>;
using params_type = typename Tree::params_type;
using init_type = typename params_type::init_type;
using is_key_compare_to = typename params_type::is_key_compare_to;
template <class K>
using key_arg = typename super_type::template key_arg<K>;
public:
using key_type = typename Tree::key_type;
using value_type = typename Tree::value_type;
using size_type = typename Tree::size_type;
using key_compare = typename Tree::key_compare;
using allocator_type = typename Tree::allocator_type;
using iterator = typename Tree::iterator;
using const_iterator = typename Tree::const_iterator;
// Inherit constructors.
using super_type::super_type;
btree_multiset_container() {}
// Range constructor.
template <class InputIterator>
btree_multiset_container(InputIterator b, InputIterator e,
const key_compare &comp = key_compare(),
const allocator_type &alloc = allocator_type())
: super_type(comp, alloc) {
insert(b, e);
}
// Initializer list constructor.
btree_multiset_container(std::initializer_list<init_type> init,
const key_compare &comp = key_compare(),
const allocator_type &alloc = allocator_type())
: btree_multiset_container(init.begin(), init.end(), comp, alloc) {}
// Lookup routines.
template <typename K = key_type>
size_type count(const key_arg<K> &key) const {
return this->tree_.count_multi(key);
}
// Insertion routines.
iterator insert(const value_type &x) { return this->tree_.insert_multi(x); }
iterator insert(value_type &&x) {
return this->tree_.insert_multi(std::move(x));
}
iterator insert(const_iterator position, const value_type &x) {
return this->tree_.insert_hint_multi(iterator(position), x);
}
iterator insert(const_iterator position, value_type &&x) {
return this->tree_.insert_hint_multi(iterator(position), std::move(x));
}
template <typename InputIterator>
void insert(InputIterator b, InputIterator e) {
this->tree_.insert_iterator_multi(b, e);
}
void insert(std::initializer_list<init_type> init) {
this->tree_.insert_iterator_multi(init.begin(), init.end());
}
template <typename... Args>
iterator emplace(Args &&... args) {
return this->tree_.insert_multi(init_type(std::forward<Args>(args)...));
}
template <typename... Args>
iterator emplace_hint(const_iterator position, Args &&... args) {
return this->tree_.insert_hint_multi(
iterator(position), init_type(std::forward<Args>(args)...));
}
// Deletion routines.
template <typename K = key_type>
size_type erase(const key_arg<K> &key) {
return this->tree_.erase_multi(key);
}
using super_type::erase;
// Merge routines.
// Moves all elements from `src` into `this`.
template <
typename T,
typename std::enable_if_t<
std::conjunction_v<
std::is_same<value_type, typename T::value_type>,
std::is_same<allocator_type, typename T::allocator_type>,
std::is_same<typename params_type::is_map_container,
typename T::params_type::is_map_container>>,
int> = 0>
void merge(btree_container<T> &src) { // NOLINT
insert(std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end()));
src.clear();
}
template <
typename T,
typename std::enable_if_t<
std::conjunction_v<
std::is_same<value_type, typename T::value_type>,
std::is_same<allocator_type, typename T::allocator_type>,
std::is_same<typename params_type::is_map_container,
typename T::params_type::is_map_container>>,
int> = 0>
void merge(btree_container<T> &&src) {
merge(src);
}
};
// A base class for btree_multimap.
template <typename Tree>
class btree_multimap_container : public btree_multiset_container<Tree> {
using super_type = btree_multiset_container<Tree>;
using params_type = typename Tree::params_type;
public:
using mapped_type = typename params_type::mapped_type;
// Inherit constructors.
using super_type::super_type;
btree_multimap_container() {}
};
} // namespace btree::internal
| 19,109 | 35.26186 | 85 | h |
null | ceph-main/src/include/cpp-btree/btree_map.h | // Copyright 2018 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//
// -----------------------------------------------------------------------------
// File: btree_map.h
// -----------------------------------------------------------------------------
//
// This header file defines B-tree maps: sorted associative containers mapping
// keys to values.
//
// * `btree::btree_map<>`
// * `btree::btree_multimap<>`
//
// These B-tree types are similar to the corresponding types in the STL
// (`std::map` and `std::multimap`) and generally conform to the STL interfaces
// of those types. However, because they are implemented using B-trees, they
// are more efficient in most situations.
//
// Unlike `std::map` and `std::multimap`, which are commonly implemented using
// red-black tree nodes, B-tree maps use more generic B-tree nodes able to hold
// multiple values per node. Holding multiple values per node often makes
// B-tree maps perform better than their `std::map` counterparts, because
// multiple entries can be checked within the same cache hit.
//
// However, these types should not be considered drop-in replacements for
// `std::map` and `std::multimap` as there are some API differences, which are
// noted in this header file.
//
// Importantly, insertions and deletions may invalidate outstanding iterators,
// pointers, and references to elements. Such invalidations are typically only
// an issue if insertion and deletion operations are interleaved with the use of
// more than one iterator, pointer, or reference simultaneously. For this
// reason, `insert()` and `erase()` return a valid iterator at the current
// position.
#pragma once
#include "btree.h"
#include "btree_container.h"
namespace btree {
// btree::btree_map<>
//
// A `btree::btree_map<K, V>` is an ordered associative container of
// unique keys and associated values designed to be a more efficient replacement
// for `std::map` (in most cases).
//
// Keys are sorted using an (optional) comparison function, which defaults to
// `std::less<K>`.
//
// A `btree::btree_map<K, V>` uses a default allocator of
// `std::allocator<std::pair<const K, V>>` to allocate (and deallocate)
// nodes, and construct and destruct values within those nodes. You may
// instead specify a custom allocator `A` (which in turn requires specifying a
// custom comparator `C`) as in `btree::btree_map<K, V, C, A>`.
//
template <typename Key, typename Value, typename Compare = std::less<Key>,
typename Alloc = std::allocator<std::pair<const Key, Value>>>
class btree_map
: public internal::btree_map_container<
internal::btree<internal::map_params<
Key, Value, Compare, Alloc, /*TargetNodeSize=*/256,
/*Multi=*/false>>> {
using Base = typename btree_map::btree_map_container;
public:
// Default constructor.
btree_map() = default;
using Base::Base;
};
// btree::swap(btree::btree_map<>, btree::btree_map<>)
//
// Swaps the contents of two `btree::btree_map` containers.
template <typename K, typename V, typename C, typename A>
void swap(btree_map<K, V, C, A> &x, btree_map<K, V, C, A> &y) {
return x.swap(y);
}
// btree::erase_if(btree::btree_map<>, Pred)
//
// Erases all elements that satisfy the predicate pred from the container.
template <typename K, typename V, typename C, typename A, typename Pred>
void erase_if(btree_map<K, V, C, A> &map, Pred pred) {
for (auto it = map.begin(); it != map.end();) {
if (pred(*it)) {
it = map.erase(it);
} else {
++it;
}
}
}
// btree::btree_multimap
//
// A `btree::btree_multimap<K, V>` is an ordered associative container of
// keys and associated values designed to be a more efficient replacement for
// `std::multimap` (in most cases). Unlike `btree::btree_map`, a B-tree multimap
// allows multiple elements with equivalent keys.
//
// Keys are sorted using an (optional) comparison function, which defaults to
// `std::less<K>`.
//
// A `btree::btree_multimap<K, V>` uses a default allocator of
// `std::allocator<std::pair<const K, V>>` to allocate (and deallocate)
// nodes, and construct and destruct values within those nodes. You may
// instead specify a custom allocator `A` (which in turn requires specifying a
// custom comparator `C`) as in `btree::btree_multimap<K, V, C, A>`.
//
template <typename Key, typename Value, typename Compare = std::less<Key>,
typename Alloc = std::allocator<std::pair<const Key, Value>>>
class btree_multimap
: public internal::btree_multimap_container<
internal::btree<internal::map_params<
Key, Value, Compare, Alloc, /*TargetNodeSize=*/256,
/*Multi=*/true>>> {
using Base = typename btree_multimap::btree_multimap_container;
public:
btree_multimap() = default;
using Base::Base;
};
// btree::swap(btree::btree_multimap<>, btree::btree_multimap<>)
//
// Swaps the contents of two `btree::btree_multimap` containers.
template <typename K, typename V, typename C, typename A>
void swap(btree_multimap<K, V, C, A> &x, btree_multimap<K, V, C, A> &y) {
return x.swap(y);
}
// btree::erase_if(btree::btree_multimap<>, Pred)
//
// Erases all elements that satisfy the predicate pred from the container.
template <typename K, typename V, typename C, typename A, typename Pred>
void erase_if(btree_multimap<K, V, C, A> &map, Pred pred) {
for (auto it = map.begin(); it != map.end();) {
if (pred(*it)) {
it = map.erase(it);
} else {
++it;
}
}
}
} // namespace btree
| 6,052 | 36.83125 | 80 | h |
null | ceph-main/src/include/cpp-btree/btree_set.h | // Copyright 2018 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//
// -----------------------------------------------------------------------------
// File: btree_set.h
// -----------------------------------------------------------------------------
//
// This header file defines B-tree sets: sorted associative containers of
// values.
//
// * `absl::btree_set<>`
// * `absl::btree_multiset<>`
//
// These B-tree types are similar to the corresponding types in the STL
// (`std::set` and `std::multiset`) and generally conform to the STL interfaces
// of those types. However, because they are implemented using B-trees, they
// are more efficient in most situations.
//
// Unlike `std::set` and `std::multiset`, which are commonly implemented using
// red-black tree nodes, B-tree sets use more generic B-tree nodes able to hold
// multiple values per node. Holding multiple values per node often makes
// B-tree sets perform better than their `std::set` counterparts, because
// multiple entries can be checked within the same cache hit.
//
// However, these types should not be considered drop-in replacements for
// `std::set` and `std::multiset` as there are some API differences, which are
// noted in this header file.
//
// Importantly, insertions and deletions may invalidate outstanding iterators,
// pointers, and references to elements. Such invalidations are typically only
// an issue if insertion and deletion operations are interleaved with the use of
// more than one iterator, pointer, or reference simultaneously. For this
// reason, `insert()` and `erase()` return a valid iterator at the current
// position.
#pragma once
#include "btree.h"
#include "btree_container.h"
namespace btree {
// btree::btree_set<>
//
// An `btree::btree_set<K>` is an ordered associative container of unique key
// values designed to be a more efficient replacement for `std::set` (in most
// cases).
//
// Keys are sorted using an (optional) comparison function, which defaults to
// `std::less<K>`.
//
// An `btree::btree_set<K>` uses a default allocator of `std::allocator<K>` to
// allocate (and deallocate) nodes, and construct and destruct values within
// those nodes. You may instead specify a custom allocator `A` (which in turn
// requires specifying a custom comparator `C`) as in
// `btree::btree_set<K, C, A>`.
//
template <typename Key, typename Compare = std::less<Key>,
typename Alloc = std::allocator<Key>>
class btree_set
: public internal::btree_set_container<
internal::btree<internal::set_params<
Key, Compare, Alloc, /*TargetNodeSize=*/256,
/*Multi=*/false>>> {
using Base = typename btree_set::btree_set_container;
public:
// Constructors and Assignment Operators
//
// A `btree_set` supports the same overload set as `std::set`
// for construction and assignment:
//
// * Default constructor
//
// btree::btree_set<std::string> set1;
//
// * Initializer List constructor
//
// btree::btree_set<std::string> set2 =
// {{"huey"}, {"dewey"}, {"louie"},};
//
// * Copy constructor
//
// btree::btree_set<std::string> set3(set2);
//
// * Copy assignment operator
//
// btree::btree_set<std::string> set4;
// set4 = set3;
//
// * Move constructor
//
// // Move is guaranteed efficient
// btree::btree_set<std::string> set5(std::move(set4));
//
// * Move assignment operator
//
// // May be efficient if allocators are compatible
// btree::btree_set<std::string> set6;
// set6 = std::move(set5);
//
// * Range constructor
//
// std::vector<std::string> v = {"a", "b"};
// btree::btree_set<std::string> set7(v.begin(), v.end());
btree_set() {}
using Base::Base;
// btree_set::begin()
//
// Returns an iterator to the beginning of the `btree_set`.
using Base::begin;
// btree_set::cbegin()
//
// Returns a const iterator to the beginning of the `btree_set`.
using Base::cbegin;
// btree_set::end()
//
// Returns an iterator to the end of the `btree_set`.
using Base::end;
// btree_set::cend()
//
// Returns a const iterator to the end of the `btree_set`.
using Base::cend;
// btree_set::empty()
//
// Returns whether or not the `btree_set` is empty.
using Base::empty;
// btree_set::max_size()
//
// Returns the largest theoretical possible number of elements within a
// `btree_set` under current memory constraints. This value can be thought
// of as the largest value of `std::distance(begin(), end())` for a
// `btree_set<Key>`.
using Base::max_size;
// btree_set::size()
//
// Returns the number of elements currently within the `btree_set`.
using Base::size;
// btree_set::clear()
//
// Removes all elements from the `btree_set`. Invalidates any references,
// pointers, or iterators referring to contained elements.
using Base::clear;
// btree_set::erase()
//
// Erases elements within the `btree_set`. Overloads are listed below.
//
// iterator erase(iterator position):
// iterator erase(const_iterator position):
//
// Erases the element at `position` of the `btree_set`, returning
// the iterator pointing to the element after the one that was erased
// (or end() if none exists).
//
// iterator erase(const_iterator first, const_iterator last):
//
// Erases the elements in the open interval [`first`, `last`), returning
// the iterator pointing to the element after the interval that was erased
// (or end() if none exists).
//
// template <typename K> size_type erase(const K& key):
//
// Erases the element with the matching key, if it exists, returning the
// number of elements erased.
using Base::erase;
// btree_set::insert()
//
// Inserts an element of the specified value into the `btree_set`,
// returning an iterator pointing to the newly inserted element, provided that
// an element with the given key does not already exist. If an insertion
// occurs, any references, pointers, or iterators are invalidated.
// Overloads are listed below.
//
// std::pair<iterator,bool> insert(const value_type& value):
//
// Inserts a value into the `btree_set`. Returns a pair consisting of an
// iterator to the inserted element (or to the element that prevented the
// insertion) and a bool denoting whether the insertion took place.
//
// std::pair<iterator,bool> insert(value_type&& value):
//
// Inserts a moveable value into the `btree_set`. Returns a pair
// consisting of an iterator to the inserted element (or to the element that
// prevented the insertion) and a bool denoting whether the insertion took
// place.
//
// iterator insert(const_iterator hint, const value_type& value):
// iterator insert(const_iterator hint, value_type&& value):
//
// Inserts a value, using the position of `hint` as a non-binding suggestion
// for where to begin the insertion search. Returns an iterator to the
// inserted element, or to the existing element that prevented the
// insertion.
//
// void insert(InputIterator first, InputIterator last):
//
// Inserts a range of values [`first`, `last`).
//
// void insert(std::initializer_list<init_type> ilist):
//
// Inserts the elements within the initializer list `ilist`.
using Base::insert;
// btree_set::emplace()
//
// Inserts an element of the specified value by constructing it in-place
// within the `btree_set`, provided that no element with the given key
// already exists.
//
// The element may be constructed even if there already is an element with the
// key in the container, in which case the newly constructed element will be
// destroyed immediately.
//
// If an insertion occurs, any references, pointers, or iterators are
// invalidated.
using Base::emplace;
// btree_set::emplace_hint()
//
// Inserts an element of the specified value by constructing it in-place
// within the `btree_set`, using the position of `hint` as a non-binding
// suggestion for where to begin the insertion search, and only inserts
// provided that no element with the given key already exists.
//
// The element may be constructed even if there already is an element with the
// key in the container, in which case the newly constructed element will be
// destroyed immediately.
//
// If an insertion occurs, any references, pointers, or iterators are
// invalidated.
using Base::emplace_hint;
// btree_set::merge()
//
// Extracts elements from a given `source` btree_set into this
// `btree_set`. If the destination `btree_set` already contains an
// element with an equivalent key, that element is not extracted.
using Base::merge;
// btree_set::swap(btree_set& other)
//
// Exchanges the contents of this `btree_set` with those of the `other`
// btree_set, avoiding invocation of any move, copy, or swap operations on
// individual elements.
//
// All iterators and references on the `btree_set` remain valid, excepting
// for the past-the-end iterator, which is invalidated.
using Base::swap;
// btree_set::contains()
//
// template <typename K> bool contains(const K& key) const:
//
// Determines whether an element comparing equal to the given `key` exists
// within the `btree_set`, returning `true` if so or `false` otherwise.
//
// Supports heterogeneous lookup, provided that the set is provided a
// compatible heterogeneous comparator.
using Base::contains;
// btree_set::count()
//
// template <typename K> size_type count(const K& key) const:
//
// Returns the number of elements comparing equal to the given `key` within
// the `btree_set`. Note that this function will return either `1` or `0`
// since duplicate elements are not allowed within a `btree_set`.
//
// Supports heterogeneous lookup, provided that the set is provided a
// compatible heterogeneous comparator.
using Base::count;
// btree_set::equal_range()
//
// Returns a closed range [first, last], defined by a `std::pair` of two
// iterators, containing all elements with the passed key in the
// `btree_set`.
using Base::equal_range;
// btree_set::find()
//
// template <typename K> iterator find(const K& key):
// template <typename K> const_iterator find(const K& key) const:
//
// Finds an element with the passed `key` within the `btree_set`.
//
// Supports heterogeneous lookup, provided that the set is provided a
// compatible heterogeneous comparator.
using Base::find;
// btree_set::get_allocator()
//
// Returns the allocator function associated with this `btree_set`.
using Base::get_allocator;
// btree_set::key_comp();
//
// Returns the key comparator associated with this `btree_set`.
using Base::key_comp;
// btree_set::value_comp();
//
// Returns the value comparator associated with this `btree_set`. The keys to
// sort the elements are the values themselves, therefore `value_comp` and its
// sibling member function `key_comp` are equivalent.
using Base::value_comp;
};
// btree::swap(btree::btree_set<>, btree::btree_set<>)
//
// Swaps the contents of two `btree::btree_set` containers.
template <typename K, typename C, typename A>
void swap(btree_set<K, C, A> &x, btree_set<K, C, A> &y) {
return x.swap(y);
}
// btree::erase_if(btree::btree_set<>, Pred)
//
// Erases all elements that satisfy the predicate pred from the container.
template <typename K, typename C, typename A, typename Pred>
void erase_if(btree_set<K, C, A> &set, Pred pred) {
for (auto it = set.begin(); it != set.end();) {
if (pred(*it)) {
it = set.erase(it);
} else {
++it;
}
}
}
// btree::btree_multiset<>
//
// An `btree::btree_multiset<K>` is an ordered associative container of
// keys and associated values designed to be a more efficient replacement
// for `std::multiset` (in most cases). Unlike `btree::btree_set`, a B-tree
// multiset allows equivalent elements.
//
// Keys are sorted using an (optional) comparison function, which defaults to
// `std::less<K>`.
//
// An `btree::btree_multiset<K>` uses a default allocator of `std::allocator<K>`
// to allocate (and deallocate) nodes, and construct and destruct values within
// those nodes. You may instead specify a custom allocator `A` (which in turn
// requires specifying a custom comparator `C`) as in
// `btree::btree_multiset<K, C, A>`.
//
template <typename Key, typename Compare = std::less<Key>,
typename Alloc = std::allocator<Key>>
class btree_multiset
: public internal::btree_multiset_container<
internal::btree<internal::set_params<
Key, Compare, Alloc, /*TargetNodeSize=*/256,
/*Multi=*/true>>> {
using Base = typename btree_multiset::btree_multiset_container;
public:
// Constructors and Assignment Operators
//
// A `btree_multiset` supports the same overload set as `std::set`
// for construction and assignment:
//
// * Default constructor
//
// btree::btree_multiset<std::string> set1;
//
// * Initializer List constructor
//
// btree::btree_multiset<std::string> set2 =
// {{"huey"}, {"dewey"}, {"louie"},};
//
// * Copy constructor
//
// btree::btree_multiset<std::string> set3(set2);
//
// * Copy assignment operator
//
// btree::btree_multiset<std::string> set4;
// set4 = set3;
//
// * Move constructor
//
// // Move is guaranteed efficient
// btree::btree_multiset<std::string> set5(std::move(set4));
//
// * Move assignment operator
//
// // May be efficient if allocators are compatible
// btree::btree_multiset<std::string> set6;
// set6 = std::move(set5);
//
// * Range constructor
//
// std::vector<std::string> v = {"a", "b"};
// btree::btree_multiset<std::string> set7(v.begin(), v.end());
btree_multiset() {}
using Base::Base;
// btree_multiset::begin()
//
// Returns an iterator to the beginning of the `btree_multiset`.
using Base::begin;
// btree_multiset::cbegin()
//
// Returns a const iterator to the beginning of the `btree_multiset`.
using Base::cbegin;
// btree_multiset::end()
//
// Returns an iterator to the end of the `btree_multiset`.
using Base::end;
// btree_multiset::cend()
//
// Returns a const iterator to the end of the `btree_multiset`.
using Base::cend;
// btree_multiset::empty()
//
// Returns whether or not the `btree_multiset` is empty.
using Base::empty;
// btree_multiset::max_size()
//
// Returns the largest theoretical possible number of elements within a
// `btree_multiset` under current memory constraints. This value can be
// thought of as the largest value of `std::distance(begin(), end())` for a
// `btree_multiset<Key>`.
using Base::max_size;
// btree_multiset::size()
//
// Returns the number of elements currently within the `btree_multiset`.
using Base::size;
// btree_multiset::clear()
//
// Removes all elements from the `btree_multiset`. Invalidates any references,
// pointers, or iterators referring to contained elements.
using Base::clear;
// btree_multiset::erase()
//
// Erases elements within the `btree_multiset`. Overloads are listed below.
//
// iterator erase(iterator position):
// iterator erase(const_iterator position):
//
// Erases the element at `position` of the `btree_multiset`, returning
// the iterator pointing to the element after the one that was erased
// (or end() if none exists).
//
// iterator erase(const_iterator first, const_iterator last):
//
// Erases the elements in the open interval [`first`, `last`), returning
// the iterator pointing to the element after the interval that was erased
// (or end() if none exists).
//
// template <typename K> size_type erase(const K& key):
//
// Erases the elements matching the key, if any exist, returning the
// number of elements erased.
using Base::erase;
// btree_multiset::insert()
//
// Inserts an element of the specified value into the `btree_multiset`,
// returning an iterator pointing to the newly inserted element.
// Any references, pointers, or iterators are invalidated. Overloads are
// listed below.
//
// iterator insert(const value_type& value):
//
// Inserts a value into the `btree_multiset`, returning an iterator to the
// inserted element.
//
// iterator insert(value_type&& value):
//
// Inserts a moveable value into the `btree_multiset`, returning an iterator
// to the inserted element.
//
// iterator insert(const_iterator hint, const value_type& value):
// iterator insert(const_iterator hint, value_type&& value):
//
// Inserts a value, using the position of `hint` as a non-binding suggestion
// for where to begin the insertion search. Returns an iterator to the
// inserted element.
//
// void insert(InputIterator first, InputIterator last):
//
// Inserts a range of values [`first`, `last`).
//
// void insert(std::initializer_list<init_type> ilist):
//
// Inserts the elements within the initializer list `ilist`.
using Base::insert;
// btree_multiset::emplace()
//
// Inserts an element of the specified value by constructing it in-place
// within the `btree_multiset`. Any references, pointers, or iterators are
// invalidated.
using Base::emplace;
// btree_multiset::emplace_hint()
//
// Inserts an element of the specified value by constructing it in-place
// within the `btree_multiset`, using the position of `hint` as a non-binding
// suggestion for where to begin the insertion search.
//
// Any references, pointers, or iterators are invalidated.
using Base::emplace_hint;
// btree_multiset::merge()
//
// Extracts elements from a given `source` btree_multiset into this
// `btree_multiset`. If the destination `btree_multiset` already contains an
// element with an equivalent key, that element is not extracted.
using Base::merge;
// btree_multiset::swap(btree_multiset& other)
//
// Exchanges the contents of this `btree_multiset` with those of the `other`
// btree_multiset, avoiding invocation of any move, copy, or swap operations
// on individual elements.
//
// All iterators and references on the `btree_multiset` remain valid,
// excepting for the past-the-end iterator, which is invalidated.
using Base::swap;
// btree_multiset::contains()
//
// template <typename K> bool contains(const K& key) const:
//
// Determines whether an element comparing equal to the given `key` exists
// within the `btree_multiset`, returning `true` if so or `false` otherwise.
//
// Supports heterogeneous lookup, provided that the set is provided a
// compatible heterogeneous comparator.
using Base::contains;
// btree_multiset::count()
//
// template <typename K> size_type count(const K& key) const:
//
// Returns the number of elements comparing equal to the given `key` within
// the `btree_multiset`.
//
// Supports heterogeneous lookup, provided that the set is provided a
// compatible heterogeneous comparator.
using Base::count;
// btree_multiset::equal_range()
//
// Returns a closed range [first, last], defined by a `std::pair` of two
// iterators, containing all elements with the passed key in the
// `btree_multiset`.
using Base::equal_range;
// btree_multiset::find()
//
// template <typename K> iterator find(const K& key):
// template <typename K> const_iterator find(const K& key) const:
//
// Finds an element with the passed `key` within the `btree_multiset`.
//
// Supports heterogeneous lookup, provided that the set is provided a
// compatible heterogeneous comparator.
using Base::find;
// btree_multiset::get_allocator()
//
// Returns the allocator function associated with this `btree_multiset`.
using Base::get_allocator;
// btree_multiset::key_comp();
//
// Returns the key comparator associated with this `btree_multiset`.
using Base::key_comp;
// btree_multiset::value_comp();
//
// Returns the value comparator associated with this `btree_multiset`. The
// keys to sort the elements are the values themselves, therefore `value_comp`
// and its sibling member function `key_comp` are equivalent.
using Base::value_comp;
};
// btree::swap(btree::btree_multiset<>, btree::btree_multiset<>)
//
// Swaps the contents of two `btree::btree_multiset` containers.
template <typename K, typename C, typename A>
void swap(btree_multiset<K, C, A> &x, btree_multiset<K, C, A> &y) {
return x.swap(y);
}
// btree::erase_if(btree::btree_multiset<>, Pred)
//
// Erases all elements that satisfy the predicate pred from the container.
template <typename K, typename C, typename A, typename Pred>
void erase_if(btree_multiset<K, C, A> &set, Pred pred) {
for (auto it = set.begin(); it != set.end();) {
if (pred(*it)) {
it = set.erase(it);
} else {
++it;
}
}
}
} // namespace btree
| 21,678 | 33.248025 | 80 | h |
null | ceph-main/src/include/rados/librgw.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_LIBRGW_H
#define CEPH_LIBRGW_H
#ifdef __cplusplus
extern "C" {
#endif
#define LIBRGW_VER_MAJOR 1
#define LIBRGW_VER_MINOR 1
#define LIBRGW_VER_EXTRA 0
#define LIBRGW_VERSION(maj, min, extra) ((maj << 16) + (min << 8) + extra)
#define LIBRGW_VERSION_CODE LIBRGW_VERSION(LIBRGW_VER_MAJOR, LIBRGW_VER_MINOR, LIBRGW_VER_EXTRA)
typedef void* librgw_t;
int librgw_create(librgw_t *rgw, int argc, char **argv);
void librgw_shutdown(librgw_t rgw);
#ifdef __cplusplus
}
#endif
#endif /* CEPH_LIBRGW_H */
| 922 | 23.945946 | 96 | h |
null | ceph-main/src/include/rados/objclass.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_OBJCLASS_OBJCLASS_PUBLIC_H
#define CEPH_OBJCLASS_OBJCLASS_PUBLIC_H
#ifdef __cplusplus
#include "buffer.h"
extern "C" {
#endif
#define CEPH_CLS_API [[gnu::visibility("default")]]
#define CLS_VER(maj,min) \
int __cls_ver__## maj ## _ ##min = 0; \
int __cls_ver_maj = maj; \
int __cls_ver_min = min;
#define CLS_NAME(name) \
int __cls_name__## name = 0; \
const char *__cls_name = #name;
#define CLS_INIT(name) \
CEPH_CLS_API void __cls_init()
#define CLS_METHOD_RD 0x1 /// method executes read operations
#define CLS_METHOD_WR 0x2 /// method executes write operations
#define CLS_METHOD_PROMOTE 0x8 /// method cannot be proxied to base tier
#define CLS_LOG(level, fmt, ...) \
cls_log(level, "<cls> %s:%d: " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
#define CLS_ERR(fmt, ...) CLS_LOG(0, fmt, ##__VA_ARGS__)
/**
* Initialize a class.
*/
void __cls_init();
/**
* @typdef cls_handle_t
*
* A handle for interacting with the object class.
*/
typedef void *cls_handle_t;
/**
* @typedef cls_method_handle_t
*
* A handle for interacting with the method of the object class.
*/
typedef void *cls_method_handle_t;
/**
* @typedef cls_method_context_t
*
* A context for the method of the object class.
*/
typedef void* cls_method_context_t;
/*class utils*/
extern int cls_log(int level, const char *format, ...)
__attribute__((__format__(printf, 2, 3)));
/* class registration api */
extern int cls_register(const char *name, cls_handle_t *handle);
#ifdef __cplusplus
}
/**
* @typedef cls_method_cxx_call_t
*
*/
typedef int (*cls_method_cxx_call_t)(cls_method_context_t ctx,
class ceph::buffer::list *inbl, class ceph::buffer::list *outbl);
/**
* Register a method.
*
* @param hclass
* @param method
* @param flags
* @param class_call
* @param handle
*/
extern int cls_register_cxx_method(cls_handle_t hclass, const char *method, int flags,
cls_method_cxx_call_t class_call, cls_method_handle_t *handle);
/**
* Create an object.
*
* @param hctx
* @param exclusive
*/
extern int cls_cxx_create(cls_method_context_t hctx, bool exclusive);
/**
* Remove an object.
*
* @param hctx
*/
extern int cls_cxx_remove(cls_method_context_t hctx);
/**
* Check on the status of an object.
*
* @param hctx
* @param size
* @param mtime
*/
extern int cls_cxx_stat(cls_method_context_t hctx, uint64_t *size, time_t *mtime);
/**
* Read contents of an object.
*
* @param hctx
* @param ofs
* @param len
* @param bl
*/
extern int cls_cxx_read(cls_method_context_t hctx, int ofs, int len, ceph::bufferlist *bl);
/**
* Write to the object.
*
* @param hctx
* @param ofs
* @param len
* @param bl
*/
extern int cls_cxx_write(cls_method_context_t hctx, int ofs, int len, ceph::bufferlist *bl);
/**
* Get xattr of the object.
*
* @param hctx
* @param name
* @param outbl
*/
extern int cls_cxx_getxattr(cls_method_context_t hctx, const char *name,
ceph::bufferlist *outbl);
/**
* Set xattr of the object.
*
* @param hctx
* @param name
* @param inbl
*/
extern int cls_cxx_setxattr(cls_method_context_t hctx, const char *name,
ceph::bufferlist *inbl);
/**
* Get value corresponding to a key from the map.
*
* @param hctx
* @param key
* @param outbl
*/
extern int cls_cxx_map_get_val(cls_method_context_t hctx,
const std::string &key, ceph::bufferlist *outbl);
/**
* Set value corresponding to a key in the map.
*
* @param hctx
* @param key
* @param inbl
*/
extern int cls_cxx_map_set_val(cls_method_context_t hctx,
const std::string &key, ceph::bufferlist *inbl);
#endif
#endif
| 3,860 | 20.691011 | 98 | h |
null | ceph-main/src/include/rados/rgw_file.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* convert RGW commands to file commands
*
* Copyright (C) 2015 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 RADOS_RGW_FILE_H
#define RADOS_RGW_FILE_H
#include <sys/stat.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include "librgw.h"
#ifdef __cplusplus
extern "C" {
#endif
#define LIBRGW_FILE_VER_MAJOR 1
#define LIBRGW_FILE_VER_MINOR 2
#define LIBRGW_FILE_VER_EXTRA 1 /* version number needs to advance to
* match change in rgw_raddir2 signature */
#define LIBRGW_FILE_VERSION(maj, min, extra) ((maj << 16) + (min << 8) + extra)
#define LIBRGW_FILE_VERSION_CODE LIBRGW_FILE_VERSION(LIBRGW_FILE_VER_MAJOR, LIBRGW_FILE_VER_MINOR, LIBRGW_FILE_VER_EXTRA)
/*
* object types
*/
enum rgw_fh_type {
RGW_FS_TYPE_NIL = 0,
RGW_FS_TYPE_FILE,
RGW_FS_TYPE_DIRECTORY,
RGW_FS_TYPE_SYMBOLIC_LINK,
};
/*
* dynamic allocated handle to support nfs handle
*/
/* content-addressable hash */
struct rgw_fh_hk {
uint64_t bucket;
uint64_t object;
};
struct rgw_file_handle
{
/* content-addressable hash */
struct rgw_fh_hk fh_hk;
void *fh_private; /* librgw private data */
/* object type */
enum rgw_fh_type fh_type;
};
struct rgw_fs
{
librgw_t rgw;
void *fs_private;
struct rgw_file_handle* root_fh;
};
/* XXX mount info hypothetical--emulate Unix, support at least
* UUID-length fsid */
struct rgw_statvfs {
uint64_t f_bsize; /* file system block size */
uint64_t f_frsize; /* fragment size */
uint64_t f_blocks; /* size of fs in f_frsize units */
uint64_t f_bfree; /* # free blocks */
uint64_t f_bavail; /* # free blocks for unprivileged users */
uint64_t f_files; /* # inodes */
uint64_t f_ffree; /* # free inodes */
uint64_t f_favail; /* # free inodes for unprivileged users */
uint64_t f_fsid[2]; /* file system ID */
uint64_t f_flag; /* mount flags */
uint64_t f_namemax; /* maximum filename length */
};
void rgwfile_version(int *major, int *minor, int *extra);
/*
lookup object by name (POSIX style)
*/
#define RGW_LOOKUP_FLAG_NONE 0x0000
#define RGW_LOOKUP_FLAG_CREATE 0x0001
#define RGW_LOOKUP_FLAG_RCB 0x0002 /* readdir callback hint */
#define RGW_LOOKUP_FLAG_DIR 0x0004
#define RGW_LOOKUP_FLAG_FILE 0x0008
#define RGW_LOOKUP_TYPE_FLAGS \
(RGW_LOOKUP_FLAG_DIR|RGW_LOOKUP_FLAG_FILE)
int rgw_lookup(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh, const char *path,
struct rgw_file_handle **fh,
struct stat *st, uint32_t mask, uint32_t flags);
/*
lookup object by handle (NFS style)
*/
int rgw_lookup_handle(struct rgw_fs *rgw_fs, struct rgw_fh_hk *fh_hk,
struct rgw_file_handle **fh, uint32_t flags);
/*
* release file handle
*/
#define RGW_FH_RELE_FLAG_NONE 0x0000
int rgw_fh_rele(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
uint32_t flags);
/*
attach rgw namespace
*/
#define RGW_MOUNT_FLAG_NONE 0x0000
int rgw_mount(librgw_t rgw, const char *uid, const char *key,
const char *secret, struct rgw_fs **rgw_fs,
uint32_t flags);
int rgw_mount2(librgw_t rgw, const char *uid, const char *key,
const char *secret, const char *root, struct rgw_fs **rgw_fs,
uint32_t flags);
/*
register invalidate callbacks
*/
#define RGW_REG_INVALIDATE_FLAG_NONE 0x0000
typedef void (*rgw_fh_callback_t)(void *handle, struct rgw_fh_hk fh_hk);
int rgw_register_invalidate(struct rgw_fs *rgw_fs, rgw_fh_callback_t cb,
void *arg, uint32_t flags);
/*
detach rgw namespace
*/
#define RGW_UMOUNT_FLAG_NONE 0x0000
int rgw_umount(struct rgw_fs *rgw_fs, uint32_t flags);
/*
get filesystem attributes
*/
#define RGW_STATFS_FLAG_NONE 0x0000
int rgw_statfs(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh,
struct rgw_statvfs *vfs_st,
uint32_t flags);
/* XXX (get|set)attr mask bits */
#define RGW_SETATTR_MODE 1
#define RGW_SETATTR_UID 2
#define RGW_SETATTR_GID 4
#define RGW_SETATTR_MTIME 8
#define RGW_SETATTR_ATIME 16
#define RGW_SETATTR_SIZE 32
#define RGW_SETATTR_CTIME 64
/*
create file
*/
#define RGW_CREATE_FLAG_NONE 0x0000
int rgw_create(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh,
const char *name, struct stat *st, uint32_t mask,
struct rgw_file_handle **fh, uint32_t posix_flags,
uint32_t flags);
/*
create a symbolic link
*/
#define RGW_CREATELINK_FLAG_NONE 0x0000
int rgw_symlink(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh,
const char *name, const char *link_path, struct stat *st,
uint32_t mask, struct rgw_file_handle **fh, uint32_t posix_flags,
uint32_t flags);
/*
create a new directory
*/
#define RGW_MKDIR_FLAG_NONE 0x0000
int rgw_mkdir(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh,
const char *name, struct stat *st, uint32_t mask,
struct rgw_file_handle **fh, uint32_t flags);
/*
rename object
*/
#define RGW_RENAME_FLAG_NONE 0x0000
int rgw_rename(struct rgw_fs *rgw_fs,
struct rgw_file_handle *olddir, const char* old_name,
struct rgw_file_handle *newdir, const char* new_name,
uint32_t flags);
/*
remove file or directory
*/
#define RGW_UNLINK_FLAG_NONE 0x0000
int rgw_unlink(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh, const char* path,
uint32_t flags);
/*
read directory content
*/
typedef int (*rgw_readdir_cb)(const char *name, void *arg, uint64_t offset,
struct stat *st, uint32_t mask,
uint32_t flags);
#define RGW_READDIR_FLAG_NONE 0x0000
#define RGW_READDIR_FLAG_DOTDOT 0x0001 /* send dot names */
int rgw_readdir(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh, uint64_t *offset,
rgw_readdir_cb rcb, void *cb_arg, bool *eof,
uint32_t flags);
/* enumeration continuing from name */
int rgw_readdir2(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh, const char *name,
rgw_readdir_cb rcb, void *cb_arg, bool *eof,
uint32_t flags);
/* project offset of dirent name */
#define RGW_DIRENT_OFFSET_FLAG_NONE 0x0000
int rgw_dirent_offset(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh,
const char *name, int64_t *offset,
uint32_t flags);
/*
get unix attributes for object
*/
#define RGW_GETATTR_FLAG_NONE 0x0000
int rgw_getattr(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, struct stat *st,
uint32_t flags);
/*
set unix attributes for object
*/
#define RGW_SETATTR_FLAG_NONE 0x0000
int rgw_setattr(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, struct stat *st,
uint32_t mask, uint32_t flags);
/*
truncate file
*/
#define RGW_TRUNCATE_FLAG_NONE 0x0000
int rgw_truncate(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint64_t size,
uint32_t flags);
/*
open file
*/
#define RGW_OPEN_FLAG_NONE 0x0000
#define RGW_OPEN_FLAG_CREATE 0x0001
#define RGW_OPEN_FLAG_V3 0x0002 /* ops have v3 semantics */
#define RGW_OPEN_FLAG_STATELESS 0x0002 /* alias it */
int rgw_open(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh,
uint32_t posix_flags, uint32_t flags);
/*
close file
*/
#define RGW_CLOSE_FLAG_NONE 0x0000
#define RGW_CLOSE_FLAG_RELE 0x0001
int rgw_close(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
uint32_t flags);
/*
read data from file
*/
#define RGW_READ_FLAG_NONE 0x0000
int rgw_read(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint64_t offset,
size_t length, size_t *bytes_read, void *buffer,
uint32_t flags);
/*
read symbolic link
*/
#define RGW_READLINK_FLAG_NONE 0x0000
int rgw_readlink(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint64_t offset,
size_t length, size_t *bytes_read, void *buffer,
uint32_t flags);
/*
write data to file
*/
#define RGW_WRITE_FLAG_NONE 0x0000
int rgw_write(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint64_t offset,
size_t length, size_t *bytes_written, void *buffer,
uint32_t flags);
#define RGW_UIO_NONE 0x0000
#define RGW_UIO_GIFT 0x0001
#define RGW_UIO_FREE 0x0002
#define RGW_UIO_BUFQ 0x0004
struct rgw_uio;
typedef void (*rgw_uio_release)(struct rgw_uio *, uint32_t);
/* buffer vector descriptors */
struct rgw_vio {
void *vio_p1;
void *vio_u1;
void *vio_base;
int32_t vio_len;
};
struct rgw_uio {
rgw_uio_release uio_rele;
void *uio_p1;
void *uio_u1;
uint64_t uio_offset;
uint64_t uio_resid;
uint32_t uio_cnt;
uint32_t uio_flags;
struct rgw_vio *uio_vio; /* appended vectors */
};
typedef struct rgw_uio rgw_uio;
int rgw_readv(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, rgw_uio *uio, uint32_t flags);
int rgw_writev(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, rgw_uio *uio, uint32_t flags);
/*
sync written data
*/
#define RGW_FSYNC_FLAG_NONE 0x0000
int rgw_fsync(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
uint32_t flags);
/*
NFS commit operation
*/
#define RGW_COMMIT_FLAG_NONE 0x0000
int rgw_commit(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
uint64_t offset, uint64_t length, uint32_t flags);
/*
extended attributes
*/
typedef struct rgw_xattrstr
{
char *val;
uint32_t len;
} rgw_xattrstr;
typedef struct rgw_xattr
{
rgw_xattrstr key;
rgw_xattrstr val;
} rgw_xattr;
typedef struct rgw_xattrlist
{
rgw_xattr *xattrs;
uint32_t xattr_cnt;
} rgw_xattrlist;
#define RGW_GETXATTR_FLAG_NONE 0x0000
typedef int (*rgw_getxattr_cb)(rgw_xattrlist *attrs, void *arg,
uint32_t flags);
int rgw_getxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrlist *attrs, rgw_getxattr_cb cb, void *cb_arg,
uint32_t flags);
#define RGW_LSXATTR_FLAG_NONE 0x0000
#define RGW_LSXATTR_FLAG_STOP 0x0001
int rgw_lsxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrstr *filter_prefix /* unimplemented for now */,
rgw_getxattr_cb cb, void *cb_arg, uint32_t flags);
#define RGW_SETXATTR_FLAG_NONE 0x0000
int rgw_setxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrlist *attrs, uint32_t flags);
#define RGW_RMXATTR_FLAG_NONE 0x0000
int rgw_rmxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrlist *attrs, uint32_t flags);
#ifdef __cplusplus
}
#endif
#endif /* RADOS_RGW_FILE_H */
| 10,819 | 23.988453 | 121 | h |
null | ceph-main/src/include/rbd/features.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_RBD_FEATURES_H
#define CEPH_RBD_FEATURES_H
#define RBD_FEATURE_LAYERING (1ULL<<0)
#define RBD_FEATURE_STRIPINGV2 (1ULL<<1)
#define RBD_FEATURE_EXCLUSIVE_LOCK (1ULL<<2)
#define RBD_FEATURE_OBJECT_MAP (1ULL<<3)
#define RBD_FEATURE_FAST_DIFF (1ULL<<4)
#define RBD_FEATURE_DEEP_FLATTEN (1ULL<<5)
#define RBD_FEATURE_JOURNALING (1ULL<<6)
#define RBD_FEATURE_DATA_POOL (1ULL<<7)
#define RBD_FEATURE_OPERATIONS (1ULL<<8)
#define RBD_FEATURE_MIGRATING (1ULL<<9)
#define RBD_FEATURE_NON_PRIMARY (1ULL<<10)
#define RBD_FEATURE_DIRTY_CACHE (1ULL<<11)
#define RBD_FEATURES_DEFAULT (RBD_FEATURE_LAYERING | \
RBD_FEATURE_EXCLUSIVE_LOCK | \
RBD_FEATURE_OBJECT_MAP | \
RBD_FEATURE_FAST_DIFF | \
RBD_FEATURE_DEEP_FLATTEN)
#define RBD_FEATURE_NAME_LAYERING "layering"
#define RBD_FEATURE_NAME_STRIPINGV2 "striping"
#define RBD_FEATURE_NAME_EXCLUSIVE_LOCK "exclusive-lock"
#define RBD_FEATURE_NAME_OBJECT_MAP "object-map"
#define RBD_FEATURE_NAME_FAST_DIFF "fast-diff"
#define RBD_FEATURE_NAME_DEEP_FLATTEN "deep-flatten"
#define RBD_FEATURE_NAME_JOURNALING "journaling"
#define RBD_FEATURE_NAME_DATA_POOL "data-pool"
#define RBD_FEATURE_NAME_OPERATIONS "operations"
#define RBD_FEATURE_NAME_MIGRATING "migrating"
#define RBD_FEATURE_NAME_NON_PRIMARY "non-primary"
#define RBD_FEATURE_NAME_DIRTY_CACHE "dirty-cache"
/// features that make an image inaccessible for read or write by
/// clients that don't understand them
#define RBD_FEATURES_INCOMPATIBLE (RBD_FEATURE_LAYERING | \
RBD_FEATURE_STRIPINGV2 | \
RBD_FEATURE_DATA_POOL | \
RBD_FEATURE_DIRTY_CACHE)
/// features that make an image unwritable by clients that don't understand them
#define RBD_FEATURES_RW_INCOMPATIBLE (RBD_FEATURES_INCOMPATIBLE | \
RBD_FEATURE_EXCLUSIVE_LOCK | \
RBD_FEATURE_OBJECT_MAP | \
RBD_FEATURE_FAST_DIFF | \
RBD_FEATURE_DEEP_FLATTEN | \
RBD_FEATURE_JOURNALING | \
RBD_FEATURE_OPERATIONS | \
RBD_FEATURE_MIGRATING | \
RBD_FEATURE_NON_PRIMARY)
#define RBD_FEATURES_ALL (RBD_FEATURE_LAYERING | \
RBD_FEATURE_STRIPINGV2 | \
RBD_FEATURE_EXCLUSIVE_LOCK | \
RBD_FEATURE_OBJECT_MAP | \
RBD_FEATURE_FAST_DIFF | \
RBD_FEATURE_DEEP_FLATTEN | \
RBD_FEATURE_JOURNALING | \
RBD_FEATURE_DATA_POOL | \
RBD_FEATURE_OPERATIONS | \
RBD_FEATURE_MIGRATING | \
RBD_FEATURE_NON_PRIMARY | \
RBD_FEATURE_DIRTY_CACHE)
/// features that may be dynamically enabled or disabled
#define RBD_FEATURES_MUTABLE (RBD_FEATURE_EXCLUSIVE_LOCK | \
RBD_FEATURE_OBJECT_MAP | \
RBD_FEATURE_FAST_DIFF | \
RBD_FEATURE_JOURNALING | \
RBD_FEATURE_NON_PRIMARY | \
RBD_FEATURE_DIRTY_CACHE)
#define RBD_FEATURES_MUTABLE_INTERNAL (RBD_FEATURE_NON_PRIMARY | \
RBD_FEATURE_DIRTY_CACHE)
/// features that may be dynamically disabled
#define RBD_FEATURES_DISABLE_ONLY (RBD_FEATURE_DEEP_FLATTEN)
/// features that only work when used with a single client
/// using the image for writes
#define RBD_FEATURES_SINGLE_CLIENT (RBD_FEATURE_EXCLUSIVE_LOCK | \
RBD_FEATURE_OBJECT_MAP | \
RBD_FEATURE_FAST_DIFF | \
RBD_FEATURE_JOURNALING | \
RBD_FEATURE_DIRTY_CACHE)
/// features that will be implicitly enabled
#define RBD_FEATURES_IMPLICIT_ENABLE (RBD_FEATURE_STRIPINGV2 | \
RBD_FEATURE_DATA_POOL | \
RBD_FEATURE_FAST_DIFF | \
RBD_FEATURE_OPERATIONS | \
RBD_FEATURE_MIGRATING | \
RBD_FEATURE_NON_PRIMARY | \
RBD_FEATURE_DIRTY_CACHE)
/// features that cannot be controlled by the user
#define RBD_FEATURES_INTERNAL (RBD_FEATURE_OPERATIONS | \
RBD_FEATURE_MIGRATING)
#define RBD_OPERATION_FEATURE_CLONE_PARENT (1ULL<<0)
#define RBD_OPERATION_FEATURE_CLONE_CHILD (1ULL<<1)
#define RBD_OPERATION_FEATURE_GROUP (1ULL<<2)
#define RBD_OPERATION_FEATURE_SNAP_TRASH (1ULL<<3)
#define RBD_OPERATION_FEATURE_NAME_CLONE_PARENT "clone-parent"
#define RBD_OPERATION_FEATURE_NAME_CLONE_CHILD "clone-child"
#define RBD_OPERATION_FEATURE_NAME_GROUP "group"
#define RBD_OPERATION_FEATURE_NAME_SNAP_TRASH "snap-trash"
/// all valid operation features
#define RBD_OPERATION_FEATURES_ALL (RBD_OPERATION_FEATURE_CLONE_PARENT | \
RBD_OPERATION_FEATURE_CLONE_CHILD | \
RBD_OPERATION_FEATURE_GROUP | \
RBD_OPERATION_FEATURE_SNAP_TRASH)
#endif
| 6,383 | 51.327869 | 80 | h |
null | ceph-main/src/include/win32/fs_compat.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2021 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.
*
*/
// Those definitions allow handling information coming from Ceph and should
// not be passed to Windows functions.
#pragma once
#define S_IFLNK 0120000
#define S_ISTYPE(m, TYPE) ((m & S_IFMT) == TYPE)
#define S_ISLNK(m) S_ISTYPE(m, S_IFLNK)
#define S_ISUID 04000
#define S_ISGID 02000
#define S_ISVTX 01000
#define LOCK_SH 1
#define LOCK_EX 2
#define LOCK_NB 4
#define LOCK_UN 8
#define LOCK_MAND 32
#define LOCK_READ 64
#define LOCK_WRITE 128
#define LOCK_RW 192
#define AT_SYMLINK_NOFOLLOW 0x100
#define AT_REMOVEDIR 0x200
#define MAXSYMLINKS 65000
#define O_DIRECTORY 0200000
#define O_NOFOLLOW 0400000
#define XATTR_CREATE 1
#define XATTR_REPLACE 2
typedef unsigned int uid_t;
typedef unsigned int gid_t;
| 1,069 | 21.291667 | 75 | h |
null | ceph-main/src/include/win32/ifaddrs.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) 2002-2016 Free Software Foundation, Inc.
* Copyright (C) 2019 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 IFADDRS_H
#define IFADDRS_H
#include "winsock_compat.h"
#include <ifdef.h>
struct ifaddrs {
struct ifaddrs *ifa_next; /* Next item in list */
char *ifa_name; /* Name of interface */
unsigned int ifa_flags; /* Flags from SIOCGIFFLAGS */
struct sockaddr *ifa_addr; /* Address of interface */
struct sockaddr *ifa_netmask; /* Netmask of interface */
struct sockaddr_storage in_addrs;
struct sockaddr_storage in_netmasks;
char ad_name[IF_MAX_STRING_SIZE];
size_t speed;
};
int getifaddrs(struct ifaddrs **ifap);
void freeifaddrs(struct ifaddrs *ifa);
#endif
| 1,100 | 26.525 | 70 | h |
null | ceph-main/src/include/win32/syslog.h | /*
* Copyright 2013, 2015 Cloudbase Solutions Srl
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifndef SYSLOG_H
#define SYSLOG_H 1
#define LOG_EMERG 0 /* system is unusable */
#define LOG_ALERT 1 /* action must be taken immediately */
#define LOG_CRIT 2 /* critical conditions */
#define LOG_ERR 3 /* error conditions */
#define LOG_WARNING 4 /* warning conditions */
#define LOG_NOTICE 5 /* normal but significant condition */
#define LOG_INFO 6 /* informational */
#define LOG_DEBUG 7 /* debug-level messages */
#define LOG_KERN (0<<3) /* kernel messages */
#define LOG_USER (1<<3) /* user-level messages */
#define LOG_MAIL (2<<3) /* mail system */
#define LOG_DAEMON (3<<3) /* system daemons */
#define LOG_AUTH (4<<3) /* security/authorization messages */
#define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */
#define LOG_LPR (6<<3) /* line printer subsystem */
#define LOG_NEWS (7<<3) /* network news subsystem */
#define LOG_UUCP (8<<3) /* UUCP subsystem */
#define LOG_CRON (9<<3) /* clock daemon */
#define LOG_AUTHPRIV (10<<3) /* security/authorization messages */
#define LOG_FTP (11<<3) /* FTP daemon */
#define LOG_LOCAL0 (16<<3) /* reserved for local use */
#define LOG_LOCAL1 (17<<3) /* reserved for local use */
#define LOG_LOCAL2 (18<<3) /* reserved for local use */
#define LOG_LOCAL3 (19<<3) /* reserved for local use */
#define LOG_LOCAL4 (20<<3) /* reserved for local use */
#define LOG_LOCAL5 (21<<3) /* reserved for local use */
#define LOG_LOCAL6 (22<<3) /* reserved for local use */
#define LOG_LOCAL7 (23<<3) /* reserved for local use */
#define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */
/* extract priority */
#define LOG_PRI(p) ((p) & LOG_PRIMASK)
static inline void
openlog(const char *ident, int option, int facility)
{
}
void
syslog(int priority, const char *format, ...);
#endif /* syslog.h */
| 2,597 | 38.969231 | 76 | h |
null | ceph-main/src/include/win32/winsock_compat.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (c) 2019 SUSE LLC
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef WINSOCK_COMPAT_H
#define WINSOCK_COMPAT_H 1
#include "winsock_wrapper.h"
#ifndef poll
#define poll WSAPoll
#endif
// afunix.h is available starting with Windows SDK 17063. Still, it wasn't
// picked up by mingw yet, for which reason we're going to define sockaddr_un
// here.
#ifndef _AFUNIX_
#define UNIX_PATH_MAX 108
typedef struct sockaddr_un
{
ADDRESS_FAMILY sun_family; /* AF_UNIX */
char sun_path[UNIX_PATH_MAX]; /* pathname */
} SOCKADDR_UN, *PSOCKADDR_UN;
#define SIO_AF_UNIX_GETPEERPID _WSAIOR(IOC_VENDOR, 256)
#endif /* _AFUNIX */
#endif /* WINSOCK_COMPAT_H */
| 1,000 | 24.025 | 77 | h |
null | ceph-main/src/include/win32/winsock_wrapper.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (c) 2020 SUSE LLC
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef WINSOCK_WRAPPER_H
#define WINSOCK_WRAPPER_H 1
#ifdef __cplusplus
// Boost complains if winsock2.h (or windows.h) is included before asio.hpp.
#include <boost/asio.hpp>
#endif
#include <winsock2.h>
#include <ws2ipdef.h>
#include <ws2tcpip.h>
#endif /* WINSOCK_WRAPPER_H */
| 683 | 23.428571 | 76 | h |
null | ceph-main/src/java/native/JniConstants.h | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JNI_CONSTANTS_H_included
#define JNI_CONSTANTS_H_included
#include <jni.h>
/**
* A cache to avoid calling FindClass at runtime.
*
* Class lookup is relatively expensive (2.5us on passion-eng at the time of writing), so we do
* all such lookups eagerly at VM startup. This means that code that never uses, say,
* java.util.zip.Deflater still has to pay for the lookup, but it means that on a device the cost
* is definitely paid during boot and amortized. A central cache also removes the temptation to
* dynamically call FindClass rather than add a small cache to each file that needs one. Another
* cost is that each class cached here requires a global reference, though in practice we save
* enough by not having a global reference for each file that uses a class such as java.lang.String
* which is used in several files.
*
* FindClass is still called in a couple of situations: when throwing exceptions, and in some of
* the serialization code. The former is clearly not a performance case, and we're currently
* assuming that neither is the latter.
*
* TODO: similar arguments hold for field and method IDs; we should cache them centrally too.
*/
struct JniConstants {
static void init(JNIEnv* env);
static jclass inet6AddressClass;
static jclass inetAddressClass;
static jclass inetSocketAddressClass;
static jclass stringClass;
};
#define NATIVE_METHOD(className, functionName, signature) \
{ #functionName, signature, reinterpret_cast<void*>(className ## _ ## functionName) }
#endif // JNI_CONSTANTS_H_included
| 2,195 | 40.433962 | 99 | h |
null | ceph-main/src/java/native/ScopedLocalRef.h | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SCOPED_LOCAL_REF_H_included
#define SCOPED_LOCAL_REF_H_included
#include "jni.h"
#include <stddef.h>
// A smart pointer that deletes a JNI local reference when it goes out of scope.
template<typename T>
class ScopedLocalRef {
public:
ScopedLocalRef(JNIEnv* env, T localRef) : mEnv(env), mLocalRef(localRef) {
}
~ScopedLocalRef() {
reset();
}
void reset(T ptr = NULL) {
if (ptr != mLocalRef) {
if (mLocalRef != NULL) {
mEnv->DeleteLocalRef(mLocalRef);
}
mLocalRef = ptr;
}
}
T release() __attribute__((warn_unused_result)) {
T localRef = mLocalRef;
mLocalRef = NULL;
return localRef;
}
T get() const {
return mLocalRef;
}
private:
JNIEnv* mEnv;
T mLocalRef;
// Disallow copy and assignment.
ScopedLocalRef(const ScopedLocalRef&);
void operator=(const ScopedLocalRef&);
};
#endif // SCOPED_LOCAL_REF_H_included
| 1,617 | 24.28125 | 80 | h |
null | ceph-main/src/journal/Entry.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_ENTRY_H
#define CEPH_JOURNAL_ENTRY_H
#include "include/int_types.h"
#include "include/buffer.h"
#include "include/encoding.h"
#include <iosfwd>
#include <string>
namespace ceph {
class Formatter;
}
namespace journal {
class Entry {
public:
Entry() : m_tag_tid(0), m_entry_tid() {}
Entry(uint64_t tag_tid, uint64_t entry_tid, const bufferlist &data)
: m_tag_tid(tag_tid), m_entry_tid(entry_tid), m_data(data)
{
}
static uint32_t get_fixed_size();
inline uint64_t get_tag_tid() const {
return m_tag_tid;
}
inline uint64_t get_entry_tid() const {
return m_entry_tid;
}
inline const bufferlist &get_data() const {
return m_data;
}
void encode(bufferlist &bl) const;
void decode(bufferlist::const_iterator &iter);
void dump(ceph::Formatter *f) const;
bool operator==(const Entry& rhs) const;
static bool is_readable(bufferlist::const_iterator iter, uint32_t *bytes_needed);
static void generate_test_instances(std::list<Entry *> &o);
private:
static const uint64_t preamble = 0x3141592653589793;
uint64_t m_tag_tid;
uint64_t m_entry_tid;
bufferlist m_data;
};
std::ostream &operator<<(std::ostream &os, const Entry &entry);
WRITE_CLASS_ENCODER(journal::Entry)
} // namespace journal
#endif // CEPH_JOURNAL_ENTRY_H
| 1,402 | 21.269841 | 83 | h |
null | ceph-main/src/journal/FutureImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_FUTURE_IMPL_H
#define CEPH_JOURNAL_FUTURE_IMPL_H
#include "include/int_types.h"
#include "common/RefCountedObj.h"
#include "include/Context.h"
#include "journal/Future.h"
#include <list>
#include <map>
#include <boost/noncopyable.hpp>
#include "include/ceph_assert.h"
class Context;
namespace journal {
class FutureImpl : public RefCountedObject, boost::noncopyable {
public:
struct FlushHandler {
using ref = std::shared_ptr<FlushHandler>;
virtual void flush(const ceph::ref_t<FutureImpl> &future) = 0;
virtual ~FlushHandler() = default;
};
void init(const ceph::ref_t<FutureImpl> &prev_future);
inline uint64_t get_tag_tid() const {
return m_tag_tid;
}
inline uint64_t get_entry_tid() const {
return m_entry_tid;
}
inline uint64_t get_commit_tid() const {
return m_commit_tid;
}
void flush(Context *on_safe = NULL);
void wait(Context *on_safe);
bool is_complete() const;
int get_return_value() const;
inline bool is_flush_in_progress() const {
std::lock_guard locker{m_lock};
return (m_flush_state == FLUSH_STATE_IN_PROGRESS);
}
inline void set_flush_in_progress() {
auto h = std::move(m_flush_handler);
ceph_assert(h);
std::lock_guard locker{m_lock};
m_flush_state = FLUSH_STATE_IN_PROGRESS;
}
bool attach(FlushHandler::ref flush_handler);
inline void detach() {
m_flush_handler.reset();
}
inline FlushHandler::ref get_flush_handler() const {
return m_flush_handler;
}
void safe(int r);
private:
friend std::ostream &operator<<(std::ostream &, const FutureImpl &);
typedef std::map<FlushHandler::ref, ceph::ref_t<FutureImpl>> FlushHandlers;
typedef std::list<Context *> Contexts;
enum FlushState {
FLUSH_STATE_NONE,
FLUSH_STATE_REQUESTED,
FLUSH_STATE_IN_PROGRESS
};
struct C_ConsistentAck : public Context {
ceph::ref_t<FutureImpl> future;
C_ConsistentAck(ceph::ref_t<FutureImpl> _future) : future(std::move(_future)) {}
void complete(int r) override {
future->consistent(r);
future.reset();
}
void finish(int r) override {}
};
FRIEND_MAKE_REF(FutureImpl);
FutureImpl(uint64_t tag_tid, uint64_t entry_tid, uint64_t commit_tid);
~FutureImpl() override = default;
uint64_t m_tag_tid;
uint64_t m_entry_tid;
uint64_t m_commit_tid;
mutable ceph::mutex m_lock = ceph::make_mutex("FutureImpl::m_lock", false);
ceph::ref_t<FutureImpl> m_prev_future;
bool m_safe = false;
bool m_consistent = false;
int m_return_value = 0;
FlushHandler::ref m_flush_handler;
FlushState m_flush_state = FLUSH_STATE_NONE;
C_ConsistentAck m_consistent_ack;
Contexts m_contexts;
ceph::ref_t<FutureImpl> prepare_flush(FlushHandlers *flush_handlers);
ceph::ref_t<FutureImpl> prepare_flush(FlushHandlers *flush_handlers, ceph::mutex &lock);
void consistent(int r);
void finish_unlock();
};
std::ostream &operator<<(std::ostream &os, const FutureImpl &future);
} // namespace journal
using journal::operator<<;
#endif // CEPH_JOURNAL_FUTURE_IMPL_H
| 3,161 | 24.707317 | 90 | h |
null | ceph-main/src/journal/JournalMetadata.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_JOURNAL_METADATA_H
#define CEPH_JOURNAL_JOURNAL_METADATA_H
#include "include/int_types.h"
#include "include/Context.h"
#include "include/rados/librados.hpp"
#include "common/AsyncOpTracker.h"
#include "common/Cond.h"
#include "common/Timer.h"
#include "common/ceph_mutex.h"
#include "common/RefCountedObj.h"
#include "common/WorkQueue.h"
#include "cls/journal/cls_journal_types.h"
#include "journal/JournalMetadataListener.h"
#include "journal/Settings.h"
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <functional>
#include <list>
#include <map>
#include <string>
#include "include/ceph_assert.h"
namespace journal {
class JournalMetadata : public RefCountedObject, boost::noncopyable {
public:
typedef std::function<Context*()> CreateContext;
typedef cls::journal::ObjectPosition ObjectPosition;
typedef cls::journal::ObjectPositions ObjectPositions;
typedef cls::journal::ObjectSetPosition ObjectSetPosition;
typedef cls::journal::Client Client;
typedef cls::journal::Tag Tag;
typedef std::set<Client> RegisteredClients;
typedef std::list<Tag> Tags;
void init(Context *on_init);
void shut_down(Context *on_finish);
bool is_initialized() const { return m_initialized; }
void get_immutable_metadata(uint8_t *order, uint8_t *splay_width,
int64_t *pool_id, Context *on_finish);
void get_mutable_metadata(uint64_t *minimum_set, uint64_t *active_set,
RegisteredClients *clients, Context *on_finish);
void add_listener(JournalMetadataListener *listener);
void remove_listener(JournalMetadataListener *listener);
void register_client(const bufferlist &data, Context *on_finish);
void update_client(const bufferlist &data, Context *on_finish);
void unregister_client(Context *on_finish);
void get_client(const std::string &client_id, cls::journal::Client *client,
Context *on_finish);
void allocate_tag(uint64_t tag_class, const bufferlist &data,
Tag *tag, Context *on_finish);
void get_tag(uint64_t tag_tid, Tag *tag, Context *on_finish);
void get_tags(uint64_t start_after_tag_tid,
const boost::optional<uint64_t> &tag_class, Tags *tags,
Context *on_finish);
inline const Settings &get_settings() const {
return m_settings;
}
inline const std::string &get_client_id() const {
return m_client_id;
}
inline uint8_t get_order() const {
return m_order;
}
inline uint64_t get_object_size() const {
return 1 << m_order;
}
inline uint8_t get_splay_width() const {
return m_splay_width;
}
inline int64_t get_pool_id() const {
return m_pool_id;
}
inline void queue(Context *on_finish, int r) {
m_work_queue->queue(on_finish, r);
}
inline ContextWQ *get_work_queue() {
return m_work_queue;
}
inline SafeTimer &get_timer() {
return *m_timer;
}
inline ceph::mutex &get_timer_lock() {
return *m_timer_lock;
}
void set_minimum_set(uint64_t object_set);
inline uint64_t get_minimum_set() const {
std::lock_guard locker{m_lock};
return m_minimum_set;
}
int set_active_set(uint64_t object_set);
void set_active_set(uint64_t object_set, Context *on_finish);
inline uint64_t get_active_set() const {
std::lock_guard locker{m_lock};
return m_active_set;
}
void assert_active_tag(uint64_t tag_tid, Context *on_finish);
void flush_commit_position();
void flush_commit_position(Context *on_safe);
void get_commit_position(ObjectSetPosition *commit_position) const {
std::lock_guard locker{m_lock};
*commit_position = m_client.commit_position;
}
void get_registered_clients(RegisteredClients *registered_clients) {
std::lock_guard locker{m_lock};
*registered_clients = m_registered_clients;
}
inline uint64_t allocate_entry_tid(uint64_t tag_tid) {
std::lock_guard locker{m_lock};
return m_allocated_entry_tids[tag_tid]++;
}
void reserve_entry_tid(uint64_t tag_tid, uint64_t entry_tid);
bool get_last_allocated_entry_tid(uint64_t tag_tid, uint64_t *entry_tid) const;
uint64_t allocate_commit_tid(uint64_t object_num, uint64_t tag_tid,
uint64_t entry_tid);
void overflow_commit_tid(uint64_t commit_tid, uint64_t object_num);
void get_commit_entry(uint64_t commit_tid, uint64_t *object_num,
uint64_t *tag_tid, uint64_t *entry_tid);
void committed(uint64_t commit_tid, const CreateContext &create_context);
void notify_update();
void async_notify_update(Context *on_safe);
void wait_for_ops();
private:
FRIEND_MAKE_REF(JournalMetadata);
JournalMetadata(ContextWQ *work_queue, SafeTimer *timer, ceph::mutex *timer_lock,
librados::IoCtx &ioctx, const std::string &oid,
const std::string &client_id, const Settings &settings);
~JournalMetadata() override;
typedef std::map<uint64_t, uint64_t> AllocatedEntryTids;
typedef std::list<JournalMetadataListener*> Listeners;
typedef std::list<Context*> Contexts;
struct CommitEntry {
uint64_t object_num;
uint64_t tag_tid;
uint64_t entry_tid;
bool committed;
CommitEntry() : object_num(0), tag_tid(0), entry_tid(0), committed(false) {
}
CommitEntry(uint64_t _object_num, uint64_t _tag_tid, uint64_t _entry_tid)
: object_num(_object_num), tag_tid(_tag_tid), entry_tid(_entry_tid),
committed(false) {
}
};
typedef std::map<uint64_t, CommitEntry> CommitTids;
struct C_WatchCtx : public librados::WatchCtx2 {
JournalMetadata *journal_metadata;
C_WatchCtx(JournalMetadata *_journal_metadata)
: journal_metadata(_journal_metadata) {}
void handle_notify(uint64_t notify_id, uint64_t cookie,
uint64_t notifier_id, bufferlist& bl) override {
journal_metadata->handle_watch_notify(notify_id, cookie);
}
void handle_error(uint64_t cookie, int err) override {
journal_metadata->handle_watch_error(err);
}
};
struct C_WatchReset : public Context {
JournalMetadata *journal_metadata;
C_WatchReset(JournalMetadata *_journal_metadata)
: journal_metadata(_journal_metadata) {
journal_metadata->m_async_op_tracker.start_op();
}
~C_WatchReset() override {
journal_metadata->m_async_op_tracker.finish_op();
}
void finish(int r) override {
journal_metadata->handle_watch_reset();
}
};
struct C_CommitPositionTask : public Context {
JournalMetadata *journal_metadata;
C_CommitPositionTask(JournalMetadata *_journal_metadata)
: journal_metadata(_journal_metadata) {
journal_metadata->m_async_op_tracker.start_op();
}
~C_CommitPositionTask() override {
journal_metadata->m_async_op_tracker.finish_op();
}
void finish(int r) override {
std::lock_guard locker{journal_metadata->m_lock};
journal_metadata->handle_commit_position_task();
};
};
struct C_AioNotify : public Context {
JournalMetadata* journal_metadata;
Context *on_safe;
C_AioNotify(JournalMetadata *_journal_metadata, Context *_on_safe)
: journal_metadata(_journal_metadata), on_safe(_on_safe) {
journal_metadata->m_async_op_tracker.start_op();
}
~C_AioNotify() override {
journal_metadata->m_async_op_tracker.finish_op();
}
void finish(int r) override {
journal_metadata->handle_notified(r);
if (on_safe != nullptr) {
on_safe->complete(0);
}
}
};
struct C_NotifyUpdate : public Context {
JournalMetadata* journal_metadata;
Context *on_safe;
C_NotifyUpdate(JournalMetadata *_journal_metadata, Context *_on_safe = NULL)
: journal_metadata(_journal_metadata), on_safe(_on_safe) {
journal_metadata->m_async_op_tracker.start_op();
}
~C_NotifyUpdate() override {
journal_metadata->m_async_op_tracker.finish_op();
}
void finish(int r) override {
if (r == 0) {
journal_metadata->async_notify_update(on_safe);
return;
}
if (on_safe != NULL) {
on_safe->complete(r);
}
}
};
struct C_ImmutableMetadata : public Context {
JournalMetadata* journal_metadata;
Context *on_finish;
C_ImmutableMetadata(JournalMetadata *_journal_metadata, Context *_on_finish)
: journal_metadata(_journal_metadata), on_finish(_on_finish) {
std::lock_guard locker{journal_metadata->m_lock};
journal_metadata->m_async_op_tracker.start_op();
}
~C_ImmutableMetadata() override {
journal_metadata->m_async_op_tracker.finish_op();
}
void finish(int r) override {
journal_metadata->handle_immutable_metadata(r, on_finish);
}
};
struct C_Refresh : public Context {
JournalMetadata* journal_metadata;
uint64_t minimum_set;
uint64_t active_set;
RegisteredClients registered_clients;
C_Refresh(JournalMetadata *_journal_metadata)
: journal_metadata(_journal_metadata), minimum_set(0), active_set(0) {
std::lock_guard locker{journal_metadata->m_lock};
journal_metadata->m_async_op_tracker.start_op();
}
~C_Refresh() override {
journal_metadata->m_async_op_tracker.finish_op();
}
void finish(int r) override {
journal_metadata->handle_refresh_complete(this, r);
}
};
librados::IoCtx m_ioctx;
CephContext *m_cct = nullptr;
std::string m_oid;
std::string m_client_id;
Settings m_settings;
uint8_t m_order = 0;
uint8_t m_splay_width = 0;
int64_t m_pool_id = -1;
bool m_initialized = false;
ContextWQ *m_work_queue;
SafeTimer *m_timer;
ceph::mutex *m_timer_lock;
mutable ceph::mutex m_lock = ceph::make_mutex("JournalMetadata::m_lock");
uint64_t m_commit_tid = 0;
CommitTids m_pending_commit_tids;
Listeners m_listeners;
C_WatchCtx m_watch_ctx;
uint64_t m_watch_handle = 0;
uint64_t m_minimum_set = 0;
uint64_t m_active_set = 0;
RegisteredClients m_registered_clients;
Client m_client;
AllocatedEntryTids m_allocated_entry_tids;
size_t m_update_notifications = 0;
ceph::condition_variable m_update_cond;
size_t m_ignore_watch_notifies = 0;
size_t m_refreshes_in_progress = 0;
Contexts m_refresh_ctxs;
uint64_t m_commit_position_tid = 0;
ObjectSetPosition m_commit_position;
Context *m_commit_position_ctx = nullptr;
Context *m_commit_position_task_ctx = nullptr;
size_t m_flush_commits_in_progress = 0;
Contexts m_flush_commit_position_ctxs;
AsyncOpTracker m_async_op_tracker;
void handle_immutable_metadata(int r, Context *on_init);
void refresh(Context *on_finish);
void handle_refresh_complete(C_Refresh *refresh, int r);
void cancel_commit_task();
void schedule_commit_task();
void handle_commit_position_task();
void schedule_watch_reset();
void handle_watch_reset();
void handle_watch_notify(uint64_t notify_id, uint64_t cookie);
void handle_watch_error(int err);
void handle_notified(int r);
void schedule_laggy_clients_disconnect(Context *on_finish);
friend std::ostream &operator<<(std::ostream &os,
const JournalMetadata &journal_metadata);
};
std::ostream &operator<<(std::ostream &os,
const JournalMetadata::RegisteredClients &clients);
std::ostream &operator<<(std::ostream &os,
const JournalMetadata &journal_metadata);
} // namespace journal
#endif // CEPH_JOURNAL_JOURNAL_METADATA_H
| 11,486 | 29.550532 | 83 | h |
null | ceph-main/src/journal/JournalMetadataListener.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_JOURNAL_JOURNAL_METADATA_LISTENER_H
#define CEPH_JOURNAL_JOURNAL_METADATA_LISTENER_H
namespace journal {
class JournalMetadata;
struct JournalMetadataListener {
virtual ~JournalMetadataListener() {};
virtual void handle_update(JournalMetadata *) = 0;
};
} // namespace journal
#endif // CEPH_JOURNAL_JOURNAL_METADATA_LISTENER_H
| 758 | 23.483871 | 70 | h |
null | ceph-main/src/journal/JournalPlayer.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_JOURNAL_PLAYER_H
#define CEPH_JOURNAL_JOURNAL_PLAYER_H
#include "include/int_types.h"
#include "include/Context.h"
#include "include/rados/librados.hpp"
#include "common/AsyncOpTracker.h"
#include "common/Timer.h"
#include "journal/JournalMetadata.h"
#include "journal/ObjectPlayer.h"
#include "journal/Types.h"
#include "cls/journal/cls_journal_types.h"
#include <boost/none.hpp>
#include <boost/optional.hpp>
#include <map>
namespace journal {
class CacheManagerHandler;
class Entry;
class ReplayHandler;
class JournalPlayer {
public:
typedef cls::journal::ObjectPosition ObjectPosition;
typedef cls::journal::ObjectPositions ObjectPositions;
typedef cls::journal::ObjectSetPosition ObjectSetPosition;
JournalPlayer(librados::IoCtx &ioctx, std::string_view object_oid_prefix,
ceph::ref_t<JournalMetadata> journal_metadata,
ReplayHandler* replay_handler,
CacheManagerHandler *cache_manager_handler);
~JournalPlayer();
void prefetch();
void prefetch_and_watch(double interval);
void shut_down(Context *on_finish);
bool try_pop_front(Entry *entry, uint64_t *commit_tid);
private:
typedef std::set<uint8_t> PrefetchSplayOffsets;
typedef std::map<uint8_t, ceph::ref_t<ObjectPlayer>> SplayedObjectPlayers;
typedef std::map<uint8_t, ObjectPosition> SplayedObjectPositions;
typedef std::set<uint64_t> ObjectNumbers;
enum State {
STATE_INIT,
STATE_WAITCACHE,
STATE_PREFETCH,
STATE_PLAYBACK,
STATE_ERROR
};
enum WatchStep {
WATCH_STEP_FETCH_CURRENT,
WATCH_STEP_FETCH_FIRST,
WATCH_STEP_ASSERT_ACTIVE
};
struct C_Fetch : public Context {
JournalPlayer *player;
uint64_t object_num;
C_Fetch(JournalPlayer *p, uint64_t o) : player(p), object_num(o) {
player->m_async_op_tracker.start_op();
}
~C_Fetch() override {
player->m_async_op_tracker.finish_op();
}
void finish(int r) override {
player->handle_fetched(object_num, r);
}
};
struct C_Watch : public Context {
JournalPlayer *player;
uint64_t object_num;
C_Watch(JournalPlayer *player, uint64_t object_num)
: player(player), object_num(object_num) {
player->m_async_op_tracker.start_op();
}
~C_Watch() override {
player->m_async_op_tracker.finish_op();
}
void finish(int r) override {
player->handle_watch(object_num, r);
}
};
struct CacheRebalanceHandler : public journal::CacheRebalanceHandler {
JournalPlayer *player;
CacheRebalanceHandler(JournalPlayer *player) : player(player) {
}
void handle_cache_rebalanced(uint64_t new_cache_bytes) override {
player->handle_cache_rebalanced(new_cache_bytes);
}
};
librados::IoCtx m_ioctx;
CephContext *m_cct = nullptr;
std::string m_object_oid_prefix;
ceph::ref_t<JournalMetadata> m_journal_metadata;
ReplayHandler* m_replay_handler;
CacheManagerHandler *m_cache_manager_handler;
std::string m_cache_name;
CacheRebalanceHandler m_cache_rebalance_handler;
uint64_t m_max_fetch_bytes;
AsyncOpTracker m_async_op_tracker;
mutable ceph::mutex m_lock = ceph::make_mutex("JournalPlayer::m_lock");
State m_state = STATE_INIT;
uint8_t m_splay_offset = 0;
bool m_watch_enabled = false;
bool m_watch_scheduled = false;
double m_watch_interval = 0;
WatchStep m_watch_step = WATCH_STEP_FETCH_CURRENT;
bool m_watch_prune_active_tag = false;
bool m_shut_down = false;
bool m_handler_notified = false;
ObjectNumbers m_fetch_object_numbers;
PrefetchSplayOffsets m_prefetch_splay_offsets;
SplayedObjectPlayers m_object_players;
bool m_commit_position_valid = false;
ObjectPosition m_commit_position;
SplayedObjectPositions m_commit_positions;
uint64_t m_active_set = 0;
boost::optional<uint64_t> m_active_tag_tid = boost::none;
boost::optional<uint64_t> m_prune_tag_tid = boost::none;
void advance_splay_object();
bool is_object_set_ready() const;
bool verify_playback_ready();
void prune_tag(uint64_t tag_tid);
void prune_active_tag(const boost::optional<uint64_t>& tag_tid);
ceph::ref_t<ObjectPlayer> get_object_player() const;
ceph::ref_t<ObjectPlayer> get_object_player(uint64_t object_number) const;
bool remove_empty_object_player(const ceph::ref_t<ObjectPlayer> &object_player);
void process_state(uint64_t object_number, int r);
int process_prefetch(uint64_t object_number);
int process_playback(uint64_t object_number);
void fetch(uint64_t object_num);
void fetch(const ceph::ref_t<ObjectPlayer> &object_player);
void handle_fetched(uint64_t object_num, int r);
void refetch(bool immediate);
void schedule_watch(bool immediate);
void handle_watch(uint64_t object_num, int r);
void handle_watch_assert_active(int r);
void notify_entries_available();
void notify_complete(int r);
void handle_cache_rebalanced(uint64_t new_cache_bytes);
};
} // namespace journal
#endif // CEPH_JOURNAL_JOURNAL_PLAYER_H
| 5,090 | 27.762712 | 82 | h |
null | ceph-main/src/journal/JournalRecorder.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_JOURNAL_RECORDER_H
#define CEPH_JOURNAL_JOURNAL_RECORDER_H
#include "include/int_types.h"
#include "include/Context.h"
#include "include/rados/librados.hpp"
#include "common/ceph_mutex.h"
#include "common/containers.h"
#include "common/Timer.h"
#include "journal/Future.h"
#include "journal/FutureImpl.h"
#include "journal/JournalMetadata.h"
#include "journal/ObjectRecorder.h"
#include <map>
#include <string>
namespace journal {
class JournalRecorder {
public:
JournalRecorder(librados::IoCtx &ioctx, std::string_view object_oid_prefix,
ceph::ref_t<JournalMetadata> journal_metadata,
uint64_t max_in_flight_appends);
~JournalRecorder();
void shut_down(Context *on_safe);
void set_append_batch_options(int flush_interval, uint64_t flush_bytes,
double flush_age);
Future append(uint64_t tag_tid, const bufferlist &bl);
void flush(Context *on_safe);
ceph::ref_t<ObjectRecorder> get_object(uint8_t splay_offset);
private:
typedef std::map<uint8_t, ceph::ref_t<ObjectRecorder>> ObjectRecorderPtrs;
typedef std::vector<std::unique_lock<ceph::mutex>> Lockers;
struct Listener : public JournalMetadataListener {
JournalRecorder *journal_recorder;
Listener(JournalRecorder *_journal_recorder)
: journal_recorder(_journal_recorder) {}
void handle_update(JournalMetadata *) override {
journal_recorder->handle_update();
}
};
struct ObjectHandler : public ObjectRecorder::Handler {
JournalRecorder *journal_recorder;
ObjectHandler(JournalRecorder *_journal_recorder)
: journal_recorder(_journal_recorder) {
}
void closed(ObjectRecorder *object_recorder) override {
journal_recorder->handle_closed(object_recorder);
}
void overflow(ObjectRecorder *object_recorder) override {
journal_recorder->handle_overflow(object_recorder);
}
};
struct C_AdvanceObjectSet : public Context {
JournalRecorder *journal_recorder;
C_AdvanceObjectSet(JournalRecorder *_journal_recorder)
: journal_recorder(_journal_recorder) {
}
void finish(int r) override {
journal_recorder->handle_advance_object_set(r);
}
};
librados::IoCtx m_ioctx;
CephContext *m_cct = nullptr;
std::string m_object_oid_prefix;
ceph::ref_t<JournalMetadata> m_journal_metadata;
uint32_t m_flush_interval = 0;
uint64_t m_flush_bytes = 0;
double m_flush_age = 0;
uint64_t m_max_in_flight_appends;
Listener m_listener;
ObjectHandler m_object_handler;
ceph::mutex m_lock = ceph::make_mutex("JournalerRecorder::m_lock");
uint32_t m_in_flight_advance_sets = 0;
uint32_t m_in_flight_object_closes = 0;
uint64_t m_current_set;
ObjectRecorderPtrs m_object_ptrs;
ceph::containers::tiny_vector<ceph::mutex> m_object_locks;
ceph::ref_t<FutureImpl> m_prev_future;
Context *m_on_object_set_advanced = nullptr;
void open_object_set();
bool close_object_set(uint64_t active_set);
void advance_object_set();
void handle_advance_object_set(int r);
void close_and_advance_object_set(uint64_t object_set);
ceph::ref_t<ObjectRecorder> create_object_recorder(uint64_t object_number,
ceph::mutex* lock);
bool create_next_object_recorder(ceph::ref_t<ObjectRecorder> object_recorder);
void handle_update();
void handle_closed(ObjectRecorder *object_recorder);
void handle_overflow(ObjectRecorder *object_recorder);
Lockers lock_object_recorders();
};
} // namespace journal
#endif // CEPH_JOURNAL_JOURNAL_RECORDER_H
| 3,690 | 27.612403 | 80 | h |
null | ceph-main/src/journal/JournalTrimmer.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_JOURNAL_TRIMMER_H
#define CEPH_JOURNAL_JOURNAL_TRIMMER_H
#include "include/int_types.h"
#include "include/rados/librados.hpp"
#include "include/Context.h"
#include "common/AsyncOpTracker.h"
#include "journal/JournalMetadata.h"
#include "cls/journal/cls_journal_types.h"
#include <functional>
struct Context;
namespace journal {
class JournalTrimmer {
public:
typedef cls::journal::ObjectSetPosition ObjectSetPosition;
JournalTrimmer(librados::IoCtx &ioctx, const std::string &object_oid_prefix,
const ceph::ref_t<JournalMetadata> &journal_metadata);
~JournalTrimmer();
void shut_down(Context *on_finish);
void remove_objects(bool force, Context *on_finish);
void committed(uint64_t commit_tid);
private:
typedef std::function<Context*()> CreateContext;
struct MetadataListener : public JournalMetadataListener {
JournalTrimmer *journal_trimmer;
MetadataListener(JournalTrimmer *journal_trimmer)
: journal_trimmer(journal_trimmer) {
}
void handle_update(JournalMetadata *) override {
journal_trimmer->handle_metadata_updated();
}
};
struct C_CommitPositionSafe : public Context {
JournalTrimmer *journal_trimmer;
C_CommitPositionSafe(JournalTrimmer *_journal_trimmer)
: journal_trimmer(_journal_trimmer) {
journal_trimmer->m_async_op_tracker.start_op();
}
~C_CommitPositionSafe() override {
journal_trimmer->m_async_op_tracker.finish_op();
}
void finish(int r) override {
}
};
struct C_RemoveSet;
librados::IoCtx m_ioctx;
CephContext *m_cct;
std::string m_object_oid_prefix;
ceph::ref_t<JournalMetadata> m_journal_metadata;
MetadataListener m_metadata_listener;
AsyncOpTracker m_async_op_tracker;
ceph::mutex m_lock = ceph::make_mutex("JournalTrimmer::m_lock");
bool m_remove_set_pending;
uint64_t m_remove_set;
Context *m_remove_set_ctx;
bool m_shutdown = false;
CreateContext m_create_commit_position_safe_context = [this]() {
return new C_CommitPositionSafe(this);
};
void trim_objects(uint64_t minimum_set);
void remove_set(uint64_t object_set);
void handle_metadata_updated();
void handle_set_removed(int r, uint64_t object_set);
};
} // namespace journal
#endif // CEPH_JOURNAL_JOURNAL_TRIMMER_H
| 2,407 | 24.617021 | 78 | h |
null | ceph-main/src/journal/Journaler.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_JOURNALER_H
#define CEPH_JOURNAL_JOURNALER_H
#include "include/int_types.h"
#include "include/buffer_fwd.h"
#include "include/Context.h"
#include "include/rados/librados.hpp"
#include "journal/Future.h"
#include "journal/JournalMetadataListener.h"
#include "cls/journal/cls_journal_types.h"
#include "common/Timer.h"
#include <list>
#include <map>
#include <string>
#include "include/ceph_assert.h"
class ContextWQ;
class ThreadPool;
namespace journal {
struct CacheManagerHandler;
class JournalTrimmer;
class ReplayEntry;
class ReplayHandler;
class Settings;
class Journaler {
public:
struct Threads {
Threads(CephContext *cct);
~Threads();
ThreadPool *thread_pool = nullptr;
ContextWQ *work_queue = nullptr;
SafeTimer *timer;
ceph::mutex timer_lock = ceph::make_mutex("Journaler::timer_lock");
};
typedef cls::journal::Tag Tag;
typedef std::list<cls::journal::Tag> Tags;
typedef std::set<cls::journal::Client> RegisteredClients;
static std::string header_oid(const std::string &journal_id);
static std::string object_oid_prefix(int pool_id,
const std::string &journal_id);
Journaler(librados::IoCtx &header_ioctx, const std::string &journal_id,
const std::string &client_id, const Settings &settings,
CacheManagerHandler *cache_manager_handler);
Journaler(ContextWQ *work_queue, SafeTimer *timer, ceph::mutex *timer_lock,
librados::IoCtx &header_ioctx, const std::string &journal_id,
const std::string &client_id, const Settings &settings,
CacheManagerHandler *cache_manager_handler);
~Journaler();
void exists(Context *on_finish) const;
void create(uint8_t order, uint8_t splay_width, int64_t pool_id, Context *ctx);
void remove(bool force, Context *on_finish);
void init(Context *on_init);
void shut_down();
void shut_down(Context *on_finish);
bool is_initialized() const;
void get_immutable_metadata(uint8_t *order, uint8_t *splay_width,
int64_t *pool_id, Context *on_finish);
void get_mutable_metadata(uint64_t *minimum_set, uint64_t *active_set,
RegisteredClients *clients, Context *on_finish);
void add_listener(JournalMetadataListener *listener);
void remove_listener(JournalMetadataListener *listener);
int register_client(const bufferlist &data);
void register_client(const bufferlist &data, Context *on_finish);
int unregister_client();
void unregister_client(Context *on_finish);
void update_client(const bufferlist &data, Context *on_finish);
void get_client(const std::string &client_id, cls::journal::Client *client,
Context *on_finish);
int get_cached_client(const std::string &client_id,
cls::journal::Client *client);
void flush_commit_position(Context *on_safe);
void allocate_tag(const bufferlist &data, cls::journal::Tag *tag,
Context *on_finish);
void allocate_tag(uint64_t tag_class, const bufferlist &data,
cls::journal::Tag *tag, Context *on_finish);
void get_tag(uint64_t tag_tid, Tag *tag, Context *on_finish);
void get_tags(uint64_t tag_class, Tags *tags, Context *on_finish);
void get_tags(uint64_t start_after_tag_tid, uint64_t tag_class, Tags *tags,
Context *on_finish);
void start_replay(ReplayHandler* replay_handler);
void start_live_replay(ReplayHandler* replay_handler, double interval);
bool try_pop_front(ReplayEntry *replay_entry, uint64_t *tag_tid = nullptr);
void stop_replay();
void stop_replay(Context *on_finish);
uint64_t get_max_append_size() const;
void start_append(uint64_t max_in_flight_appends);
void set_append_batch_options(int flush_interval, uint64_t flush_bytes,
double flush_age);
Future append(uint64_t tag_tid, const bufferlist &bl);
void flush_append(Context *on_safe);
void stop_append(Context *on_safe);
void committed(const ReplayEntry &replay_entry);
void committed(const Future &future);
void get_metadata(uint8_t *order, uint8_t *splay_width, int64_t *pool_id);
private:
struct C_InitJournaler : public Context {
Journaler *journaler;
Context *on_safe;
C_InitJournaler(Journaler *_journaler, Context *_on_safe)
: journaler(_journaler), on_safe(_on_safe) {
}
void finish(int r) override {
if (r == 0) {
r = journaler->init_complete();
}
on_safe->complete(r);
}
};
Threads *m_threads = nullptr;
mutable librados::IoCtx m_header_ioctx;
librados::IoCtx m_data_ioctx;
CephContext *m_cct;
std::string m_client_id;
CacheManagerHandler *m_cache_manager_handler;
std::string m_header_oid;
std::string m_object_oid_prefix;
bool m_initialized = false;
ceph::ref_t<class JournalMetadata> m_metadata;
std::unique_ptr<class JournalPlayer> m_player;
std::unique_ptr<class JournalRecorder> m_recorder;
JournalTrimmer *m_trimmer = nullptr;
void set_up(ContextWQ *work_queue, SafeTimer *timer, ceph::mutex *timer_lock,
librados::IoCtx &header_ioctx, const std::string &journal_id,
const Settings &settings);
int init_complete();
void create_player(ReplayHandler* replay_handler);
friend std::ostream &operator<<(std::ostream &os,
const Journaler &journaler);
};
std::ostream &operator<<(std::ostream &os,
const Journaler &journaler);
} // namespace journal
#endif // CEPH_JOURNAL_JOURNALER_H
| 5,545 | 31.432749 | 81 | h |
null | ceph-main/src/journal/ObjectPlayer.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_OBJECT_PLAYER_H
#define CEPH_JOURNAL_OBJECT_PLAYER_H
#include "include/Context.h"
#include "include/interval_set.h"
#include "include/rados/librados.hpp"
#include "common/ceph_mutex.h"
#include "common/Timer.h"
#include "common/RefCountedObj.h"
#include "journal/Entry.h"
#include <list>
#include <string>
#include <boost/noncopyable.hpp>
#include <boost/unordered_map.hpp>
#include "include/ceph_assert.h"
namespace journal {
class ObjectPlayer : public RefCountedObject {
public:
typedef std::list<Entry> Entries;
typedef interval_set<uint64_t> InvalidRanges;
enum RefetchState {
REFETCH_STATE_NONE,
REFETCH_STATE_REQUIRED,
REFETCH_STATE_IMMEDIATE
};
inline const std::string &get_oid() const {
return m_oid;
}
inline uint64_t get_object_number() const {
return m_object_num;
}
void fetch(Context *on_finish);
void watch(Context *on_fetch, double interval);
void unwatch();
void front(Entry *entry) const;
void pop_front();
inline bool empty() const {
std::lock_guard locker{m_lock};
return m_entries.empty();
}
inline void get_entries(Entries *entries) {
std::lock_guard locker{m_lock};
*entries = m_entries;
}
inline void get_invalid_ranges(InvalidRanges *invalid_ranges) {
std::lock_guard locker{m_lock};
*invalid_ranges = m_invalid_ranges;
}
inline bool refetch_required() const {
return (get_refetch_state() != REFETCH_STATE_NONE);
}
inline RefetchState get_refetch_state() const {
return m_refetch_state;
}
inline void set_refetch_state(RefetchState refetch_state) {
m_refetch_state = refetch_state;
}
inline void set_max_fetch_bytes(uint64_t max_fetch_bytes) {
std::lock_guard locker{m_lock};
m_max_fetch_bytes = max_fetch_bytes;
}
private:
FRIEND_MAKE_REF(ObjectPlayer);
ObjectPlayer(librados::IoCtx &ioctx, const std::string& object_oid_prefix,
uint64_t object_num, SafeTimer &timer, ceph::mutex &timer_lock,
uint8_t order, uint64_t max_fetch_bytes);
~ObjectPlayer() override;
typedef std::pair<uint64_t, uint64_t> EntryKey;
typedef boost::unordered_map<EntryKey, Entries::iterator> EntryKeys;
struct C_Fetch : public Context {
ceph::ref_t<ObjectPlayer> object_player;
Context *on_finish;
bufferlist read_bl;
C_Fetch(ObjectPlayer *o, Context *ctx) : object_player(o), on_finish(ctx) {
}
void finish(int r) override;
};
struct C_WatchFetch : public Context {
ceph::ref_t<ObjectPlayer> object_player;
C_WatchFetch(ObjectPlayer *o) : object_player(o) {
}
void finish(int r) override;
};
librados::IoCtx m_ioctx;
uint64_t m_object_num;
std::string m_oid;
CephContext *m_cct = nullptr;
SafeTimer &m_timer;
ceph::mutex &m_timer_lock;
uint8_t m_order;
uint64_t m_max_fetch_bytes;
double m_watch_interval = 0;
Context *m_watch_task = nullptr;
mutable ceph::mutex m_lock;
bool m_fetch_in_progress = false;
bufferlist m_read_bl;
uint32_t m_read_off = 0;
uint32_t m_read_bl_off = 0;
Entries m_entries;
EntryKeys m_entry_keys;
InvalidRanges m_invalid_ranges;
Context *m_watch_ctx = nullptr;
bool m_unwatched = false;
RefetchState m_refetch_state = REFETCH_STATE_IMMEDIATE;
int handle_fetch_complete(int r, const bufferlist &bl, bool *refetch);
void clear_invalid_range(uint32_t off, uint32_t len);
void schedule_watch();
bool cancel_watch();
void handle_watch_task();
void handle_watch_fetched(int r);
};
} // namespace journal
#endif // CEPH_JOURNAL_OBJECT_PLAYER_H
| 3,672 | 24.866197 | 79 | h |
null | ceph-main/src/journal/ObjectRecorder.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_OBJECT_RECORDER_H
#define CEPH_JOURNAL_OBJECT_RECORDER_H
#include "include/utime.h"
#include "include/Context.h"
#include "include/rados/librados.hpp"
#include "common/ceph_mutex.h"
#include "common/RefCountedObj.h"
#include "common/WorkQueue.h"
#include "common/Timer.h"
#include "journal/FutureImpl.h"
#include <list>
#include <map>
#include <set>
#include <boost/noncopyable.hpp>
#include "include/ceph_assert.h"
namespace journal {
class ObjectRecorder;
typedef std::pair<ceph::ref_t<FutureImpl>, bufferlist> AppendBuffer;
typedef std::list<AppendBuffer> AppendBuffers;
class ObjectRecorder : public RefCountedObject, boost::noncopyable {
public:
struct Handler {
virtual ~Handler() {
}
virtual void closed(ObjectRecorder *object_recorder) = 0;
virtual void overflow(ObjectRecorder *object_recorder) = 0;
};
void set_append_batch_options(int flush_interval, uint64_t flush_bytes,
double flush_age);
inline uint64_t get_object_number() const {
return m_object_number;
}
inline const std::string &get_oid() const {
return m_oid;
}
bool append(AppendBuffers &&append_buffers);
void flush(Context *on_safe);
void flush(const ceph::ref_t<FutureImpl> &future);
void claim_append_buffers(AppendBuffers *append_buffers);
bool is_closed() const {
ceph_assert(ceph_mutex_is_locked(*m_lock));
return (m_object_closed && m_in_flight_appends.empty());
}
bool close();
inline CephContext *cct() const {
return m_cct;
}
inline size_t get_pending_appends() const {
std::lock_guard locker{*m_lock};
return m_pending_buffers.size();
}
private:
FRIEND_MAKE_REF(ObjectRecorder);
ObjectRecorder(librados::IoCtx &ioctx, std::string_view oid,
uint64_t object_number, ceph::mutex* lock,
ContextWQ *work_queue, Handler *handler, uint8_t order,
int32_t max_in_flight_appends);
~ObjectRecorder() override;
typedef std::set<uint64_t> InFlightTids;
typedef std::map<uint64_t, AppendBuffers> InFlightAppends;
struct FlushHandler : public FutureImpl::FlushHandler {
ceph::ref_t<ObjectRecorder> object_recorder;
virtual void flush(const ceph::ref_t<FutureImpl> &future) override {
object_recorder->flush(future);
}
FlushHandler(ceph::ref_t<ObjectRecorder> o) : object_recorder(std::move(o)) {}
};
struct C_AppendFlush : public Context {
ceph::ref_t<ObjectRecorder> object_recorder;
uint64_t tid;
C_AppendFlush(ceph::ref_t<ObjectRecorder> o, uint64_t _tid)
: object_recorder(std::move(o)), tid(_tid) {
}
void finish(int r) override {
object_recorder->handle_append_flushed(tid, r);
}
};
librados::IoCtx m_ioctx;
std::string m_oid;
uint64_t m_object_number;
CephContext *m_cct = nullptr;
ContextWQ *m_op_work_queue;
Handler *m_handler;
uint8_t m_order;
uint64_t m_soft_max_size;
uint32_t m_flush_interval = 0;
uint64_t m_flush_bytes = 0;
double m_flush_age = 0;
int32_t m_max_in_flight_appends;
bool m_compat_mode;
/* So that ObjectRecorder::FlushHandler doesn't create a circular reference: */
std::weak_ptr<FlushHandler> m_flush_handler;
auto get_flush_handler() {
auto h = m_flush_handler.lock();
if (!h) {
h = std::make_shared<FlushHandler>(this);
m_flush_handler = h;
}
return h;
}
mutable ceph::mutex* m_lock;
AppendBuffers m_pending_buffers;
uint64_t m_pending_bytes = 0;
utime_t m_last_flush_time;
uint64_t m_append_tid = 0;
InFlightTids m_in_flight_tids;
InFlightAppends m_in_flight_appends;
uint64_t m_object_bytes = 0;
bool m_overflowed = false;
bool m_object_closed = false;
bool m_object_closed_notify = false;
bufferlist m_prefetch_bl;
uint32_t m_in_flight_callbacks = 0;
ceph::condition_variable m_in_flight_callbacks_cond;
uint64_t m_in_flight_bytes = 0;
bool send_appends(bool force, ceph::ref_t<FutureImpl> flush_sentinel);
void handle_append_flushed(uint64_t tid, int r);
void append_overflowed();
void wake_up_flushes();
void notify_handler_unlock(std::unique_lock<ceph::mutex>& locker,
bool notify_overflowed);
};
} // namespace journal
#endif // CEPH_JOURNAL_OBJECT_RECORDER_H
| 4,394 | 26.298137 | 82 | h |
null | ceph-main/src/journal/Settings.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_SETTINGS_H
#define CEPH_JOURNAL_SETTINGS_H
#include "include/int_types.h"
namespace journal {
struct Settings {
double commit_interval = 5; ///< commit position throttle (in secs)
uint64_t max_payload_bytes = 0; ///< 0 implies object size limit
int max_concurrent_object_sets = 0; ///< 0 implies no limit
std::set<std::string> ignored_laggy_clients;
///< clients that mustn't be disconnected
};
} // namespace journal
#endif // # CEPH_JOURNAL_SETTINGS_H
| 637 | 28 | 79 | h |
null | ceph-main/src/journal/Types.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_TYPES_H
#define CEPH_JOURNAL_TYPES_H
namespace journal {
struct CacheRebalanceHandler {
virtual ~CacheRebalanceHandler() {
}
virtual void handle_cache_rebalanced(uint64_t new_cache_bytes) = 0;
};
struct CacheManagerHandler {
virtual ~CacheManagerHandler() {
}
virtual void register_cache(const std::string &cache_name,
uint64_t min_size, uint64_t max_size,
CacheRebalanceHandler* handler) = 0;
virtual void unregister_cache(const std::string &cache_name) = 0;
};
} // namespace journal
#endif // # CEPH_JOURNAL_TYPES_H
| 720 | 23.862069 | 70 | h |
null | ceph-main/src/journal/Utils.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_JOURNAL_UTILS_H
#define CEPH_JOURNAL_UTILS_H
#include "include/int_types.h"
#include "include/Context.h"
#include "include/rados/librados.hpp"
#include <string>
namespace journal {
namespace utils {
namespace detail {
template <typename M>
struct C_AsyncCallback : public Context {
M journal_metadata;
Context *on_finish;
C_AsyncCallback(M journal_metadata, Context *on_finish)
: journal_metadata(journal_metadata), on_finish(on_finish) {
}
void finish(int r) override {
journal_metadata->queue(on_finish, r);
}
};
} // namespace detail
template <typename T, void(T::*MF)(int)>
void rados_state_callback(rados_completion_t c, void *arg) {
T *obj = reinterpret_cast<T*>(arg);
int r = rados_aio_get_return_value(c);
(obj->*MF)(r);
}
std::string get_object_name(const std::string &prefix, uint64_t number);
std::string unique_lock_name(const std::string &name, void *address);
void rados_ctx_callback(rados_completion_t c, void *arg);
template <typename M>
Context *create_async_context_callback(M journal_metadata, Context *on_finish) {
// use async callback to acquire a clean lock context
return new detail::C_AsyncCallback<M>(journal_metadata, on_finish);
}
} // namespace utils
} // namespace journal
#endif // CEPH_JOURNAL_UTILS_H
| 1,389 | 24.272727 | 80 | h |
null | ceph-main/src/json_spirit/json_spirit_error_position.h | #ifndef JSON_SPIRIT_ERROR_POSITION
#define JSON_SPIRIT_ERROR_POSITION
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <string>
namespace json_spirit
{
// An Error_position exception is thrown by the "read_or_throw" functions below on finding an error.
// Note the "read_or_throw" functions are around 3 times slower than the standard functions "read"
// functions that return a bool.
//
struct Error_position
{
Error_position();
Error_position( unsigned int line, unsigned int column, const std::string& reason );
bool operator==( const Error_position& lhs ) const;
unsigned int line_;
unsigned int column_;
std::string reason_;
};
inline Error_position::Error_position()
: line_( 0 )
, column_( 0 )
{
}
inline Error_position::Error_position( unsigned int line, unsigned int column, const std::string& reason )
: line_( line )
, column_( column )
, reason_( reason )
{
}
inline bool Error_position::operator==( const Error_position& lhs ) const
{
if( this == &lhs ) return true;
return ( reason_ == lhs.reason_ ) &&
( line_ == lhs.line_ ) &&
( column_ == lhs.column_ );
}
}
#endif
| 1,461 | 25.581818 | 110 | h |
null | ceph-main/src/json_spirit/json_spirit_reader.h | #ifndef JSON_SPIRIT_READER
#define JSON_SPIRIT_READER
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include "json_spirit_value.h"
#include "json_spirit_error_position.h"
#include <iostream>
namespace json_spirit
{
// functions to reads a JSON values
#ifdef JSON_SPIRIT_VALUE_ENABLED
bool read( const std::string& s, Value& value );
bool read( std::istream& is, Value& value );
bool read( std::string::const_iterator& begin, std::string::const_iterator end, Value& value );
void read_or_throw( const std::string& s, Value& value );
void read_or_throw( std::istream& is, Value& value );
void read_or_throw( std::string::const_iterator& begin, std::string::const_iterator end, Value& value );
#endif
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
bool read( const std::wstring& s, wValue& value );
bool read( std::wistream& is, wValue& value );
bool read( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value );
void read_or_throw( const std::wstring& s, wValue& value );
void read_or_throw( std::wistream& is, wValue& value );
void read_or_throw( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value );
#endif
#ifdef JSON_SPIRIT_MVALUE_ENABLED
bool read( const std::string& s, mValue& value );
bool read( std::istream& is, mValue& value );
bool read( std::string::const_iterator& begin, std::string::const_iterator end, mValue& value );
void read_or_throw( const std::string& s, mValue& value );
void read_or_throw( std::istream& is, mValue& value );
void read_or_throw( std::string::const_iterator& begin, std::string::const_iterator end, mValue& value );
#endif
#if defined( JSON_SPIRIT_WMVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
bool read( const std::wstring& s, wmValue& value );
bool read( std::wistream& is, wmValue& value );
bool read( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wmValue& value );
void read_or_throw( const std::wstring& s, wmValue& value );
void read_or_throw( std::wistream& is, wmValue& value );
void read_or_throw( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wmValue& value );
#endif
}
#endif
| 2,509 | 38.84127 | 112 | h |
null | ceph-main/src/json_spirit/json_spirit_reader_template.h | #ifndef JSON_SPIRIT_READER_TEMPLATE
#define JSON_SPIRIT_READER_TEMPLATE
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include "json_spirit_value.h"
#include "json_spirit_error_position.h"
#include "common/utf8.h"
#define BOOST_SPIRIT_THREADSAFE // uncomment for multithreaded use, requires linking to boost.thread
#include <boost/bind/bind.hpp>
#include <boost/function.hpp>
#include <boost/version.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_confix.hpp>
#include <boost/spirit/include/classic_escape_char.hpp>
#include <boost/spirit/include/classic_multi_pass.hpp>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include "include/ceph_assert.h"
namespace json_spirit
{
namespace spirit_namespace = boost::spirit::classic;
const spirit_namespace::int_parser < boost::int64_t > int64_p = spirit_namespace::int_parser < boost::int64_t >();
const spirit_namespace::uint_parser< boost::uint64_t > uint64_p = spirit_namespace::uint_parser< boost::uint64_t >();
template< class Iter_type >
bool is_eq( Iter_type first, Iter_type last, const char* c_str )
{
for( Iter_type i = first; i != last; ++i, ++c_str )
{
if( *c_str == 0 ) return false;
if( *i != *c_str ) return false;
}
return true;
}
template< class Char_type >
Char_type hex_to_num( const Char_type c )
{
if( ( c >= '0' ) && ( c <= '9' ) ) return c - '0';
if( ( c >= 'a' ) && ( c <= 'f' ) ) return c - 'a' + 10;
if( ( c >= 'A' ) && ( c <= 'F' ) ) return c - 'A' + 10;
return 0;
}
template< class Char_type, class Iter_type >
Char_type hex_str_to_char( Iter_type& begin )
{
const Char_type c1( *( ++begin ) );
const Char_type c2( *( ++begin ) );
return ( hex_to_num( c1 ) << 4 ) + hex_to_num( c2 );
}
template< class String_type, class Iter_type >
String_type unicode_str_to_utf8( Iter_type& begin );
template<>
std::string unicode_str_to_utf8( std::string::const_iterator & begin )
{
typedef std::string::value_type Char_type;
const Char_type c1( *( ++begin ) );
const Char_type c2( *( ++begin ) );
const Char_type c3( *( ++begin ) );
const Char_type c4( *( ++begin ) );
unsigned long uc = ( hex_to_num( c1 ) << 12 ) +
( hex_to_num( c2 ) << 8 ) +
( hex_to_num( c3 ) << 4 ) +
hex_to_num( c4 );
unsigned char buf[7]; // MAX_UTF8_SZ is 6 (see src/common/utf8.c)
int r = encode_utf8(uc, buf);
if (r >= 0) {
return std::string(reinterpret_cast<char *>(buf), r);
}
return std::string("_");
}
template< class String_type >
void append_esc_char_and_incr_iter( String_type& s,
typename String_type::const_iterator& begin,
typename String_type::const_iterator end )
{
typedef typename String_type::value_type Char_type;
const Char_type c2( *begin );
switch( c2 )
{
case 't': s += '\t'; break;
case 'b': s += '\b'; break;
case 'f': s += '\f'; break;
case 'n': s += '\n'; break;
case 'r': s += '\r'; break;
case '\\': s += '\\'; break;
case '/': s += '/'; break;
case '"': s += '"'; break;
case 'x':
{
if( end - begin >= 3 ) // expecting "xHH..."
{
s += hex_str_to_char< Char_type >( begin );
}
break;
}
case 'u':
{
if( end - begin >= 5 ) // expecting "uHHHH..."
{
s += unicode_str_to_utf8< String_type >( begin );
}
break;
}
}
}
template< class String_type >
String_type substitute_esc_chars( typename String_type::const_iterator begin,
typename String_type::const_iterator end )
{
typedef typename String_type::const_iterator Iter_type;
if( end - begin < 2 ) return String_type( begin, end );
String_type result;
result.reserve( end - begin );
const Iter_type end_minus_1( end - 1 );
Iter_type substr_start = begin;
Iter_type i = begin;
for( ; i < end_minus_1; ++i )
{
if( *i == '\\' )
{
result.append( substr_start, i );
++i; // skip the '\'
append_esc_char_and_incr_iter( result, i, end );
substr_start = i + 1;
}
}
result.append( substr_start, end );
return result;
}
template< class String_type >
String_type get_str_( typename String_type::const_iterator begin,
typename String_type::const_iterator end )
{
ceph_assert( end - begin >= 2 );
typedef typename String_type::const_iterator Iter_type;
Iter_type str_without_quotes( ++begin );
Iter_type end_without_quotes( --end );
return substitute_esc_chars< String_type >( str_without_quotes, end_without_quotes );
}
inline std::string get_str( std::string::const_iterator begin, std::string::const_iterator end )
{
return get_str_< std::string >( begin, end );
}
// Need this guard else it tries to instantiate unicode_str_to_utf8 with a
// std::wstring, which isn't presently implemented
#if defined( JSON_SPIRIT_WMVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
inline std::wstring get_str( std::wstring::const_iterator begin, std::wstring::const_iterator end )
{
return get_str_< std::wstring >( begin, end );
}
#endif
template< class String_type, class Iter_type >
String_type get_str( Iter_type begin, Iter_type end )
{
const String_type tmp( begin, end ); // convert multipass iterators to string iterators
return get_str( tmp.begin(), tmp.end() );
}
using namespace boost::placeholders;
// this class's methods get called by the spirit parse resulting
// in the creation of a JSON object or array
//
// NB Iter_type could be a std::string iterator, wstring iterator, a position iterator or a multipass iterator
//
template< class Value_type, class Iter_type >
class Semantic_actions
{
public:
typedef typename Value_type::Config_type Config_type;
typedef typename Config_type::String_type String_type;
typedef typename Config_type::Object_type Object_type;
typedef typename Config_type::Array_type Array_type;
typedef typename String_type::value_type Char_type;
Semantic_actions( Value_type& value )
: value_( value )
, current_p_( 0 )
{
}
void begin_obj( Char_type c )
{
ceph_assert( c == '{' );
begin_compound< Object_type >();
}
void end_obj( Char_type c )
{
ceph_assert( c == '}' );
end_compound();
}
void begin_array( Char_type c )
{
ceph_assert( c == '[' );
begin_compound< Array_type >();
}
void end_array( Char_type c )
{
ceph_assert( c == ']' );
end_compound();
}
void new_name( Iter_type begin, Iter_type end )
{
ceph_assert( current_p_->type() == obj_type );
name_ = get_str< String_type >( begin, end );
}
void new_str( Iter_type begin, Iter_type end )
{
add_to_current( get_str< String_type >( begin, end ) );
}
void new_true( Iter_type begin, Iter_type end )
{
ceph_assert( is_eq( begin, end, "true" ) );
add_to_current( true );
}
void new_false( Iter_type begin, Iter_type end )
{
ceph_assert( is_eq( begin, end, "false" ) );
add_to_current( false );
}
void new_null( Iter_type begin, Iter_type end )
{
ceph_assert( is_eq( begin, end, "null" ) );
add_to_current( Value_type() );
}
void new_int( boost::int64_t i )
{
add_to_current( i );
}
void new_uint64( boost::uint64_t ui )
{
add_to_current( ui );
}
void new_real( double d )
{
add_to_current( d );
}
private:
Semantic_actions& operator=( const Semantic_actions& );
// to prevent "assignment operator could not be generated" warning
Value_type* add_first( const Value_type& value )
{
ceph_assert( current_p_ == 0 );
value_ = value;
current_p_ = &value_;
return current_p_;
}
template< class Array_or_obj >
void begin_compound()
{
if( current_p_ == 0 )
{
add_first( Array_or_obj() );
}
else
{
stack_.push_back( current_p_ );
Array_or_obj new_array_or_obj; // avoid copy by building new array or object in place
current_p_ = add_to_current( new_array_or_obj );
}
}
void end_compound()
{
if( current_p_ != &value_ )
{
current_p_ = stack_.back();
stack_.pop_back();
}
}
Value_type* add_to_current( const Value_type& value )
{
if( current_p_ == 0 )
{
return add_first( value );
}
else if( current_p_->type() == array_type )
{
current_p_->get_array().push_back( value );
return ¤t_p_->get_array().back();
}
ceph_assert( current_p_->type() == obj_type );
return &Config_type::add( current_p_->get_obj(), name_, value );
}
Value_type& value_; // this is the object or array that is being created
Value_type* current_p_; // the child object or array that is currently being constructed
std::vector< Value_type* > stack_; // previous child objects and arrays
String_type name_; // of current name/value pair
};
template< typename Iter_type >
void throw_error( spirit_namespace::position_iterator< Iter_type > i, const std::string& reason )
{
throw Error_position( i.get_position().line, i.get_position().column, reason );
}
template< typename Iter_type >
void throw_error( Iter_type i, const std::string& reason )
{
throw reason;
}
// the spirit grammar
//
template< class Value_type, class Iter_type >
class Json_grammer : public spirit_namespace::grammar< Json_grammer< Value_type, Iter_type > >
{
public:
typedef Semantic_actions< Value_type, Iter_type > Semantic_actions_t;
Json_grammer( Semantic_actions_t& semantic_actions )
: actions_( semantic_actions )
{
}
static void throw_not_value( Iter_type begin, Iter_type end )
{
throw_error( begin, "not a value" );
}
static void throw_not_array( Iter_type begin, Iter_type end )
{
throw_error( begin, "not an array" );
}
static void throw_not_object( Iter_type begin, Iter_type end )
{
throw_error( begin, "not an object" );
}
static void throw_not_pair( Iter_type begin, Iter_type end )
{
throw_error( begin, "not a pair" );
}
static void throw_not_colon( Iter_type begin, Iter_type end )
{
throw_error( begin, "no colon in pair" );
}
static void throw_not_string( Iter_type begin, Iter_type end )
{
throw_error( begin, "not a string" );
}
template< typename ScannerT >
class definition
{
public:
definition( const Json_grammer& self )
{
using namespace spirit_namespace;
typedef typename Value_type::String_type::value_type Char_type;
// first we convert the semantic action class methods to functors with the
// parameter signature expected by spirit
typedef boost::function< void( Char_type ) > Char_action;
typedef boost::function< void( Iter_type, Iter_type ) > Str_action;
typedef boost::function< void( double ) > Real_action;
typedef boost::function< void( boost::int64_t ) > Int_action;
typedef boost::function< void( boost::uint64_t ) > Uint64_action;
Char_action begin_obj ( boost::bind( &Semantic_actions_t::begin_obj, &self.actions_, _1 ) );
Char_action end_obj ( boost::bind( &Semantic_actions_t::end_obj, &self.actions_, _1 ) );
Char_action begin_array( boost::bind( &Semantic_actions_t::begin_array, &self.actions_, _1 ) );
Char_action end_array ( boost::bind( &Semantic_actions_t::end_array, &self.actions_, _1 ) );
Str_action new_name ( boost::bind( &Semantic_actions_t::new_name, &self.actions_, _1, _2 ) );
Str_action new_str ( boost::bind( &Semantic_actions_t::new_str, &self.actions_, _1, _2 ) );
Str_action new_true ( boost::bind( &Semantic_actions_t::new_true, &self.actions_, _1, _2 ) );
Str_action new_false ( boost::bind( &Semantic_actions_t::new_false, &self.actions_, _1, _2 ) );
Str_action new_null ( boost::bind( &Semantic_actions_t::new_null, &self.actions_, _1, _2 ) );
Real_action new_real ( boost::bind( &Semantic_actions_t::new_real, &self.actions_, _1 ) );
Int_action new_int ( boost::bind( &Semantic_actions_t::new_int, &self.actions_, _1 ) );
Uint64_action new_uint64 ( boost::bind( &Semantic_actions_t::new_uint64, &self.actions_, _1 ) );
// actual grammar
json_
= value_ | eps_p[ &throw_not_value ]
;
value_
= string_[ new_str ]
| number_
| object_
| array_
| str_p( "true" ) [ new_true ]
| str_p( "false" )[ new_false ]
| str_p( "null" ) [ new_null ]
;
object_
= ch_p('{')[ begin_obj ]
>> !members_
>> ( ch_p('}')[ end_obj ] | eps_p[ &throw_not_object ] )
;
members_
= pair_ >> *( ',' >> pair_ | ch_p(',') )
;
pair_
= string_[ new_name ]
>> ( ':' | eps_p[ &throw_not_colon ] )
>> ( value_ | eps_p[ &throw_not_value ] )
;
array_
= ch_p('[')[ begin_array ]
>> !elements_
>> ( ch_p(']')[ end_array ] | eps_p[ &throw_not_array ] )
;
elements_
= value_ >> *( ',' >> value_ | ch_p(',') )
;
string_
= lexeme_d // this causes white space inside a string to be retained
[
confix_p
(
'"',
*lex_escape_ch_p,
'"'
)
]
;
number_
= strict_real_p[ new_real ]
| int64_p [ new_int ]
| uint64_p [ new_uint64 ]
;
}
spirit_namespace::rule< ScannerT > json_, object_, members_, pair_, array_, elements_, value_, string_, number_;
const spirit_namespace::rule< ScannerT >& start() const { return json_; }
};
private:
Json_grammer& operator=( const Json_grammer& ); // to prevent "assignment operator could not be generated" warning
Semantic_actions_t& actions_;
};
template< class Iter_type, class Value_type >
void add_posn_iter_and_read_range_or_throw( Iter_type begin, Iter_type end, Value_type& value )
{
typedef spirit_namespace::position_iterator< Iter_type > Posn_iter_t;
const Posn_iter_t posn_begin( begin, end );
const Posn_iter_t posn_end( end, end );
read_range_or_throw( posn_begin, posn_end, value );
}
template< class Istream_type >
struct Multi_pass_iters
{
typedef typename Istream_type::char_type Char_type;
typedef std::istream_iterator< Char_type, Char_type > istream_iter;
typedef spirit_namespace::multi_pass< istream_iter > Mp_iter;
Multi_pass_iters( Istream_type& is )
{
is.unsetf( std::ios::skipws );
begin_ = spirit_namespace::make_multi_pass( istream_iter( is ) );
end_ = spirit_namespace::make_multi_pass( istream_iter() );
}
Mp_iter begin_;
Mp_iter end_;
};
// reads a JSON Value from a pair of input iterators throwing an exception on invalid input, e.g.
//
// string::const_iterator start = str.begin();
// const string::const_iterator next = read_range_or_throw( str.begin(), str.end(), value );
//
// The iterator 'next' will point to the character past the
// last one read.
//
template< class Iter_type, class Value_type >
Iter_type read_range_or_throw( Iter_type begin, Iter_type end, Value_type& value )
{
Semantic_actions< Value_type, Iter_type > semantic_actions( value );
const spirit_namespace::parse_info< Iter_type > info =
spirit_namespace::parse( begin, end,
Json_grammer< Value_type, Iter_type >( semantic_actions ),
spirit_namespace::space_p );
if( !info.hit )
{
ceph_assert( false ); // in theory exception should already have been thrown
throw_error( info.stop, "error" );
}
return info.stop;
}
// reads a JSON Value from a pair of input iterators, e.g.
//
// string::const_iterator start = str.begin();
// const bool success = read_string( start, str.end(), value );
//
// The iterator 'start' will point to the character past the
// last one read.
//
template< class Iter_type, class Value_type >
bool read_range( Iter_type& begin, Iter_type end, Value_type& value )
{
try
{
begin = read_range_or_throw( begin, end, value );
return true;
}
catch( ... )
{
return false;
}
}
// reads a JSON Value from a string, e.g.
//
// const bool success = read_string( str, value );
//
template< class String_type, class Value_type >
bool read_string( const String_type& s, Value_type& value )
{
typename String_type::const_iterator begin = s.begin();
return read_range( begin, s.end(), value );
}
// reads a JSON Value from a string throwing an exception on invalid input, e.g.
//
// read_string_or_throw( is, value );
//
template< class String_type, class Value_type >
void read_string_or_throw( const String_type& s, Value_type& value )
{
add_posn_iter_and_read_range_or_throw( s.begin(), s.end(), value );
}
// reads a JSON Value from a stream, e.g.
//
// const bool success = read_stream( is, value );
//
template< class Istream_type, class Value_type >
bool read_stream( Istream_type& is, Value_type& value )
{
Multi_pass_iters< Istream_type > mp_iters( is );
return read_range( mp_iters.begin_, mp_iters.end_, value );
}
// reads a JSON Value from a stream throwing an exception on invalid input, e.g.
//
// read_stream_or_throw( is, value );
//
template< class Istream_type, class Value_type >
void read_stream_or_throw( Istream_type& is, Value_type& value )
{
const Multi_pass_iters< Istream_type > mp_iters( is );
add_posn_iter_and_read_range_or_throw( mp_iters.begin_, mp_iters.end_, value );
}
}
#endif
| 21,383 | 31.302115 | 124 | h |
null | ceph-main/src/json_spirit/json_spirit_stream_reader.h | #ifndef JSON_SPIRIT_READ_STREAM
#define JSON_SPIRIT_READ_STREAM
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include "json_spirit_reader_template.h"
namespace json_spirit
{
// these classes allows you to read multiple top level contiguous values from a stream,
// the normal stream read functions have a bug that prevent multiple top level values
// from being read unless they are separated by spaces
template< class Istream_type, class Value_type >
class Stream_reader
{
public:
Stream_reader( Istream_type& is )
: iters_( is )
{
}
bool read_next( Value_type& value )
{
return read_range( iters_.begin_, iters_.end_, value );
}
private:
typedef Multi_pass_iters< Istream_type > Mp_iters;
Mp_iters iters_;
};
template< class Istream_type, class Value_type >
class Stream_reader_thrower
{
public:
Stream_reader_thrower( Istream_type& is )
: iters_( is )
, posn_begin_( iters_.begin_, iters_.end_ )
, posn_end_( iters_.end_, iters_.end_ )
{
}
void read_next( Value_type& value )
{
posn_begin_ = read_range_or_throw( posn_begin_, posn_end_, value );
}
private:
typedef Multi_pass_iters< Istream_type > Mp_iters;
typedef spirit_namespace::position_iterator< typename Mp_iters::Mp_iter > Posn_iter_t;
Mp_iters iters_;
Posn_iter_t posn_begin_, posn_end_;
};
}
#endif
| 1,724 | 23.295775 | 94 | h |
null | ceph-main/src/json_spirit/json_spirit_utils.h | #ifndef JSON_SPIRIT_UTILS
#define JSON_SPIRIT_UTILS
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include "json_spirit_value.h"
#include <map>
namespace json_spirit
{
template< class Obj_t, class Map_t >
void obj_to_map( const Obj_t& obj, Map_t& mp_obj )
{
mp_obj.clear();
for( typename Obj_t::const_iterator i = obj.begin(); i != obj.end(); ++i )
{
mp_obj[ i->name_ ] = i->value_;
}
}
template< class Obj_t, class Map_t >
void map_to_obj( const Map_t& mp_obj, Obj_t& obj )
{
obj.clear();
for( typename Map_t::const_iterator i = mp_obj.begin(); i != mp_obj.end(); ++i )
{
obj.push_back( typename Obj_t::value_type( i->first, i->second ) );
}
}
#ifdef JSON_SPIRIT_VALUE_ENABLED
typedef std::map< std::string, Value > Mapped_obj;
#endif
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
typedef std::map< std::wstring, wValue > wMapped_obj;
#endif
template< class Object_type, class String_type >
const typename Object_type::value_type::Value_type& find_value( const Object_type& obj, const String_type& name )
{
for( typename Object_type::const_iterator i = obj.begin(); i != obj.end(); ++i )
{
if( i->name_ == name )
{
return i->value_;
}
}
return Object_type::value_type::Value_type::null;
}
}
#endif
| 1,644 | 24.703125 | 117 | h |
null | ceph-main/src/json_spirit/json_spirit_value.h | #ifndef JSON_SPIRIT_VALUE
#define JSON_SPIRIT_VALUE
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <stdexcept>
#include <boost/config.hpp>
#include <boost/cstdint.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
// comment out the value types you don't need to reduce build times and intermediate file sizes
#define JSON_SPIRIT_VALUE_ENABLED
//#define JSON_SPIRIT_WVALUE_ENABLED
#define JSON_SPIRIT_MVALUE_ENABLED
//#define JSON_SPIRIT_WMVALUE_ENABLED
namespace json_spirit
{
enum Value_type{ obj_type, array_type, str_type, bool_type, int_type, real_type, null_type };
struct Null{};
template< class Config > // Config determines whether the value uses std::string or std::wstring and
// whether JSON Objects are represented as vectors or maps
class Value_impl
{
public:
typedef Config Config_type;
typedef typename Config::String_type String_type;
typedef typename Config::Object_type Object;
typedef typename Config::Array_type Array;
typedef typename String_type::const_pointer Const_str_ptr; // eg const char*
Value_impl(); // creates null value
Value_impl( Const_str_ptr value );
Value_impl( const String_type& value );
Value_impl( const Object& value );
Value_impl( const Array& value );
Value_impl( bool value );
Value_impl( int value );
Value_impl( boost::int64_t value );
Value_impl( boost::uint64_t value );
Value_impl( double value );
template< class Iter >
Value_impl( Iter first, Iter last ); // constructor from containers, e.g. std::vector or std::list
template< BOOST_VARIANT_ENUM_PARAMS( typename T ) >
Value_impl( const boost::variant< BOOST_VARIANT_ENUM_PARAMS(T) >& variant ); // constructor for compatible variant types
Value_impl( const Value_impl& other );
bool operator==( const Value_impl& lhs ) const;
Value_impl& operator=( const Value_impl& lhs );
Value_type type() const;
bool is_uint64() const;
bool is_null() const;
const String_type& get_str() const;
const Object& get_obj() const;
const Array& get_array() const;
bool get_bool() const;
int get_int() const;
boost::int64_t get_int64() const;
boost::uint64_t get_uint64() const;
double get_real() const;
Object& get_obj();
Array& get_array();
template< typename T > T get_value() const; // example usage: int i = value.get_value< int >();
// or double d = value.get_value< double >();
static const Value_impl null;
private:
void check_type( const Value_type vtype ) const;
typedef boost::variant< boost::recursive_wrapper< Object >, boost::recursive_wrapper< Array >,
String_type, bool, boost::int64_t, double, Null, boost::uint64_t > Variant;
Variant v_;
class Variant_converter_visitor : public boost::static_visitor< Variant >
{
public:
template< typename T, typename A, template< typename, typename > class Cont >
Variant operator()( const Cont< T, A >& cont ) const
{
return Array( cont.begin(), cont.end() );
}
Variant operator()( int i ) const
{
return static_cast< boost::int64_t >( i );
}
template<class T>
Variant operator()( const T& t ) const
{
return t;
}
};
};
// vector objects
template< class Config >
struct Pair_impl
{
typedef typename Config::String_type String_type;
typedef typename Config::Value_type Value_type;
Pair_impl()
{
}
Pair_impl( const String_type& name, const Value_type& value );
bool operator==( const Pair_impl& lhs ) const;
String_type name_;
Value_type value_;
};
#if defined( JSON_SPIRIT_VALUE_ENABLED ) || defined( JSON_SPIRIT_WVALUE_ENABLED )
template< class String >
struct Config_vector
{
typedef String String_type;
typedef Value_impl< Config_vector > Value_type;
typedef Pair_impl < Config_vector > Pair_type;
typedef std::vector< Value_type > Array_type;
typedef std::vector< Pair_type > Object_type;
static Value_type& add( Object_type& obj, const String_type& name, const Value_type& value )
{
obj.push_back( Pair_type( name , value ) );
return obj.back().value_;
}
static String_type get_name( const Pair_type& pair )
{
return pair.name_;
}
static Value_type get_value( const Pair_type& pair )
{
return pair.value_;
}
};
#endif
// typedefs for ASCII
#ifdef JSON_SPIRIT_VALUE_ENABLED
typedef Config_vector< std::string > Config;
typedef Config::Value_type Value;
typedef Config::Pair_type Pair;
typedef Config::Object_type Object;
typedef Config::Array_type Array;
#endif
// typedefs for Unicode
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
typedef Config_vector< std::wstring > wConfig;
typedef wConfig::Value_type wValue;
typedef wConfig::Pair_type wPair;
typedef wConfig::Object_type wObject;
typedef wConfig::Array_type wArray;
#endif
// map objects
#if defined( JSON_SPIRIT_MVALUE_ENABLED ) || defined( JSON_SPIRIT_WMVALUE_ENABLED )
template< class String >
struct Config_map
{
typedef String String_type;
typedef Value_impl< Config_map > Value_type;
typedef std::vector< Value_type > Array_type;
typedef std::map< String_type, Value_type > Object_type;
typedef std::pair< String_type, Value_type > Pair_type;
static Value_type& add( Object_type& obj, const String_type& name, const Value_type& value )
{
return obj[ name ] = value;
}
static String_type get_name( const Pair_type& pair )
{
return pair.first;
}
static Value_type get_value( const Pair_type& pair )
{
return pair.second;
}
};
#endif
// typedefs for ASCII
#ifdef JSON_SPIRIT_MVALUE_ENABLED
typedef Config_map< std::string > mConfig;
typedef mConfig::Value_type mValue;
typedef mConfig::Object_type mObject;
typedef mConfig::Array_type mArray;
#endif
// typedefs for Unicode
#if defined( JSON_SPIRIT_WMVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
typedef Config_map< std::wstring > wmConfig;
typedef wmConfig::Value_type wmValue;
typedef wmConfig::Object_type wmObject;
typedef wmConfig::Array_type wmArray;
#endif
///////////////////////////////////////////////////////////////////////////////////////////////
//
// implementation
inline bool operator==( const Null&, const Null& )
{
return true;
}
template< class Config >
const Value_impl< Config > Value_impl< Config >::null;
template< class Config >
Value_impl< Config >::Value_impl()
: v_( Null() )
{
}
template< class Config >
Value_impl< Config >::Value_impl( const Const_str_ptr value )
: v_( String_type( value ) )
{
}
template< class Config >
Value_impl< Config >::Value_impl( const String_type& value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( const Object& value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( const Array& value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( bool value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( int value )
: v_( static_cast< boost::int64_t >( value ) )
{
}
template< class Config >
Value_impl< Config >::Value_impl( boost::int64_t value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( boost::uint64_t value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( double value )
: v_( value )
{
}
template< class Config >
Value_impl< Config >::Value_impl( const Value_impl< Config >& other )
: v_( other.v_ )
{
}
template< class Config >
template< class Iter >
Value_impl< Config >::Value_impl( Iter first, Iter last )
: v_( Array( first, last ) )
{
}
template< class Config >
template< BOOST_VARIANT_ENUM_PARAMS( typename T ) >
Value_impl< Config >::Value_impl( const boost::variant< BOOST_VARIANT_ENUM_PARAMS(T) >& variant )
: v_( boost::apply_visitor( Variant_converter_visitor(), variant) )
{
}
template< class Config >
Value_impl< Config >& Value_impl< Config >::operator=( const Value_impl& lhs )
{
Value_impl tmp( lhs );
std::swap( v_, tmp.v_ );
return *this;
}
template< class Config >
bool Value_impl< Config >::operator==( const Value_impl& lhs ) const
{
if( this == &lhs ) return true;
if( type() != lhs.type() ) return false;
return v_ == lhs.v_;
}
template< class Config >
Value_type Value_impl< Config >::type() const
{
if( is_uint64() )
{
return int_type;
}
return static_cast< Value_type >( v_.which() );
}
template< class Config >
bool Value_impl< Config >::is_uint64() const
{
return v_.which() == null_type + 1;
}
template< class Config >
bool Value_impl< Config >::is_null() const
{
return type() == null_type;
}
template< class Config >
void Value_impl< Config >::check_type( const Value_type vtype ) const
{
if( type() != vtype )
{
std::ostringstream os;
os << "value type is " << type() << " not " << vtype;
throw std::runtime_error( os.str() );
}
}
template< class Config >
const typename Config::String_type& Value_impl< Config >::get_str() const
{
check_type( str_type );
return *boost::get< String_type >( &v_ );
}
template< class Config >
const typename Value_impl< Config >::Object& Value_impl< Config >::get_obj() const
{
check_type( obj_type );
return *boost::get< Object >( &v_ );
}
template< class Config >
const typename Value_impl< Config >::Array& Value_impl< Config >::get_array() const
{
check_type( array_type );
return *boost::get< Array >( &v_ );
}
template< class Config >
bool Value_impl< Config >::get_bool() const
{
check_type( bool_type );
return boost::get< bool >( v_ );
}
template< class Config >
int Value_impl< Config >::get_int() const
{
check_type( int_type );
return static_cast< int >( get_int64() );
}
template< class Config >
boost::int64_t Value_impl< Config >::get_int64() const
{
check_type( int_type );
if( is_uint64() )
{
return static_cast< boost::int64_t >( get_uint64() );
}
return boost::get< boost::int64_t >( v_ );
}
template< class Config >
boost::uint64_t Value_impl< Config >::get_uint64() const
{
check_type( int_type );
if( !is_uint64() )
{
return static_cast< boost::uint64_t >( get_int64() );
}
return boost::get< boost::uint64_t >( v_ );
}
template< class Config >
double Value_impl< Config >::get_real() const
{
if( type() == int_type )
{
return is_uint64() ? static_cast< double >( get_uint64() )
: static_cast< double >( get_int64() );
}
check_type( real_type );
return boost::get< double >( v_ );
}
template< class Config >
typename Value_impl< Config >::Object& Value_impl< Config >::get_obj()
{
check_type( obj_type );
return *boost::get< Object >( &v_ );
}
template< class Config >
typename Value_impl< Config >::Array& Value_impl< Config >::get_array()
{
check_type( array_type );
return *boost::get< Array >( &v_ );
}
template< class Config >
Pair_impl< Config >::Pair_impl( const String_type& name, const Value_type& value )
: name_( name )
, value_( value )
{
}
template< class Config >
bool Pair_impl< Config >::operator==( const Pair_impl< Config >& lhs ) const
{
if( this == &lhs ) return true;
return ( name_ == lhs.name_ ) && ( value_ == lhs.value_ );
}
// converts a C string, ie. 8 bit char array, to a string object
//
template < class String_type >
String_type to_str( const char* c_str )
{
String_type result;
for( const char* p = c_str; *p != 0; ++p )
{
result += *p;
}
return result;
}
//
namespace internal_
{
template< typename T >
struct Type_to_type
{
};
template< class Value >
int get_value( const Value& value, Type_to_type< int > )
{
return value.get_int();
}
template< class Value >
boost::int64_t get_value( const Value& value, Type_to_type< boost::int64_t > )
{
return value.get_int64();
}
template< class Value >
boost::uint64_t get_value( const Value& value, Type_to_type< boost::uint64_t > )
{
return value.get_uint64();
}
template< class Value >
double get_value( const Value& value, Type_to_type< double > )
{
return value.get_real();
}
template< class Value >
typename Value::String_type get_value( const Value& value, Type_to_type< typename Value::String_type > )
{
return value.get_str();
}
template< class Value >
typename Value::Array get_value( const Value& value, Type_to_type< typename Value::Array > )
{
return value.get_array();
}
template< class Value >
typename Value::Object get_value( const Value& value, Type_to_type< typename Value::Object > )
{
return value.get_obj();
}
template< class Value >
bool get_value( const Value& value, Type_to_type< bool > )
{
return value.get_bool();
}
}
template< class Config >
template< typename T >
T Value_impl< Config >::get_value() const
{
return internal_::get_value( *this, internal_::Type_to_type< T >() );
}
}
#endif
| 15,731 | 25.892308 | 128 | h |
null | ceph-main/src/json_spirit/json_spirit_writer.h | #ifndef JSON_SPIRIT_WRITER
#define JSON_SPIRIT_WRITER
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include "json_spirit_value.h"
#include "json_spirit_writer_options.h"
#include <iostream>
namespace json_spirit
{
// these functions to convert JSON Values to text
#ifdef JSON_SPIRIT_VALUE_ENABLED
void write( const Value& value, std::ostream& os, unsigned int options = 0 );
std::string write( const Value& value, unsigned int options = 0 );
#endif
#ifdef JSON_SPIRIT_MVALUE_ENABLED
void write( const mValue& value, std::ostream& os, unsigned int options = 0 );
std::string write( const mValue& value, unsigned int options = 0 );
#endif
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
void write( const wValue& value, std::wostream& os, unsigned int options = 0 );
std::wstring write( const wValue& value, unsigned int options = 0 );
#endif
#if defined( JSON_SPIRIT_WMVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
void write( const wmValue& value, std::wostream& os, unsigned int options = 0 );
std::wstring write( const wmValue& value, unsigned int options = 0 );
#endif
// these "formatted" versions of the "write" functions are the equivalent of the above functions
// with option "pretty_print"
#ifdef JSON_SPIRIT_VALUE_ENABLED
void write_formatted( const Value& value, std::ostream& os );
std::string write_formatted( const Value& value );
#endif
#ifdef JSON_SPIRIT_MVALUE_ENABLED
void write_formatted( const mValue& value, std::ostream& os );
std::string write_formatted( const mValue& value );
#endif
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
void write_formatted( const wValue& value, std::wostream& os );
std::wstring write_formatted( const wValue& value );
#endif
#if defined( JSON_SPIRIT_WMVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
void write_formatted( const wmValue& value, std::wostream& os );
std::wstring write_formatted( const wmValue& value );
#endif
}
#endif
| 2,301 | 34.96875 | 100 | h |
null | ceph-main/src/json_spirit/json_spirit_writer_options.h | #ifndef JSON_SPIRIT_WRITER_OPTIONS
#define JSON_SPIRIT_WRITER_OPTIONS
// Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.05
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
namespace json_spirit
{
enum Output_options{ pretty_print = 0x01, // Add whitespace to format the output nicely.
raw_utf8 = 0x02, // This prevents non-printable characters from being escapted using "\uNNNN" notation.
// Note, this is an extension to the JSON standard. It disables the escaping of
// non-printable characters allowing UTF-8 sequences held in 8 bit char strings
// to pass through unaltered.
remove_trailing_zeros = 0x04,
// outputs e.g. "1.200000000000000" as "1.2"
single_line_arrays = 0x08,
// pretty printing except that arrays printed on single lines unless they contain
// composite elements, i.e. objects or arrays
};
}
#endif
| 1,341 | 42.290323 | 134 | h |
null | ceph-main/src/key_value_store/key_value_structure.h | /*
* Interface for key-value store using librados
*
* September 2, 2012
* Eleanor Cawthon
* [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 KEY_VALUE_STRUCTURE_HPP_
#define KEY_VALUE_STRUCTURE_HPP_
#include "include/rados/librados.hpp"
#include "include/utime.h"
#include <vector>
using ceph::bufferlist;
class KeyValueStructure;
/**An injection_t is a function that is called before every
* ObjectWriteOperation to test concurrency issues. For example,
* one injection_t might cause the client to have a greater chance of dying
* mid-split/merge.
*/
typedef int (KeyValueStructure::*injection_t)();
/**
* Passed to aio methods to be called when the operation completes
*/
typedef void (*callback)(int * err, void *arg);
class KeyValueStructure{
public:
std::map<char, int> opmap;
//these are injection methods. By default, nothing is called at each
//interruption point.
/**
* returns 0
*/
virtual int nothing() = 0;
/**
* 10% chance of waiting wait_ms seconds
*/
virtual int wait() = 0;
/**
* 10% chance of killing the client.
*/
virtual int suicide() = 0;
////////////////DESTRUCTOR/////////////////
virtual ~KeyValueStructure() {}
////////////////UPDATERS///////////////////
/**
* set up the KeyValueStructure (i.e., initialize rados/io_ctx, etc.)
*/
virtual int setup(int argc, const char** argv) = 0;
/**
* set the method that gets called before each ObjectWriteOperation.
* If waite_time is set and the method passed involves waiting, it will wait
* for that many milliseconds.
*/
virtual void set_inject(injection_t inject, int wait_time) = 0;
/**
* if update_on_existing is false, returns an error if
* key already exists in the structure
*/
virtual int set(const std::string &key, const bufferlist &val,
bool update_on_existing) = 0;
/**
* efficiently insert the contents of in_map into the structure
*/
virtual int set_many(const std::map<std::string, bufferlist> &in_map) = 0;
/**
* removes the key-value for key. returns an error if key does not exist
*/
virtual int remove(const std::string &key) = 0;
/**
* removes all keys and values
*/
virtual int remove_all() = 0;
/**
* launches a thread to get the value of key. When complete, calls cb(cb_args)
*/
virtual void aio_get(const std::string &key, bufferlist *val, callback cb,
void *cb_args, int * err) = 0;
/**
* launches a thread to set key to val. When complete, calls cb(cb_args)
*/
virtual void aio_set(const std::string &key, const bufferlist &val, bool exclusive,
callback cb, void * cb_args, int * err) = 0;
/**
* launches a thread to remove key. When complete, calls cb(cb_args)
*/
virtual void aio_remove(const std::string &key, callback cb, void *cb_args,
int * err) = 0;
////////////////READERS////////////////////
/**
* gets the val associated with key.
*
* @param key the key to get
* @param val the value is stored in this
* @return error code
*/
virtual int get(const std::string &key, bufferlist *val) = 0;
/**
* stores all keys in keys. set should put them in order by key.
*/
virtual int get_all_keys(std::set<std::string> *keys) = 0;
/**
* stores all keys and values in kv_map. map should put them in order by key.
*/
virtual int get_all_keys_and_values(std::map<std::string,bufferlist> *kv_map) = 0;
/**
* True if the structure meets its own requirements for consistency.
*/
virtual bool is_consistent() = 0;
/**
* prints a string representation of the structure
*/
virtual std::string str() = 0;
};
#endif /* KEY_VALUE_STRUCTURE_HPP_ */
| 3,898 | 25.52381 | 85 | h |
null | ceph-main/src/kv/KeyValueDB.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef KEY_VALUE_DB_H
#define KEY_VALUE_DB_H
#include "include/buffer.h"
#include <ostream>
#include <set>
#include <map>
#include <optional>
#include <string>
#include <boost/scoped_ptr.hpp>
#include "include/encoding.h"
#include "common/Formatter.h"
#include "common/perf_counters.h"
#include "common/PriorityCache.h"
/**
* Defines virtual interface to be implemented by key value store
*
* Kyoto Cabinet should implement this
*/
class KeyValueDB {
public:
class TransactionImpl {
public:
/// Set Keys
void set(
const std::string &prefix, ///< [in] Prefix for keys, or CF name
const std::map<std::string, ceph::buffer::list> &to_set ///< [in] keys/values to set
) {
for (auto it = to_set.cbegin(); it != to_set.cend(); ++it)
set(prefix, it->first, it->second);
}
/// Set Keys (via encoded ceph::buffer::list)
void set(
const std::string &prefix, ///< [in] prefix, or CF name
ceph::buffer::list& to_set_bl ///< [in] encoded key/values to set
) {
using ceph::decode;
auto p = std::cbegin(to_set_bl);
uint32_t num;
decode(num, p);
while (num--) {
std::string key;
ceph::buffer::list value;
decode(key, p);
decode(value, p);
set(prefix, key, value);
}
}
/// Set Key
virtual void set(
const std::string &prefix, ///< [in] Prefix or CF for the key
const std::string &k, ///< [in] Key to set
const ceph::buffer::list &bl ///< [in] Value to set
) = 0;
virtual void set(
const std::string &prefix,
const char *k,
size_t keylen,
const ceph::buffer::list& bl) {
set(prefix, std::string(k, keylen), bl);
}
/// Removes Keys (via encoded ceph::buffer::list)
void rmkeys(
const std::string &prefix, ///< [in] Prefix or CF to search for
ceph::buffer::list &keys_bl ///< [in] Keys to remove
) {
using ceph::decode;
auto p = std::cbegin(keys_bl);
uint32_t num;
decode(num, p);
while (num--) {
std::string key;
decode(key, p);
rmkey(prefix, key);
}
}
/// Removes Keys
void rmkeys(
const std::string &prefix, ///< [in] Prefix/CF to search for
const std::set<std::string> &keys ///< [in] Keys to remove
) {
for (auto it = keys.cbegin(); it != keys.cend(); ++it)
rmkey(prefix, *it);
}
/// Remove Key
virtual void rmkey(
const std::string &prefix, ///< [in] Prefix/CF to search for
const std::string &k ///< [in] Key to remove
) = 0;
virtual void rmkey(
const std::string &prefix, ///< [in] Prefix to search for
const char *k, ///< [in] Key to remove
size_t keylen
) {
rmkey(prefix, std::string(k, keylen));
}
/// Remove Single Key which exists and was not overwritten.
/// This API is only related to performance optimization, and should only be
/// re-implemented by log-insert-merge tree based keyvalue stores(such as RocksDB).
/// If a key is overwritten (by calling set multiple times), then the result
/// of calling rm_single_key on this key is undefined.
virtual void rm_single_key(
const std::string &prefix, ///< [in] Prefix/CF to search for
const std::string &k ///< [in] Key to remove
) { return rmkey(prefix, k);}
/// Removes keys beginning with prefix
virtual void rmkeys_by_prefix(
const std::string &prefix ///< [in] Prefix/CF by which to remove keys
) = 0;
virtual void rm_range_keys(
const std::string &prefix, ///< [in] Prefix by which to remove keys
const std::string &start, ///< [in] The start bound of remove keys
const std::string &end ///< [in] The start bound of remove keys
) = 0;
/// Merge value into key
virtual void merge(
const std::string &prefix, ///< [in] Prefix/CF ==> MUST match some established merge operator
const std::string &key, ///< [in] Key to be merged
const ceph::buffer::list &value ///< [in] value to be merged into key
) { ceph_abort_msg("Not implemented"); }
virtual ~TransactionImpl() {}
};
typedef std::shared_ptr< TransactionImpl > Transaction;
/// create a new instance
static KeyValueDB *create(CephContext *cct, const std::string& type,
const std::string& dir,
std::map<std::string,std::string> options = {},
void *p = NULL);
/// test whether we can successfully initialize; may have side effects (e.g., create)
static int test_init(const std::string& type, const std::string& dir);
virtual int init(std::string option_str="") = 0;
virtual int open(std::ostream &out, const std::string& cfs="") = 0;
// std::vector cfs contains column families to be created when db is created.
virtual int create_and_open(std::ostream &out, const std::string& cfs="") = 0;
virtual int open_read_only(std::ostream &out, const std::string& cfs="") {
return -ENOTSUP;
}
virtual void close() { }
/// Try to repair K/V database. rocksdb requires that database must be not opened.
virtual int repair(std::ostream &out) { return 0; }
virtual Transaction get_transaction() = 0;
virtual int submit_transaction(Transaction) = 0;
virtual int submit_transaction_sync(Transaction t) {
return submit_transaction(t);
}
/// Retrieve Keys
virtual int get(
const std::string &prefix, ///< [in] Prefix/CF for key
const std::set<std::string> &key, ///< [in] Key to retrieve
std::map<std::string, ceph::buffer::list> *out ///< [out] Key value retrieved
) = 0;
virtual int get(const std::string &prefix, ///< [in] prefix or CF name
const std::string &key, ///< [in] key
ceph::buffer::list *value) { ///< [out] value
std::set<std::string> ks;
ks.insert(key);
std::map<std::string,ceph::buffer::list> om;
int r = get(prefix, ks, &om);
if (om.find(key) != om.end()) {
*value = std::move(om[key]);
} else {
*value = ceph::buffer::list();
r = -ENOENT;
}
return r;
}
virtual int get(const std::string &prefix,
const char *key, size_t keylen,
ceph::buffer::list *value) {
return get(prefix, std::string(key, keylen), value);
}
// This superclass is used both by kv iterators *and* by the ObjectMap
// omap iterator. The class hierarchies are unfortunately tied together
// by the legacy DBOjectMap implementation :(.
class SimplestIteratorImpl {
public:
virtual int seek_to_first() = 0;
virtual int upper_bound(const std::string &after) = 0;
virtual int lower_bound(const std::string &to) = 0;
virtual bool valid() = 0;
virtual int next() = 0;
virtual std::string key() = 0;
virtual std::string tail_key() {
return "";
}
virtual ceph::buffer::list value() = 0;
virtual int status() = 0;
virtual ~SimplestIteratorImpl() {}
};
class IteratorImpl : public SimplestIteratorImpl {
public:
virtual ~IteratorImpl() {}
virtual int seek_to_last() = 0;
virtual int prev() = 0;
virtual std::pair<std::string, std::string> raw_key() = 0;
virtual ceph::buffer::ptr value_as_ptr() {
ceph::buffer::list bl = value();
if (bl.length() == 1) {
return *bl.buffers().begin();
} else if (bl.length() == 0) {
return ceph::buffer::ptr();
} else {
ceph_abort();
}
}
};
typedef std::shared_ptr< IteratorImpl > Iterator;
// This is the low-level iterator implemented by the underlying KV store.
class WholeSpaceIteratorImpl {
public:
virtual int seek_to_first() = 0;
virtual int seek_to_first(const std::string &prefix) = 0;
virtual int seek_to_last() = 0;
virtual int seek_to_last(const std::string &prefix) = 0;
virtual int upper_bound(const std::string &prefix, const std::string &after) = 0;
virtual int lower_bound(const std::string &prefix, const std::string &to) = 0;
virtual bool valid() = 0;
virtual int next() = 0;
virtual int prev() = 0;
virtual std::string key() = 0;
virtual std::pair<std::string,std::string> raw_key() = 0;
virtual bool raw_key_is_prefixed(const std::string &prefix) = 0;
virtual ceph::buffer::list value() = 0;
virtual ceph::buffer::ptr value_as_ptr() {
ceph::buffer::list bl = value();
if (bl.length()) {
return *bl.buffers().begin();
} else {
return ceph::buffer::ptr();
}
}
virtual int status() = 0;
virtual size_t key_size() {
return 0;
}
virtual size_t value_size() {
return 0;
}
virtual ~WholeSpaceIteratorImpl() { }
};
typedef std::shared_ptr< WholeSpaceIteratorImpl > WholeSpaceIterator;
private:
// This class filters a WholeSpaceIterator by a prefix.
// Performs as a dummy wrapper over WholeSpaceIterator
// if prefix is empty
class PrefixIteratorImpl : public IteratorImpl {
const std::string prefix;
WholeSpaceIterator generic_iter;
public:
PrefixIteratorImpl(const std::string &prefix, WholeSpaceIterator iter) :
prefix(prefix), generic_iter(iter) { }
~PrefixIteratorImpl() override { }
int seek_to_first() override {
return prefix.empty() ?
generic_iter->seek_to_first() :
generic_iter->seek_to_first(prefix);
}
int seek_to_last() override {
return prefix.empty() ?
generic_iter->seek_to_last() :
generic_iter->seek_to_last(prefix);
}
int upper_bound(const std::string &after) override {
return generic_iter->upper_bound(prefix, after);
}
int lower_bound(const std::string &to) override {
return generic_iter->lower_bound(prefix, to);
}
bool valid() override {
if (!generic_iter->valid())
return false;
if (prefix.empty())
return true;
return prefix.empty() ?
true :
generic_iter->raw_key_is_prefixed(prefix);
}
int next() override {
return generic_iter->next();
}
int prev() override {
return generic_iter->prev();
}
std::string key() override {
return generic_iter->key();
}
std::pair<std::string, std::string> raw_key() override {
return generic_iter->raw_key();
}
ceph::buffer::list value() override {
return generic_iter->value();
}
ceph::buffer::ptr value_as_ptr() override {
return generic_iter->value_as_ptr();
}
int status() override {
return generic_iter->status();
}
};
protected:
Iterator make_iterator(const std::string &prefix, WholeSpaceIterator w_iter) {
return std::make_shared<PrefixIteratorImpl>(
prefix,
w_iter);
}
public:
typedef uint32_t IteratorOpts;
static const uint32_t ITERATOR_NOCACHE = 1;
struct IteratorBounds {
std::optional<std::string> lower_bound;
std::optional<std::string> upper_bound;
};
virtual WholeSpaceIterator get_wholespace_iterator(IteratorOpts opts = 0) = 0;
virtual Iterator get_iterator(const std::string &prefix, IteratorOpts opts = 0, IteratorBounds bounds = IteratorBounds()) {
return make_iterator(prefix,
get_wholespace_iterator(opts));
}
virtual uint64_t get_estimated_size(std::map<std::string,uint64_t> &extra) = 0;
virtual int get_statfs(struct store_statfs_t *buf) {
return -EOPNOTSUPP;
}
virtual int set_cache_size(uint64_t) {
return -EOPNOTSUPP;
}
virtual int set_cache_high_pri_pool_ratio(double ratio) {
return -EOPNOTSUPP;
}
virtual int64_t get_cache_usage() const {
return -EOPNOTSUPP;
}
virtual int64_t get_cache_usage(std::string prefix) const {
return -EOPNOTSUPP;
}
virtual std::shared_ptr<PriorityCache::PriCache> get_priority_cache() const {
return nullptr;
}
virtual std::shared_ptr<PriorityCache::PriCache> get_priority_cache(std::string prefix) const {
return nullptr;
}
virtual ~KeyValueDB() {}
/// estimate space utilization for a prefix (in bytes)
virtual int64_t estimate_prefix_size(const std::string& prefix,
const std::string& key_prefix) {
return 0;
}
/// compact the underlying store
virtual void compact() {}
/// compact the underlying store in async mode
virtual void compact_async() {}
/// compact db for all keys with a given prefix
virtual void compact_prefix(const std::string& prefix) {}
/// compact db for all keys with a given prefix, async
virtual void compact_prefix_async(const std::string& prefix) {}
virtual void compact_range(const std::string& prefix,
const std::string& start, const std::string& end) {}
virtual void compact_range_async(const std::string& prefix,
const std::string& start, const std::string& end) {}
// See RocksDB merge operator definition, we support the basic
// associative merge only right now.
class MergeOperator {
public:
/// Merge into a key that doesn't exist
virtual void merge_nonexistent(
const char *rdata, size_t rlen,
std::string *new_value) = 0;
/// Merge into a key that does exist
virtual void merge(
const char *ldata, size_t llen,
const char *rdata, size_t rlen,
std::string *new_value) = 0;
/// We use each operator name and each prefix to construct the overall RocksDB operator name for consistency check at open time.
virtual const char *name() const = 0;
virtual ~MergeOperator() {}
};
/// Setup one or more operators, this needs to be done BEFORE the DB is opened.
virtual int set_merge_operator(const std::string& prefix,
std::shared_ptr<MergeOperator> mop) {
return -EOPNOTSUPP;
}
virtual void get_statistics(ceph::Formatter *f) {
return;
}
/**
* Return your perf counters if you have any. Subclasses are not
* required to implement this, and callers must respect a null return
* value.
*/
virtual PerfCounters *get_perf_counters() {
return nullptr;
}
/**
* Access implementation specific integral property corresponding
* to passed property and prefic.
* Return value is true if property is valid for prefix, populates out.
*/
virtual bool get_property(
const std::string &property,
uint64_t *out) {
return false;
}
protected:
/// List of matching prefixes/ColumnFamilies and merge operators
std::vector<std::pair<std::string,
std::shared_ptr<MergeOperator> > > merge_ops;
};
#endif
| 14,552 | 30.914474 | 132 | h |
null | ceph-main/src/kv/KeyValueHistogram.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef KeyValueHistogram_H
#define KeyValueHistogram_H
#include <map>
#include <string>
#include "common/Formatter.h"
/**
*
* Key Value DB Histogram generator
*
*/
struct KeyValueHistogram {
struct value_dist {
uint64_t count;
uint32_t max_len;
};
struct key_dist {
uint64_t count;
uint32_t max_len;
std::map<int, struct value_dist> val_map; ///< slab id to count, max length of value and key
};
std::map<std::string, std::map<int, struct key_dist> > key_hist;
std::map<int, uint64_t> value_hist;
int get_key_slab(size_t sz);
std::string get_key_slab_to_range(int slab);
int get_value_slab(size_t sz);
std::string get_value_slab_to_range(int slab);
void update_hist_entry(std::map<std::string, std::map<int, struct key_dist> >& key_hist,
const std::string& prefix, size_t key_size, size_t value_size);
void dump(ceph::Formatter* f);
};
#endif
| 999 | 24.641026 | 96 | h |
null | ceph-main/src/kv/RocksDBStore.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef ROCKS_DB_STORE_H
#define ROCKS_DB_STORE_H
#include "include/types.h"
#include "include/buffer_fwd.h"
#include "KeyValueDB.h"
#include <set>
#include <map>
#include <string>
#include <memory>
#include <boost/scoped_ptr.hpp>
#include "rocksdb/write_batch.h"
#include "rocksdb/perf_context.h"
#include "rocksdb/iostats_context.h"
#include "rocksdb/statistics.h"
#include "rocksdb/table.h"
#include "rocksdb/db.h"
#include "kv/rocksdb_cache/BinnedLRUCache.h"
#include <errno.h>
#include "common/errno.h"
#include "common/dout.h"
#include "include/ceph_assert.h"
#include "include/common_fwd.h"
#include "common/Formatter.h"
#include "common/Cond.h"
#include "common/ceph_context.h"
#include "common/PriorityCache.h"
#include "common/pretty_binary.h"
enum {
l_rocksdb_first = 34300,
l_rocksdb_get_latency,
l_rocksdb_submit_latency,
l_rocksdb_submit_sync_latency,
l_rocksdb_compact,
l_rocksdb_compact_range,
l_rocksdb_compact_queue_merge,
l_rocksdb_compact_queue_len,
l_rocksdb_write_wal_time,
l_rocksdb_write_memtable_time,
l_rocksdb_write_delay_time,
l_rocksdb_write_pre_and_post_process_time,
l_rocksdb_last,
};
namespace rocksdb{
class DB;
class Env;
class Cache;
class FilterPolicy;
class Snapshot;
class Slice;
class WriteBatch;
class Iterator;
class Logger;
class ColumnFamilyHandle;
struct Options;
struct BlockBasedTableOptions;
struct DBOptions;
struct ColumnFamilyOptions;
}
extern rocksdb::Logger *create_rocksdb_ceph_logger();
inline rocksdb::Slice make_slice(const std::optional<std::string>& bound) {
if (bound) {
return {*bound};
} else {
return {};
}
}
/**
* Uses RocksDB to implement the KeyValueDB interface
*/
class RocksDBStore : public KeyValueDB {
CephContext *cct;
PerfCounters *logger;
std::string path;
std::map<std::string,std::string> kv_options;
void *priv;
rocksdb::DB *db;
rocksdb::Env *env;
const rocksdb::Comparator* comparator;
std::shared_ptr<rocksdb::Statistics> dbstats;
rocksdb::BlockBasedTableOptions bbt_opts;
std::string options_str;
uint64_t cache_size = 0;
bool set_cache_flag = false;
friend class ShardMergeIteratorImpl;
friend class CFIteratorImpl;
friend class WholeMergeIteratorImpl;
/*
* See RocksDB's definition of a column family(CF) and how to use it.
* The interfaces of KeyValueDB is extended, when a column family is created.
* Prefix will be the name of column family to use.
*/
public:
struct ColumnFamily {
std::string name; //< name of this individual column family
size_t shard_cnt; //< count of shards
std::string options; //< configure option string for this CF
uint32_t hash_l; //< first character to take for hash calc.
uint32_t hash_h; //< last character to take for hash calc.
ColumnFamily(const std::string &name, size_t shard_cnt, const std::string &options,
uint32_t hash_l, uint32_t hash_h)
: name(name), shard_cnt(shard_cnt), options(options), hash_l(hash_l), hash_h(hash_h) {}
};
private:
friend std::ostream& operator<<(std::ostream& out, const ColumnFamily& cf);
bool must_close_default_cf = false;
rocksdb::ColumnFamilyHandle *default_cf = nullptr;
/// column families in use, name->handles
struct prefix_shards {
uint32_t hash_l; //< first character to take for hash calc.
uint32_t hash_h; //< last character to take for hash calc.
std::vector<rocksdb::ColumnFamilyHandle *> handles;
};
std::unordered_map<std::string, prefix_shards> cf_handles;
typedef decltype(cf_handles)::iterator cf_handles_iterator;
std::unordered_map<uint32_t, std::string> cf_ids_to_prefix;
std::unordered_map<std::string, rocksdb::BlockBasedTableOptions> cf_bbt_opts;
void add_column_family(const std::string& cf_name, uint32_t hash_l, uint32_t hash_h,
size_t shard_idx, rocksdb::ColumnFamilyHandle *handle);
bool is_column_family(const std::string& prefix);
std::string_view get_key_hash_view(const prefix_shards& shards, const char* key, const size_t keylen);
rocksdb::ColumnFamilyHandle *get_key_cf(const prefix_shards& shards, const char* key, const size_t keylen);
rocksdb::ColumnFamilyHandle *get_cf_handle(const std::string& prefix, const std::string& key);
rocksdb::ColumnFamilyHandle *get_cf_handle(const std::string& prefix, const char* key, size_t keylen);
rocksdb::ColumnFamilyHandle *check_cf_handle_bounds(const cf_handles_iterator& it, const IteratorBounds& bounds);
int submit_common(rocksdb::WriteOptions& woptions, KeyValueDB::Transaction t);
int install_cf_mergeop(const std::string &cf_name, rocksdb::ColumnFamilyOptions *cf_opt);
int create_db_dir();
int do_open(std::ostream &out, bool create_if_missing, bool open_readonly,
const std::string& cfs="");
int load_rocksdb_options(bool create_if_missing, rocksdb::Options& opt);
public:
static bool parse_sharding_def(const std::string_view text_def,
std::vector<ColumnFamily>& sharding_def,
char const* *error_position = nullptr,
std::string *error_msg = nullptr);
const rocksdb::Comparator* get_comparator() const {
return comparator;
}
private:
static void sharding_def_to_columns(const std::vector<ColumnFamily>& sharding_def,
std::vector<std::string>& columns);
int create_shards(const rocksdb::Options& opt,
const std::vector<ColumnFamily>& sharding_def);
int apply_sharding(const rocksdb::Options& opt,
const std::string& sharding_text);
int verify_sharding(const rocksdb::Options& opt,
std::vector<rocksdb::ColumnFamilyDescriptor>& existing_cfs,
std::vector<std::pair<size_t, RocksDBStore::ColumnFamily> >& existing_cfs_shard,
std::vector<rocksdb::ColumnFamilyDescriptor>& missing_cfs,
std::vector<std::pair<size_t, RocksDBStore::ColumnFamily> >& missing_cfs_shard);
std::shared_ptr<rocksdb::Cache> create_block_cache(const std::string& cache_type, size_t cache_size, double cache_prio_high = 0.0);
int split_column_family_options(const std::string& opts_str,
std::unordered_map<std::string, std::string>* column_opts_map,
std::string* block_cache_opt);
int apply_block_cache_options(const std::string& column_name,
const std::string& block_cache_opt,
rocksdb::ColumnFamilyOptions* cf_opt);
int update_column_family_options(const std::string& base_name,
const std::string& more_options,
rocksdb::ColumnFamilyOptions* cf_opt);
// manage async compactions
ceph::mutex compact_queue_lock =
ceph::make_mutex("RocksDBStore::compact_thread_lock");
ceph::condition_variable compact_queue_cond;
std::list<std::pair<std::string,std::string>> compact_queue;
bool compact_queue_stop;
class CompactThread : public Thread {
RocksDBStore *db;
public:
explicit CompactThread(RocksDBStore *d) : db(d) {}
void *entry() override {
db->compact_thread_entry();
return NULL;
}
friend class RocksDBStore;
} compact_thread;
void compact_thread_entry();
void compact_range(const std::string& start, const std::string& end);
void compact_range_async(const std::string& start, const std::string& end);
int tryInterpret(const std::string& key, const std::string& val,
rocksdb::Options& opt);
public:
/// compact the underlying rocksdb store
bool compact_on_mount;
bool disableWAL;
uint64_t get_delete_range_threshold() const {
return cct->_conf.get_val<uint64_t>("rocksdb_delete_range_threshold");
}
void compact() override;
void compact_async() override {
compact_range_async({}, {});
}
int ParseOptionsFromString(const std::string& opt_str, rocksdb::Options& opt);
static int ParseOptionsFromStringStatic(
CephContext* cct,
const std::string& opt_str,
rocksdb::Options &opt,
std::function<int(const std::string&, const std::string&, rocksdb::Options&)> interp);
static int _test_init(const std::string& dir);
int init(std::string options_str) override;
/// compact rocksdb for all keys with a given prefix
void compact_prefix(const std::string& prefix) override {
compact_range(prefix, past_prefix(prefix));
}
void compact_prefix_async(const std::string& prefix) override {
compact_range_async(prefix, past_prefix(prefix));
}
void compact_range(const std::string& prefix, const std::string& start,
const std::string& end) override {
compact_range(combine_strings(prefix, start), combine_strings(prefix, end));
}
void compact_range_async(const std::string& prefix, const std::string& start,
const std::string& end) override {
compact_range_async(combine_strings(prefix, start), combine_strings(prefix, end));
}
RocksDBStore(CephContext *c, const std::string &path, std::map<std::string,std::string> opt, void *p) :
cct(c),
logger(NULL),
path(path),
kv_options(opt),
priv(p),
db(NULL),
env(static_cast<rocksdb::Env*>(p)),
comparator(nullptr),
dbstats(NULL),
compact_queue_stop(false),
compact_thread(this),
compact_on_mount(false),
disableWAL(false)
{}
~RocksDBStore() override;
static bool check_omap_dir(std::string &omap_dir);
/// Opens underlying db
int open(std::ostream &out, const std::string& cfs="") override {
return do_open(out, false, false, cfs);
}
/// Creates underlying db if missing and opens it
int create_and_open(std::ostream &out,
const std::string& cfs="") override;
int open_read_only(std::ostream &out, const std::string& cfs="") override {
return do_open(out, false, true, cfs);
}
void close() override;
int repair(std::ostream &out) override;
void split_stats(const std::string &s, char delim, std::vector<std::string> &elems);
void get_statistics(ceph::Formatter *f) override;
PerfCounters *get_perf_counters() override
{
return logger;
}
bool get_property(
const std::string &property,
uint64_t *out) final;
int64_t estimate_prefix_size(const std::string& prefix,
const std::string& key_prefix) override;
struct RocksWBHandler;
class RocksDBTransactionImpl : public KeyValueDB::TransactionImpl {
public:
rocksdb::WriteBatch bat;
RocksDBStore *db;
explicit RocksDBTransactionImpl(RocksDBStore *_db);
private:
void put_bat(
rocksdb::WriteBatch& bat,
rocksdb::ColumnFamilyHandle *cf,
const std::string &k,
const ceph::bufferlist &to_set_bl);
public:
void set(
const std::string &prefix,
const std::string &k,
const ceph::bufferlist &bl) override;
void set(
const std::string &prefix,
const char *k,
size_t keylen,
const ceph::bufferlist &bl) override;
void rmkey(
const std::string &prefix,
const std::string &k) override;
void rmkey(
const std::string &prefix,
const char *k,
size_t keylen) override;
void rm_single_key(
const std::string &prefix,
const std::string &k) override;
void rmkeys_by_prefix(
const std::string &prefix
) override;
void rm_range_keys(
const std::string &prefix,
const std::string &start,
const std::string &end) override;
void merge(
const std::string& prefix,
const std::string& k,
const ceph::bufferlist &bl) override;
};
KeyValueDB::Transaction get_transaction() override {
return std::make_shared<RocksDBTransactionImpl>(this);
}
int submit_transaction(KeyValueDB::Transaction t) override;
int submit_transaction_sync(KeyValueDB::Transaction t) override;
int get(
const std::string &prefix,
const std::set<std::string> &key,
std::map<std::string, ceph::bufferlist> *out
) override;
int get(
const std::string &prefix,
const std::string &key,
ceph::bufferlist *out
) override;
int get(
const std::string &prefix,
const char *key,
size_t keylen,
ceph::bufferlist *out) override;
class RocksDBWholeSpaceIteratorImpl :
public KeyValueDB::WholeSpaceIteratorImpl {
protected:
rocksdb::Iterator *dbiter;
public:
explicit RocksDBWholeSpaceIteratorImpl(const RocksDBStore* db,
rocksdb::ColumnFamilyHandle* cf,
const KeyValueDB::IteratorOpts opts)
{
rocksdb::ReadOptions options = rocksdb::ReadOptions();
if (opts & ITERATOR_NOCACHE)
options.fill_cache=false;
dbiter = db->db->NewIterator(options, cf);
}
~RocksDBWholeSpaceIteratorImpl() override;
int seek_to_first() override;
int seek_to_first(const std::string &prefix) override;
int seek_to_last() override;
int seek_to_last(const std::string &prefix) override;
int upper_bound(const std::string &prefix, const std::string &after) override;
int lower_bound(const std::string &prefix, const std::string &to) override;
bool valid() override;
int next() override;
int prev() override;
std::string key() override;
std::pair<std::string,std::string> raw_key() override;
bool raw_key_is_prefixed(const std::string &prefix) override;
ceph::bufferlist value() override;
ceph::bufferptr value_as_ptr() override;
int status() override;
size_t key_size() override;
size_t value_size() override;
};
Iterator get_iterator(const std::string& prefix, IteratorOpts opts = 0, IteratorBounds = IteratorBounds()) override;
private:
/// this iterator spans single cf
WholeSpaceIterator new_shard_iterator(rocksdb::ColumnFamilyHandle* cf);
Iterator new_shard_iterator(rocksdb::ColumnFamilyHandle* cf,
const std::string& prefix, IteratorBounds bound);
public:
/// Utility
static std::string combine_strings(const std::string &prefix, const std::string &value) {
std::string out = prefix;
out.push_back(0);
out.append(value);
return out;
}
static void combine_strings(const std::string &prefix,
const char *key, size_t keylen,
std::string *out) {
out->reserve(prefix.size() + 1 + keylen);
*out = prefix;
out->push_back(0);
out->append(key, keylen);
}
static int split_key(rocksdb::Slice in, std::string *prefix, std::string *key);
static std::string past_prefix(const std::string &prefix);
class MergeOperatorRouter;
class MergeOperatorLinker;
friend class MergeOperatorRouter;
int set_merge_operator(
const std::string& prefix,
std::shared_ptr<KeyValueDB::MergeOperator> mop) override;
std::string assoc_name; ///< Name of associative operator
uint64_t get_estimated_size(std::map<std::string,uint64_t> &extra) override {
DIR *store_dir = opendir(path.c_str());
if (!store_dir) {
lderr(cct) << __func__ << " something happened opening the store: "
<< cpp_strerror(errno) << dendl;
return 0;
}
uint64_t total_size = 0;
uint64_t sst_size = 0;
uint64_t log_size = 0;
uint64_t misc_size = 0;
struct dirent *entry = NULL;
while ((entry = readdir(store_dir)) != NULL) {
std::string n(entry->d_name);
if (n == "." || n == "..")
continue;
std::string fpath = path + '/' + n;
struct stat s;
int err = stat(fpath.c_str(), &s);
if (err < 0)
err = -errno;
// we may race against rocksdb while reading files; this should only
// happen when those files are being updated, data is being shuffled
// and files get removed, in which case there's not much of a problem
// as we'll get to them next time around.
if (err == -ENOENT) {
continue;
}
if (err < 0) {
lderr(cct) << __func__ << " error obtaining stats for " << fpath
<< ": " << cpp_strerror(err) << dendl;
goto err;
}
size_t pos = n.find_last_of('.');
if (pos == std::string::npos) {
misc_size += s.st_size;
continue;
}
std::string ext = n.substr(pos+1);
if (ext == "sst") {
sst_size += s.st_size;
} else if (ext == "log") {
log_size += s.st_size;
} else {
misc_size += s.st_size;
}
}
total_size = sst_size + log_size + misc_size;
extra["sst"] = sst_size;
extra["log"] = log_size;
extra["misc"] = misc_size;
extra["total"] = total_size;
err:
closedir(store_dir);
return total_size;
}
virtual int64_t get_cache_usage() const override {
return static_cast<int64_t>(bbt_opts.block_cache->GetUsage());
}
virtual int64_t get_cache_usage(std::string prefix) const override {
auto it = cf_bbt_opts.find(prefix);
if (it != cf_bbt_opts.end() && it->second.block_cache) {
return static_cast<int64_t>(it->second.block_cache->GetUsage());
}
return -EINVAL;
}
int set_cache_size(uint64_t s) override {
cache_size = s;
set_cache_flag = true;
return 0;
}
virtual std::shared_ptr<PriorityCache::PriCache>
get_priority_cache() const override {
return std::dynamic_pointer_cast<PriorityCache::PriCache>(
bbt_opts.block_cache);
}
virtual std::shared_ptr<PriorityCache::PriCache>
get_priority_cache(std::string prefix) const override {
auto it = cf_bbt_opts.find(prefix);
if (it != cf_bbt_opts.end()) {
return std::dynamic_pointer_cast<PriorityCache::PriCache>(
it->second.block_cache);
}
return nullptr;
}
WholeSpaceIterator get_wholespace_iterator(IteratorOpts opts = 0) override;
private:
WholeSpaceIterator get_default_cf_iterator();
using cf_deleter_t = std::function<void(rocksdb::ColumnFamilyHandle*)>;
using columns_t = std::map<std::string,
std::unique_ptr<rocksdb::ColumnFamilyHandle,
cf_deleter_t>>;
int prepare_for_reshard(const std::string& new_sharding,
columns_t& to_process_columns);
int reshard_cleanup(const columns_t& current_columns);
public:
struct resharding_ctrl {
size_t bytes_per_iterator = 10000000; /// amount of data to process before refreshing iterator
size_t keys_per_iterator = 10000;
size_t bytes_per_batch = 1000000; /// amount of data before submitting batch
size_t keys_per_batch = 1000;
bool unittest_fail_after_first_batch = false;
bool unittest_fail_after_processing_column = false;
bool unittest_fail_after_successful_processing = false;
};
int reshard(const std::string& new_sharding, const resharding_ctrl* ctrl = nullptr);
bool get_sharding(std::string& sharding);
};
#endif
| 18,549 | 32.605072 | 133 | h |
null | ceph-main/src/kv/rocksdb_cache/BinnedLRUCache.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
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef ROCKSDB_BINNED_LRU_CACHE
#define ROCKSDB_BINNED_LRU_CACHE
#include <string>
#include <mutex>
#include <boost/circular_buffer.hpp>
#include "ShardedCache.h"
#include "common/autovector.h"
#include "common/dout.h"
#include "include/ceph_assert.h"
#include "common/ceph_context.h"
namespace rocksdb_cache {
// LRU cache implementation
// An entry is a variable length heap-allocated structure.
// Entries are referenced by cache and/or by any external entity.
// The cache keeps all its entries in table. Some elements
// are also stored on LRU list.
//
// BinnedLRUHandle can be in these states:
// 1. Referenced externally AND in hash table.
// In that case the entry is *not* in the LRU. (refs > 1 && in_cache == true)
// 2. Not referenced externally and in hash table. In that case the entry is
// in the LRU and can be freed. (refs == 1 && in_cache == true)
// 3. Referenced externally and not in hash table. In that case the entry is
// in not on LRU and not in table. (refs >= 1 && in_cache == false)
//
// All newly created BinnedLRUHandles are in state 1. If you call
// BinnedLRUCacheShard::Release
// on entry in state 1, it will go into state 2. To move from state 1 to
// state 3, either call BinnedLRUCacheShard::Erase or BinnedLRUCacheShard::Insert with the
// same key.
// To move from state 2 to state 1, use BinnedLRUCacheShard::Lookup.
// Before destruction, make sure that no handles are in state 1. This means
// that any successful BinnedLRUCacheShard::Lookup/BinnedLRUCacheShard::Insert have a
// matching
// RUCache::Release (to move into state 2) or BinnedLRUCacheShard::Erase (for state 3)
std::shared_ptr<rocksdb::Cache> NewBinnedLRUCache(
CephContext *c,
size_t capacity,
int num_shard_bits = -1,
bool strict_capacity_limit = false,
double high_pri_pool_ratio = 0.0);
struct BinnedLRUHandle {
std::shared_ptr<uint64_t> age_bin;
void* value;
DeleterFn deleter;
BinnedLRUHandle* next_hash;
BinnedLRUHandle* next;
BinnedLRUHandle* prev;
size_t charge; // TODO(opt): Only allow uint32_t?
size_t key_length;
uint32_t refs; // a number of refs to this entry
// cache itself is counted as 1
// Include the following flags:
// in_cache: whether this entry is referenced by the hash table.
// is_high_pri: whether this entry is high priority entry.
// in_high_pri_pool: whether this entry is in high-pri pool.
char flags;
uint32_t hash; // Hash of key(); used for fast sharding and comparisons
char* key_data = nullptr; // Beginning of key
rocksdb::Slice key() const {
// For cheaper lookups, we allow a temporary Handle object
// to store a pointer to a key in "value".
if (next == this) {
return *(reinterpret_cast<rocksdb::Slice*>(value));
} else {
return rocksdb::Slice(key_data, key_length);
}
}
bool InCache() { return flags & 1; }
bool IsHighPri() { return flags & 2; }
bool InHighPriPool() { return flags & 4; }
bool HasHit() { return flags & 8; }
void SetInCache(bool in_cache) {
if (in_cache) {
flags |= 1;
} else {
flags &= ~1;
}
}
void SetPriority(rocksdb::Cache::Priority priority) {
if (priority == rocksdb::Cache::Priority::HIGH) {
flags |= 2;
} else {
flags &= ~2;
}
}
void SetInHighPriPool(bool in_high_pri_pool) {
if (in_high_pri_pool) {
flags |= 4;
} else {
flags &= ~4;
}
}
void SetHit() { flags |= 8; }
void Free() {
ceph_assert((refs == 1 && InCache()) || (refs == 0 && !InCache()));
if (deleter) {
(*deleter)(key(), value);
}
delete[] key_data;
delete this;
}
};
// We provide our own simple hash table since it removes a whole bunch
// of porting hacks and is also faster than some of the built-in hash
// table implementations in some of the compiler/runtime combinations
// we have tested. E.g., readrandom speeds up by ~5% over the g++
// 4.4.3's builtin hashtable.
class BinnedLRUHandleTable {
public:
BinnedLRUHandleTable();
~BinnedLRUHandleTable();
BinnedLRUHandle* Lookup(const rocksdb::Slice& key, uint32_t hash);
BinnedLRUHandle* Insert(BinnedLRUHandle* h);
BinnedLRUHandle* Remove(const rocksdb::Slice& key, uint32_t hash);
template <typename T>
void ApplyToAllCacheEntries(T func) {
for (uint32_t i = 0; i < length_; i++) {
BinnedLRUHandle* h = list_[i];
while (h != nullptr) {
auto n = h->next_hash;
ceph_assert(h->InCache());
func(h);
h = n;
}
}
}
private:
// Return a pointer to slot that points to a cache entry that
// matches key/hash. If there is no such cache entry, return a
// pointer to the trailing slot in the corresponding linked list.
BinnedLRUHandle** FindPointer(const rocksdb::Slice& key, uint32_t hash);
void Resize();
// The table consists of an array of buckets where each bucket is
// a linked list of cache entries that hash into the bucket.
BinnedLRUHandle** list_;
uint32_t length_;
uint32_t elems_;
};
// A single shard of sharded cache.
class alignas(CACHE_LINE_SIZE) BinnedLRUCacheShard : public CacheShard {
public:
BinnedLRUCacheShard(CephContext *c, size_t capacity, bool strict_capacity_limit,
double high_pri_pool_ratio);
virtual ~BinnedLRUCacheShard();
// Separate from constructor so caller can easily make an array of BinnedLRUCache
// if current usage is more than new capacity, the function will attempt to
// free the needed space
virtual void SetCapacity(size_t capacity) override;
// Set the flag to reject insertion if cache if full.
virtual void SetStrictCapacityLimit(bool strict_capacity_limit) override;
// Set percentage of capacity reserved for high-pri cache entries.
void SetHighPriPoolRatio(double high_pri_pool_ratio);
// Like Cache methods, but with an extra "hash" parameter.
virtual rocksdb::Status Insert(const rocksdb::Slice& key, uint32_t hash, void* value,
size_t charge,
DeleterFn deleter,
rocksdb::Cache::Handle** handle,
rocksdb::Cache::Priority priority) override;
virtual rocksdb::Cache::Handle* Lookup(const rocksdb::Slice& key, uint32_t hash) override;
virtual bool Ref(rocksdb::Cache::Handle* handle) override;
virtual bool Release(rocksdb::Cache::Handle* handle,
bool force_erase = false) override;
virtual void Erase(const rocksdb::Slice& key, uint32_t hash) override;
// Although in some platforms the update of size_t is atomic, to make sure
// GetUsage() and GetPinnedUsage() work correctly under any platform, we'll
// protect them with mutex_.
virtual size_t GetUsage() const override;
virtual size_t GetPinnedUsage() const override;
virtual void ApplyToAllCacheEntries(
const std::function<void(const rocksdb::Slice& key,
void* value,
size_t charge,
DeleterFn)>& callback,
bool thread_safe) override;
virtual void EraseUnRefEntries() override;
virtual std::string GetPrintableOptions() const override;
virtual DeleterFn GetDeleter(rocksdb::Cache::Handle* handle) const override;
void TEST_GetLRUList(BinnedLRUHandle** lru, BinnedLRUHandle** lru_low_pri);
// Retrieves number of elements in LRU, for unit test purpose only
// not threadsafe
size_t TEST_GetLRUSize();
// Retrieves high pri pool ratio
double GetHighPriPoolRatio() const;
// Retrieves high pri pool usage
size_t GetHighPriPoolUsage() const;
// Rotate the bins
void shift_bins();
// Get the bin count
uint32_t get_bin_count() const;
// Set the bin count
void set_bin_count(uint32_t count);
// Get the byte counts for a range of age bins
uint64_t sum_bins(uint32_t start, uint32_t end) const;
private:
CephContext *cct;
void LRU_Remove(BinnedLRUHandle* e);
void LRU_Insert(BinnedLRUHandle* e);
// Overflow the last entry in high-pri pool to low-pri pool until size of
// high-pri pool is no larger than the size specify by high_pri_pool_pct.
void MaintainPoolSize();
// Just reduce the reference count by 1.
// Return true if last reference
bool Unref(BinnedLRUHandle* e);
// Free some space following strict LRU policy until enough space
// to hold (usage_ + charge) is freed or the lru list is empty
// This function is not thread safe - it needs to be executed while
// holding the mutex_
void EvictFromLRU(size_t charge, ceph::autovector<BinnedLRUHandle*>* deleted);
// Initialized before use.
size_t capacity_;
// Memory size for entries in high-pri pool.
size_t high_pri_pool_usage_;
// Whether to reject insertion if cache reaches its full capacity.
bool strict_capacity_limit_;
// Ratio of capacity reserved for high priority cache entries.
double high_pri_pool_ratio_;
// High-pri pool size, equals to capacity * high_pri_pool_ratio.
// Remember the value to avoid recomputing each time.
double high_pri_pool_capacity_;
// Dummy head of LRU list.
// lru.prev is newest entry, lru.next is oldest entry.
// LRU contains items which can be evicted, ie reference only by cache
BinnedLRUHandle lru_;
// Pointer to head of low-pri pool in LRU list.
BinnedLRUHandle* lru_low_pri_;
// ------------^^^^^^^^^^^^^-----------
// Not frequently modified data members
// ------------------------------------
//
// We separate data members that are updated frequently from the ones that
// are not frequently updated so that they don't share the same cache line
// which will lead into false cache sharing
//
// ------------------------------------
// Frequently modified data members
// ------------vvvvvvvvvvvvv-----------
BinnedLRUHandleTable table_;
// Memory size for entries residing in the cache
size_t usage_;
// Memory size for entries residing only in the LRU list
size_t lru_usage_;
// mutex_ protects the following state.
// We don't count mutex_ as the cache's internal state so semantically we
// don't mind mutex_ invoking the non-const actions.
mutable std::mutex mutex_;
// Circular buffer of byte counters for age binning
boost::circular_buffer<std::shared_ptr<uint64_t>> age_bins;
};
class BinnedLRUCache : public ShardedCache {
public:
BinnedLRUCache(CephContext *c, size_t capacity, int num_shard_bits,
bool strict_capacity_limit, double high_pri_pool_ratio);
virtual ~BinnedLRUCache();
virtual const char* Name() const override { return "BinnedLRUCache"; }
virtual CacheShard* GetShard(int shard) override;
virtual const CacheShard* GetShard(int shard) const override;
virtual void* Value(Handle* handle) override;
virtual size_t GetCharge(Handle* handle) const override;
virtual uint32_t GetHash(Handle* handle) const override;
virtual void DisownData() override;
#if (ROCKSDB_MAJOR >= 7 || (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR >= 22))
virtual DeleterFn GetDeleter(Handle* handle) const override;
#endif
// Retrieves number of elements in LRU, for unit test purpose only
size_t TEST_GetLRUSize();
// Sets the high pri pool ratio
void SetHighPriPoolRatio(double high_pri_pool_ratio);
// Retrieves high pri pool ratio
double GetHighPriPoolRatio() const;
// Retrieves high pri pool usage
size_t GetHighPriPoolUsage() const;
// PriorityCache
virtual int64_t request_cache_bytes(
PriorityCache::Priority pri, uint64_t total_cache) const;
virtual int64_t commit_cache_size(uint64_t total_cache);
virtual int64_t get_committed_size() const {
return GetCapacity();
}
virtual void shift_bins();
uint64_t sum_bins(uint32_t start, uint32_t end) const;
uint32_t get_bin_count() const;
void set_bin_count(uint32_t count);
virtual std::string get_cache_name() const {
return "RocksDB Binned LRU Cache";
}
private:
CephContext *cct;
BinnedLRUCacheShard* shards_;
int num_shards_ = 0;
};
} // namespace rocksdb_cache
#endif // ROCKSDB_BINNED_LRU_CACHE
| 12,504 | 33.073569 | 92 | h |
null | ceph-main/src/kv/rocksdb_cache/ShardedCache.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
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef ROCKSDB_SHARDED_CACHE
#define ROCKSDB_SHARDED_CACHE
#include <atomic>
#include <string>
#include <mutex>
#include "rocksdb/version.h"
#include "rocksdb/cache.h"
#include "include/ceph_hash.h"
#include "common/PriorityCache.h"
//#include "hash.h"
#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 64 // XXX arch-specific define
#endif
namespace rocksdb_cache {
using DeleterFn = void (*)(const rocksdb::Slice& key, void* value);
// Single cache shard interface.
class CacheShard {
public:
CacheShard() = default;
virtual ~CacheShard() = default;
virtual rocksdb::Status Insert(const rocksdb::Slice& key, uint32_t hash, void* value,
size_t charge,
DeleterFn deleter,
rocksdb::Cache::Handle** handle, rocksdb::Cache::Priority priority) = 0;
virtual rocksdb::Cache::Handle* Lookup(const rocksdb::Slice& key, uint32_t hash) = 0;
virtual bool Ref(rocksdb::Cache::Handle* handle) = 0;
virtual bool Release(rocksdb::Cache::Handle* handle, bool force_erase = false) = 0;
virtual void Erase(const rocksdb::Slice& key, uint32_t hash) = 0;
virtual void SetCapacity(size_t capacity) = 0;
virtual void SetStrictCapacityLimit(bool strict_capacity_limit) = 0;
virtual size_t GetUsage() const = 0;
virtual size_t GetPinnedUsage() const = 0;
virtual void ApplyToAllCacheEntries(
const std::function<void(const rocksdb::Slice& key,
void* value,
size_t charge,
DeleterFn)>& callback,
bool thread_safe) = 0;
virtual void EraseUnRefEntries() = 0;
virtual std::string GetPrintableOptions() const { return ""; }
virtual DeleterFn GetDeleter(rocksdb::Cache::Handle* handle) const = 0;
};
// Generic cache interface which shards cache by hash of keys. 2^num_shard_bits
// shards will be created, with capacity split evenly to each of the shards.
// Keys are sharded by the highest num_shard_bits bits of hash value.
class ShardedCache : public rocksdb::Cache, public PriorityCache::PriCache {
public:
ShardedCache(size_t capacity, int num_shard_bits, bool strict_capacity_limit);
virtual ~ShardedCache() = default;
// rocksdb::Cache
virtual const char* Name() const override = 0;
virtual rocksdb::Status Insert(const rocksdb::Slice& key, void* value, size_t charge,
DeleterFn,
rocksdb::Cache::Handle** handle, Priority priority) override;
virtual rocksdb::Cache::Handle* Lookup(const rocksdb::Slice& key, rocksdb::Statistics* stats) override;
virtual bool Ref(rocksdb::Cache::Handle* handle) override;
virtual bool Release(rocksdb::Cache::Handle* handle, bool force_erase = false) override;
virtual void* Value(Handle* handle) override = 0;
virtual void Erase(const rocksdb::Slice& key) override;
virtual uint64_t NewId() override;
virtual void SetCapacity(size_t capacity) override;
virtual void SetStrictCapacityLimit(bool strict_capacity_limit) override;
virtual bool HasStrictCapacityLimit() const override;
virtual size_t GetCapacity() const override;
virtual size_t GetUsage() const override;
virtual size_t GetUsage(rocksdb::Cache::Handle* handle) const override;
virtual size_t GetPinnedUsage() const override;
virtual size_t GetCharge(Handle* handle) const = 0;
#if (ROCKSDB_MAJOR >= 7 || (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR >= 22))
virtual DeleterFn GetDeleter(Handle* handle) const override;
#endif
virtual void DisownData() override = 0;
#if (ROCKSDB_MAJOR >= 7 || (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR >= 22))
virtual void ApplyToAllEntries(
const std::function<void(const rocksdb::Slice& key, void* value, size_t charge,
DeleterFn deleter)>& callback,
const ApplyToAllEntriesOptions& opts) override;
#else
virtual void ApplyToAllCacheEntries(void (*callback)(void*, size_t),
bool thread_safe) override;
#endif
virtual void EraseUnRefEntries() override;
virtual std::string GetPrintableOptions() const override;
virtual CacheShard* GetShard(int shard) = 0;
virtual const CacheShard* GetShard(int shard) const = 0;
virtual uint32_t GetHash(Handle* handle) const = 0;
int GetNumShardBits() const { return num_shard_bits_; }
virtual uint32_t get_bin_count() const = 0;
virtual void set_bin_count(uint32_t count) = 0;
// PriCache
virtual int64_t get_cache_bytes(PriorityCache::Priority pri) const {
return cache_bytes[pri];
}
virtual int64_t get_cache_bytes() const {
int64_t total = 0;
for (int i = 0; i < PriorityCache::Priority::LAST + 1; i++) {
PriorityCache::Priority pri = static_cast<PriorityCache::Priority>(i);
total += get_cache_bytes(pri);
}
return total;
}
virtual void set_cache_bytes(PriorityCache::Priority pri, int64_t bytes) {
cache_bytes[pri] = bytes;
}
virtual void add_cache_bytes(PriorityCache::Priority pri, int64_t bytes) {
cache_bytes[pri] += bytes;
}
virtual double get_cache_ratio() const {
return cache_ratio;
}
virtual void set_cache_ratio(double ratio) {
cache_ratio = ratio;
}
virtual uint64_t get_bins(PriorityCache::Priority pri) const {
if (pri > PriorityCache::Priority::PRI0 &&
pri < PriorityCache::Priority::LAST) {
return bins[pri];
}
return 0;
}
virtual void set_bins(PriorityCache::Priority pri, uint64_t end_bin) {
if (pri <= PriorityCache::Priority::PRI0 ||
pri >= PriorityCache::Priority::LAST) {
return;
}
bins[pri] = end_bin;
uint64_t max = 0;
for (int pri = 1; pri < PriorityCache::Priority::LAST; pri++) {
if (bins[pri] > max) {
max = bins[pri];
}
}
set_bin_count(max);
}
virtual void import_bins(const std::vector<uint64_t> &bins_v) {
uint64_t max = 0;
for (int pri = 1; pri < PriorityCache::Priority::LAST; pri++) {
unsigned i = (unsigned) pri - 1;
if (i < bins_v.size()) {
bins[pri] = bins_v[i];
if (bins[pri] > max) {
max = bins[pri];
}
} else {
bins[pri] = 0;
}
}
set_bin_count(max);
}
virtual std::string get_cache_name() const = 0;
private:
static inline uint32_t HashSlice(const rocksdb::Slice& s) {
return ceph_str_hash(CEPH_STR_HASH_RJENKINS, s.data(), s.size());
// return Hash(s.data(), s.size(), 0);
}
uint32_t Shard(uint32_t hash) const {
// Note, hash >> 32 yields hash in gcc, not the zero we expect!
return (num_shard_bits_ > 0) ? (hash >> (32 - num_shard_bits_)) : 0;
}
uint64_t bins[PriorityCache::Priority::LAST+1] = {0};
int64_t cache_bytes[PriorityCache::Priority::LAST+1] = {0};
double cache_ratio = 0;
int num_shard_bits_;
mutable std::mutex capacity_mutex_;
size_t capacity_;
bool strict_capacity_limit_;
std::atomic<uint64_t> last_id_;
};
extern int GetDefaultCacheShardBits(size_t capacity);
} // namespace rocksdb_cache
#endif // ROCKSDB_SHARDED_CACHE
| 7,499 | 36.878788 | 105 | h |
null | ceph-main/src/librados/AioCompletionImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2012 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_LIBRADOS_AIOCOMPLETIONIMPL_H
#define CEPH_LIBRADOS_AIOCOMPLETIONIMPL_H
#include "common/ceph_mutex.h"
#include "include/buffer.h"
#include "include/xlist.h"
#include "osd/osd_types.h"
class IoCtxImpl;
struct librados::AioCompletionImpl {
ceph::mutex lock = ceph::make_mutex("AioCompletionImpl lock", false);
ceph::condition_variable cond;
int ref = 1, rval = 0;
bool released = false;
bool complete = false;
version_t objver = 0;
ceph_tid_t tid = 0;
rados_callback_t callback_complete = nullptr, callback_safe = nullptr;
void *callback_complete_arg = nullptr, *callback_safe_arg = nullptr;
// for read
bool is_read = false;
bufferlist bl;
bufferlist *blp = nullptr;
char *out_buf = nullptr;
IoCtxImpl *io = nullptr;
ceph_tid_t aio_write_seq = 0;
xlist<AioCompletionImpl*>::item aio_write_list_item;
AioCompletionImpl() : aio_write_list_item(this) { }
int set_complete_callback(void *cb_arg, rados_callback_t cb) {
std::scoped_lock l{lock};
callback_complete = cb;
callback_complete_arg = cb_arg;
return 0;
}
int set_safe_callback(void *cb_arg, rados_callback_t cb) {
std::scoped_lock l{lock};
callback_safe = cb;
callback_safe_arg = cb_arg;
return 0;
}
int wait_for_complete() {
std::unique_lock l{lock};
cond.wait(l, [this] { return complete; });
return 0;
}
int wait_for_safe() {
return wait_for_complete();
}
int is_complete() {
std::scoped_lock l{lock};
return complete;
}
int is_safe() {
return is_complete();
}
int wait_for_complete_and_cb() {
std::unique_lock l{lock};
cond.wait(l, [this] { return complete && !callback_complete && !callback_safe; });
return 0;
}
int wait_for_safe_and_cb() {
return wait_for_complete_and_cb();
}
int is_complete_and_cb() {
std::scoped_lock l{lock};
return complete && !callback_complete && !callback_safe;
}
int is_safe_and_cb() {
return is_complete_and_cb();
}
int get_return_value() {
std::scoped_lock l{lock};
return rval;
}
uint64_t get_version() {
std::scoped_lock l{lock};
return objver;
}
void get() {
std::scoped_lock l{lock};
_get();
}
void _get() {
ceph_assert(ceph_mutex_is_locked(lock));
ceph_assert(ref > 0);
++ref;
}
void release() {
lock.lock();
ceph_assert(!released);
released = true;
put_unlock();
}
void put() {
lock.lock();
put_unlock();
}
void put_unlock() {
ceph_assert(ref > 0);
int n = --ref;
lock.unlock();
if (!n)
delete this;
}
};
namespace librados {
struct CB_AioComplete {
AioCompletionImpl *c;
explicit CB_AioComplete(AioCompletionImpl *cc) : c(cc) {
c->_get();
}
void operator()() {
rados_callback_t cb_complete = c->callback_complete;
void *cb_complete_arg = c->callback_complete_arg;
if (cb_complete)
cb_complete(c, cb_complete_arg);
rados_callback_t cb_safe = c->callback_safe;
void *cb_safe_arg = c->callback_safe_arg;
if (cb_safe)
cb_safe(c, cb_safe_arg);
c->lock.lock();
c->callback_complete = NULL;
c->callback_safe = NULL;
c->cond.notify_all();
c->put_unlock();
}
};
/**
* Fills in all completed request data, and calls both
* complete and safe callbacks if they exist.
*
* Not useful for usual I/O, but for special things like
* flush where we only want to wait for things to be safe,
* but allow users to specify any of the callbacks.
*/
struct CB_AioCompleteAndSafe {
AioCompletionImpl *c;
explicit CB_AioCompleteAndSafe(AioCompletionImpl *cc) : c(cc) {
c->get();
}
CB_AioCompleteAndSafe(const CB_AioCompleteAndSafe&) = delete;
CB_AioCompleteAndSafe& operator =(const CB_AioCompleteAndSafe&) = delete;
CB_AioCompleteAndSafe(CB_AioCompleteAndSafe&& rhs) {
c = rhs.c;
rhs.c = nullptr;
}
CB_AioCompleteAndSafe& operator =(CB_AioCompleteAndSafe&& rhs) {
c = rhs.c;
rhs.c = nullptr;
return *this;
}
void operator()(int r = 0) {
c->lock.lock();
c->rval = r;
c->complete = true;
c->lock.unlock();
rados_callback_t cb_complete = c->callback_complete;
void *cb_complete_arg = c->callback_complete_arg;
if (cb_complete)
cb_complete(c, cb_complete_arg);
rados_callback_t cb_safe = c->callback_safe;
void *cb_safe_arg = c->callback_safe_arg;
if (cb_safe)
cb_safe(c, cb_safe_arg);
c->lock.lock();
c->callback_complete = NULL;
c->callback_safe = NULL;
c->cond.notify_all();
c->put_unlock();
}
};
}
#endif
| 5,013 | 22.990431 | 86 | h |
null | ceph-main/src/librados/IoCtxImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2012 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_LIBRADOS_IOCTXIMPL_H
#define CEPH_LIBRADOS_IOCTXIMPL_H
#include <atomic>
#include "common/Cond.h"
#include "common/ceph_mutex.h"
#include "common/snap_types.h"
#include "common/zipkin_trace.h"
#include "include/types.h"
#include "include/rados/librados.h"
#include "include/rados/librados.hpp"
#include "include/xlist.h"
#include "osd/osd_types.h"
#include "osdc/Objecter.h"
class RadosClient;
struct librados::IoCtxImpl {
std::atomic<uint64_t> ref_cnt = { 0 };
RadosClient *client = nullptr;
int64_t poolid = 0;
snapid_t snap_seq;
::SnapContext snapc;
uint64_t assert_ver = 0;
version_t last_objver = 0;
uint32_t notify_timeout = 30;
object_locator_t oloc;
int extra_op_flags = 0;
ceph::mutex aio_write_list_lock =
ceph::make_mutex("librados::IoCtxImpl::aio_write_list_lock");
ceph_tid_t aio_write_seq = 0;
ceph::condition_variable aio_write_cond;
xlist<AioCompletionImpl*> aio_write_list;
std::map<ceph_tid_t, std::list<AioCompletionImpl*> > aio_write_waiters;
Objecter *objecter = nullptr;
IoCtxImpl();
IoCtxImpl(RadosClient *c, Objecter *objecter,
int64_t poolid, snapid_t s);
void dup(const IoCtxImpl& rhs) {
// Copy everything except the ref count
client = rhs.client;
poolid = rhs.poolid;
snap_seq = rhs.snap_seq;
snapc = rhs.snapc;
assert_ver = rhs.assert_ver;
last_objver = rhs.last_objver;
notify_timeout = rhs.notify_timeout;
oloc = rhs.oloc;
extra_op_flags = rhs.extra_op_flags;
objecter = rhs.objecter;
}
void set_snap_read(snapid_t s);
int set_snap_write_context(snapid_t seq, std::vector<snapid_t>& snaps);
void get() {
ref_cnt++;
}
void put() {
if (--ref_cnt == 0)
delete this;
}
void queue_aio_write(struct AioCompletionImpl *c);
void complete_aio_write(struct AioCompletionImpl *c);
void flush_aio_writes_async(AioCompletionImpl *c);
void flush_aio_writes();
int64_t get_id() {
return poolid;
}
std::string get_cached_pool_name();
int get_object_hash_position(const std::string& oid, uint32_t *hash_position);
int get_object_pg_hash_position(const std::string& oid, uint32_t *pg_hash_position);
::ObjectOperation *prepare_assert_ops(::ObjectOperation *op);
// snaps
int snap_list(std::vector<uint64_t> *snaps);
int snap_lookup(const char *name, uint64_t *snapid);
int snap_get_name(uint64_t snapid, std::string *s);
int snap_get_stamp(uint64_t snapid, time_t *t);
int snap_create(const char* snapname);
int selfmanaged_snap_create(uint64_t *snapid);
void aio_selfmanaged_snap_create(uint64_t *snapid, AioCompletionImpl *c);
int snap_remove(const char* snapname);
int rollback(const object_t& oid, const char *snapName);
int selfmanaged_snap_remove(uint64_t snapid);
void aio_selfmanaged_snap_remove(uint64_t snapid, AioCompletionImpl *c);
int selfmanaged_snap_rollback_object(const object_t& oid,
::SnapContext& snapc, uint64_t snapid);
// io
int nlist(Objecter::NListContext *context, int max_entries);
uint32_t nlist_seek(Objecter::NListContext *context, uint32_t pos);
uint32_t nlist_seek(Objecter::NListContext *context, const rados_object_list_cursor& cursor);
rados_object_list_cursor nlist_get_cursor(Objecter::NListContext *context);
void object_list_slice(
const hobject_t start,
const hobject_t finish,
const size_t n,
const size_t m,
hobject_t *split_start,
hobject_t *split_finish);
int create(const object_t& oid, bool exclusive);
int write(const object_t& oid, bufferlist& bl, size_t len, uint64_t off);
int append(const object_t& oid, bufferlist& bl, size_t len);
int write_full(const object_t& oid, bufferlist& bl);
int writesame(const object_t& oid, bufferlist& bl,
size_t write_len, uint64_t offset);
int read(const object_t& oid, bufferlist& bl, size_t len, uint64_t off);
int mapext(const object_t& oid, uint64_t off, size_t len,
std::map<uint64_t,uint64_t>& m);
int sparse_read(const object_t& oid, std::map<uint64_t,uint64_t>& m,
bufferlist& bl, size_t len, uint64_t off);
int checksum(const object_t& oid, uint8_t type, const bufferlist &init_value,
size_t len, uint64_t off, size_t chunk_size, bufferlist *pbl);
int remove(const object_t& oid);
int remove(const object_t& oid, int flags);
int stat(const object_t& oid, uint64_t *psize, time_t *pmtime);
int stat2(const object_t& oid, uint64_t *psize, struct timespec *pts);
int trunc(const object_t& oid, uint64_t size);
int cmpext(const object_t& oid, uint64_t off, bufferlist& cmp_bl);
int tmap_update(const object_t& oid, bufferlist& cmdbl);
int exec(const object_t& oid, const char *cls, const char *method, bufferlist& inbl, bufferlist& outbl);
int getxattr(const object_t& oid, const char *name, bufferlist& bl);
int setxattr(const object_t& oid, const char *name, bufferlist& bl);
int getxattrs(const object_t& oid, std::map<std::string, bufferlist>& attrset);
int rmxattr(const object_t& oid, const char *name);
int operate(const object_t& oid, ::ObjectOperation *o, ceph::real_time *pmtime, int flags=0);
int operate_read(const object_t& oid, ::ObjectOperation *o, bufferlist *pbl, int flags=0);
int aio_operate(const object_t& oid, ::ObjectOperation *o,
AioCompletionImpl *c, const SnapContext& snap_context,
const ceph::real_time *pmtime, int flags,
const blkin_trace_info *trace_info = nullptr);
int aio_operate_read(const object_t& oid, ::ObjectOperation *o,
AioCompletionImpl *c, int flags, bufferlist *pbl, const blkin_trace_info *trace_info = nullptr);
struct C_aio_stat_Ack : public Context {
librados::AioCompletionImpl *c;
time_t *pmtime;
ceph::real_time mtime;
C_aio_stat_Ack(AioCompletionImpl *_c, time_t *pm);
void finish(int r) override;
};
struct C_aio_stat2_Ack : public Context {
librados::AioCompletionImpl *c;
struct timespec *pts;
ceph::real_time mtime;
C_aio_stat2_Ack(AioCompletionImpl *_c, struct timespec *pts);
void finish(int r) override;
};
struct C_aio_Complete : public Context {
#if defined(WITH_EVENTTRACE)
object_t oid;
#endif
AioCompletionImpl *c;
explicit C_aio_Complete(AioCompletionImpl *_c);
void finish(int r) override;
};
int aio_read(const object_t oid, AioCompletionImpl *c,
bufferlist *pbl, size_t len, uint64_t off, uint64_t snapid,
const blkin_trace_info *info = nullptr);
int aio_read(object_t oid, AioCompletionImpl *c,
char *buf, size_t len, uint64_t off, uint64_t snapid,
const blkin_trace_info *info = nullptr);
int aio_sparse_read(const object_t oid, AioCompletionImpl *c,
std::map<uint64_t,uint64_t> *m, bufferlist *data_bl,
size_t len, uint64_t off, uint64_t snapid);
int aio_cmpext(const object_t& oid, AioCompletionImpl *c, uint64_t off,
bufferlist& cmp_bl);
int aio_cmpext(const object_t& oid, AioCompletionImpl *c,
const char *cmp_buf, size_t cmp_len, uint64_t off);
int aio_write(const object_t &oid, AioCompletionImpl *c,
const bufferlist& bl, size_t len, uint64_t off,
const blkin_trace_info *info = nullptr);
int aio_append(const object_t &oid, AioCompletionImpl *c,
const bufferlist& bl, size_t len);
int aio_write_full(const object_t &oid, AioCompletionImpl *c,
const bufferlist& bl);
int aio_writesame(const object_t &oid, AioCompletionImpl *c,
const bufferlist& bl, size_t write_len, uint64_t off);
int aio_remove(const object_t &oid, AioCompletionImpl *c, int flags=0);
int aio_exec(const object_t& oid, AioCompletionImpl *c, const char *cls,
const char *method, bufferlist& inbl, bufferlist *outbl);
int aio_exec(const object_t& oid, AioCompletionImpl *c, const char *cls,
const char *method, bufferlist& inbl, char *buf, size_t out_len);
int aio_stat(const object_t& oid, AioCompletionImpl *c, uint64_t *psize, time_t *pmtime);
int aio_stat2(const object_t& oid, AioCompletionImpl *c, uint64_t *psize, struct timespec *pts);
int aio_getxattr(const object_t& oid, AioCompletionImpl *c,
const char *name, bufferlist& bl);
int aio_setxattr(const object_t& oid, AioCompletionImpl *c,
const char *name, bufferlist& bl);
int aio_getxattrs(const object_t& oid, AioCompletionImpl *c,
std::map<std::string, bufferlist>& attrset);
int aio_rmxattr(const object_t& oid, AioCompletionImpl *c,
const char *name);
int aio_cancel(AioCompletionImpl *c);
int hit_set_list(uint32_t hash, AioCompletionImpl *c,
std::list< std::pair<time_t, time_t> > *pls);
int hit_set_get(uint32_t hash, AioCompletionImpl *c, time_t stamp,
bufferlist *pbl);
int get_inconsistent_objects(const pg_t& pg,
const librados::object_id_t& start_after,
uint64_t max_to_get,
AioCompletionImpl *c,
std::vector<inconsistent_obj_t>* objects,
uint32_t* interval);
int get_inconsistent_snapsets(const pg_t& pg,
const librados::object_id_t& start_after,
uint64_t max_to_get,
AioCompletionImpl *c,
std::vector<inconsistent_snapset_t>* snapsets,
uint32_t* interval);
void set_sync_op_version(version_t ver);
int watch(const object_t& oid, uint64_t *cookie, librados::WatchCtx *ctx,
librados::WatchCtx2 *ctx2, bool internal = false);
int watch(const object_t& oid, uint64_t *cookie, librados::WatchCtx *ctx,
librados::WatchCtx2 *ctx2, uint32_t timeout, bool internal = false);
int aio_watch(const object_t& oid, AioCompletionImpl *c, uint64_t *cookie,
librados::WatchCtx *ctx, librados::WatchCtx2 *ctx2,
bool internal = false);
int aio_watch(const object_t& oid, AioCompletionImpl *c, uint64_t *cookie,
librados::WatchCtx *ctx, librados::WatchCtx2 *ctx2,
uint32_t timeout, bool internal = false);
int watch_check(uint64_t cookie);
int unwatch(uint64_t cookie);
int aio_unwatch(uint64_t cookie, AioCompletionImpl *c);
int notify(const object_t& oid, bufferlist& bl, uint64_t timeout_ms,
bufferlist *preplybl, char **preply_buf, size_t *preply_buf_len);
int notify_ack(const object_t& oid, uint64_t notify_id, uint64_t cookie,
bufferlist& bl);
int aio_notify(const object_t& oid, AioCompletionImpl *c, bufferlist& bl,
uint64_t timeout_ms, bufferlist *preplybl, char **preply_buf,
size_t *preply_buf_len);
int set_alloc_hint(const object_t& oid,
uint64_t expected_object_size,
uint64_t expected_write_size,
uint32_t flags);
version_t last_version();
void set_assert_version(uint64_t ver);
void set_notify_timeout(uint32_t timeout);
int cache_pin(const object_t& oid);
int cache_unpin(const object_t& oid);
int application_enable(const std::string& app_name, bool force);
void application_enable_async(const std::string& app_name, bool force,
PoolAsyncCompletionImpl *c);
int application_list(std::set<std::string> *app_names);
int application_metadata_get(const std::string& app_name,
const std::string &key,
std::string* value);
int application_metadata_set(const std::string& app_name,
const std::string &key,
const std::string& value);
int application_metadata_remove(const std::string& app_name,
const std::string &key);
int application_metadata_list(const std::string& app_name,
std::map<std::string, std::string> *values);
};
#endif
| 12,110 | 39.23588 | 106 | h |
null | ceph-main/src/librados/ListObjectImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 David Zafman <[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_LIBRADOS_LISTOBJECTIMPL_H
#define CEPH_LIBRADOS_LISTOBJECTIMPL_H
#include <string>
#include <include/rados/librados.hpp>
namespace librados {
struct ListObjectImpl {
std::string nspace;
std::string oid;
std::string locator;
ListObjectImpl() {}
ListObjectImpl(std::string n, std::string o, std::string l):
nspace(n), oid(o), locator(l) {}
auto operator<=>(const ListObjectImpl&) const = default;
const std::string& get_nspace() const { return nspace; }
const std::string& get_oid() const { return oid; }
const std::string& get_locator() const { return locator; }
};
inline std::ostream& operator<<(std::ostream& out, const struct ListObjectImpl& lop) {
out << (lop.nspace.size() ? lop.nspace + "/" : "") << lop.oid
<< (lop.locator.size() ? "@" + lop.locator : "");
return out;
}
class NObjectIteratorImpl {
public:
NObjectIteratorImpl() {}
~NObjectIteratorImpl();
NObjectIteratorImpl(const NObjectIteratorImpl &rhs);
NObjectIteratorImpl& operator=(const NObjectIteratorImpl& rhs);
bool operator==(const NObjectIteratorImpl& rhs) const;
bool operator!=(const NObjectIteratorImpl& rhs) const;
const ListObject& operator*() const;
const ListObject* operator->() const;
NObjectIteratorImpl &operator++(); // Preincrement
NObjectIteratorImpl operator++(int); // Postincrement
const ListObject *get_listobjectp() { return &cur_obj; }
/// get current hash position of the iterator, rounded to the current pg
uint32_t get_pg_hash_position() const;
/// move the iterator to a given hash position. this may (will!) be rounded to the nearest pg.
uint32_t seek(uint32_t pos);
/// move the iterator to a given cursor position
uint32_t seek(const librados::ObjectCursor& cursor);
/// get current cursor position
librados::ObjectCursor get_cursor();
void set_filter(const bufferlist &bl);
NObjectIteratorImpl(ObjListCtx *ctx_);
void get_next();
std::shared_ptr < ObjListCtx > ctx;
ListObject cur_obj;
};
}
#endif
| 2,482 | 30.0375 | 99 | h |
null | ceph-main/src/librados/ObjectOperationImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "common/ceph_time.h"
#include "osdc/Objecter.h"
namespace librados {
// Wraps Objecter's ObjectOperation with storage for an optional mtime argument.
struct ObjectOperationImpl {
::ObjectOperation o;
ceph::real_time rt;
ceph::real_time *prt = nullptr;
};
} // namespace librados
| 677 | 23.214286 | 80 | h |
null | ceph-main/src/librados/PoolAsyncCompletionImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2012 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_LIBRADOS_POOLASYNCCOMPLETIONIMPL_H
#define CEPH_LIBRADOS_POOLASYNCCOMPLETIONIMPL_H
#include "common/ceph_mutex.h"
#include <boost/intrusive_ptr.hpp>
#include "include/rados/librados.h"
#include "include/rados/librados.hpp"
namespace librados {
struct PoolAsyncCompletionImpl {
ceph::mutex lock = ceph::make_mutex("PoolAsyncCompletionImpl lock");
ceph::condition_variable cond;
int ref = 1;
int rval = 0;
bool released = false;
bool done = false;
rados_callback_t callback = nullptr;
void *callback_arg = nullptr;
PoolAsyncCompletionImpl() = default;
int set_callback(void *cb_arg, rados_callback_t cb) {
std::scoped_lock l(lock);
callback = cb;
callback_arg = cb_arg;
return 0;
}
int wait() {
std::unique_lock l(lock);
while (!done)
cond.wait(l);
return 0;
}
int is_complete() {
std::scoped_lock l(lock);
return done;
}
int get_return_value() {
std::scoped_lock l(lock);
return rval;
}
void get() {
std::scoped_lock l(lock);
ceph_assert(ref > 0);
ref++;
}
void release() {
std::scoped_lock l(lock);
ceph_assert(!released);
released = true;
}
void put() {
std::unique_lock l(lock);
int n = --ref;
l.unlock();
if (!n)
delete this;
}
};
inline void intrusive_ptr_add_ref(PoolAsyncCompletionImpl* p) {
p->get();
}
inline void intrusive_ptr_release(PoolAsyncCompletionImpl* p) {
p->put();
}
class CB_PoolAsync_Safe {
boost::intrusive_ptr<PoolAsyncCompletionImpl> p;
public:
explicit CB_PoolAsync_Safe(boost::intrusive_ptr<PoolAsyncCompletionImpl> p)
: p(p) {}
~CB_PoolAsync_Safe() = default;
void operator()(int r) {
auto c(std::move(p));
std::unique_lock l(c->lock);
c->rval = r;
c->done = true;
c->cond.notify_all();
if (c->callback) {
rados_callback_t cb = c->callback;
void *cb_arg = c->callback_arg;
l.unlock();
cb(c.get(), cb_arg);
l.lock();
}
}
};
}
#endif
| 2,529 | 21.792793 | 79 | h |
null | ceph-main/src/librados/RadosClient.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2012 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_LIBRADOS_RADOSCLIENT_H
#define CEPH_LIBRADOS_RADOSCLIENT_H
#include <functional>
#include <memory>
#include <string>
#include "msg/Dispatcher.h"
#include "common/async/context_pool.h"
#include "common/config_fwd.h"
#include "common/Cond.h"
#include "common/ceph_mutex.h"
#include "common/ceph_time.h"
#include "common/config_obs.h"
#include "include/common_fwd.h"
#include "include/rados/librados.h"
#include "include/rados/librados.hpp"
#include "mon/MonClient.h"
#include "mgr/MgrClient.h"
#include "IoCtxImpl.h"
struct Context;
class Message;
class MLog;
class Messenger;
class AioCompletionImpl;
namespace neorados { namespace detail { class RadosClient; }}
class librados::RadosClient : public Dispatcher,
public md_config_obs_t
{
friend neorados::detail::RadosClient;
public:
using Dispatcher::cct;
private:
std::unique_ptr<CephContext,
std::function<void(CephContext*)>> cct_deleter;
public:
const ConfigProxy& conf{cct->_conf};
ceph::async::io_context_pool poolctx;
private:
enum {
DISCONNECTED,
CONNECTING,
CONNECTED,
} state{DISCONNECTED};
MonClient monclient{cct, poolctx};
MgrClient mgrclient{cct, nullptr, &monclient.monmap};
Messenger *messenger{nullptr};
uint64_t instance_id{0};
bool _dispatch(Message *m);
bool ms_dispatch(Message *m) override;
void ms_handle_connect(Connection *con) override;
bool ms_handle_reset(Connection *con) override;
void ms_handle_remote_reset(Connection *con) override;
bool ms_handle_refused(Connection *con) override;
Objecter *objecter{nullptr};
ceph::mutex lock = ceph::make_mutex("librados::RadosClient::lock");
ceph::condition_variable cond;
int refcnt{1};
version_t log_last_version{0};
rados_log_callback_t log_cb{nullptr};
rados_log_callback2_t log_cb2{nullptr};
void *log_cb_arg{nullptr};
std::string log_watch;
bool service_daemon = false;
std::string daemon_name, service_name;
std::map<std::string,std::string> daemon_metadata;
ceph::timespan rados_mon_op_timeout{};
int wait_for_osdmap();
public:
boost::asio::io_context::strand finish_strand{poolctx.get_io_context()};
explicit RadosClient(CephContext *cct);
~RadosClient() override;
int ping_monitor(std::string mon_id, std::string *result);
int connect();
void shutdown();
int watch_flush();
int async_watch_flush(AioCompletionImpl *c);
uint64_t get_instance_id();
int get_min_compatible_osd(int8_t* require_osd_release);
int get_min_compatible_client(int8_t* min_compat_client,
int8_t* require_min_compat_client);
int wait_for_latest_osdmap();
int create_ioctx(const char *name, IoCtxImpl **io);
int create_ioctx(int64_t, IoCtxImpl **io);
int get_fsid(std::string *s);
int64_t lookup_pool(const char *name);
bool pool_requires_alignment(int64_t pool_id);
int pool_requires_alignment2(int64_t pool_id, bool *req);
uint64_t pool_required_alignment(int64_t pool_id);
int pool_required_alignment2(int64_t pool_id, uint64_t *alignment);
int pool_get_name(uint64_t pool_id, std::string *name,
bool wait_latest_map = false);
int pool_list(std::list<std::pair<int64_t, std::string> >& ls);
int get_pool_stats(std::list<std::string>& ls, std::map<std::string,::pool_stat_t> *result,
bool *per_pool);
int get_fs_stats(ceph_statfs& result);
bool get_pool_is_selfmanaged_snaps_mode(const std::string& pool);
/*
-1 was set as the default value and monitor will pickup the right crush rule with below order:
a) osd pool default crush replicated rule
b) the first rule
c) error out if no value find
*/
int pool_create(std::string& name, int16_t crush_rule=-1);
int pool_create_async(std::string& name, PoolAsyncCompletionImpl *c,
int16_t crush_rule=-1);
int pool_get_base_tier(int64_t pool_id, int64_t* base_tier);
int pool_delete(const char *name);
int pool_delete_async(const char *name, PoolAsyncCompletionImpl *c);
int blocklist_add(const std::string& client_address, uint32_t expire_seconds);
int mon_command(const std::vector<std::string>& cmd, const bufferlist &inbl,
bufferlist *outbl, std::string *outs);
void mon_command_async(const std::vector<std::string>& cmd, const bufferlist &inbl,
bufferlist *outbl, std::string *outs, Context *on_finish);
int mon_command(int rank,
const std::vector<std::string>& cmd, const bufferlist &inbl,
bufferlist *outbl, std::string *outs);
int mon_command(std::string name,
const std::vector<std::string>& cmd, const bufferlist &inbl,
bufferlist *outbl, std::string *outs);
int mgr_command(const std::vector<std::string>& cmd, const bufferlist &inbl,
bufferlist *outbl, std::string *outs);
int mgr_command(
const std::string& name,
const std::vector<std::string>& cmd, const bufferlist &inbl,
bufferlist *outbl, std::string *outs);
int osd_command(int osd, std::vector<std::string>& cmd, const bufferlist& inbl,
bufferlist *poutbl, std::string *prs);
int pg_command(pg_t pgid, std::vector<std::string>& cmd, const bufferlist& inbl,
bufferlist *poutbl, std::string *prs);
void handle_log(MLog *m);
int monitor_log(const std::string& level, rados_log_callback_t cb,
rados_log_callback2_t cb2, void *arg);
void get();
bool put();
void blocklist_self(bool set);
std::string get_addrs() const;
int service_daemon_register(
const std::string& service, ///< service name (e.g., 'rgw')
const std::string& name, ///< daemon name (e.g., 'gwfoo')
const std::map<std::string,std::string>& metadata); ///< static metadata about daemon
int service_daemon_update_status(
std::map<std::string,std::string>&& status);
mon_feature_t get_required_monitor_features() const;
int get_inconsistent_pgs(int64_t pool_id, std::vector<std::string>* pgs);
const char** get_tracked_conf_keys() const override;
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override;
};
#endif
| 6,525 | 31.79397 | 96 | h |
null | ceph-main/src/librados/RadosXattrIter.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Sebastien Ponce <[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_LIBRADOS_XATTRITER_H
#define CEPH_LIBRADOS_XATTRITER_H
#include <string>
#include <map>
#include "include/buffer.h" // for bufferlist
namespace librados {
/**
* iterator object used in implementation of the external
* attributes part of the C interface of librados
*/
struct RadosXattrsIter {
RadosXattrsIter();
~RadosXattrsIter();
std::map<std::string, bufferlist> attrset;
std::map<std::string, bufferlist>::iterator i;
char *val;
};
};
#endif
| 933 | 22.948718 | 70 | h |
null | ceph-main/src/librados/librados_asio.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#ifndef LIBRADOS_ASIO_H
#define LIBRADOS_ASIO_H
#include "include/rados/librados.hpp"
#include "common/async/completion.h"
/// Defines asynchronous librados operations that satisfy all of the
/// "Requirements on asynchronous operations" imposed by the C++ Networking TS
/// in section 13.2.7. Many of the type and variable names below are taken
/// directly from those requirements.
///
/// The current draft of the Networking TS (as of 2017-11-27) is available here:
/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4711.pdf
///
/// The boost::asio documentation duplicates these requirements here:
/// http://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/asynchronous_operations.html
namespace librados {
namespace detail {
#ifndef _WIN32
constexpr auto err_category = boost::system::system_category;
#else
// librados uses "errno.h" error codes. On Windows,
// boost::system::system_category refers to errors from winerror.h.
// That being considered, we'll use boost::system::generic_category.
constexpr auto err_category = boost::system::generic_category;
#endif
/// unique_ptr with custom deleter for AioCompletion
struct AioCompletionDeleter {
void operator()(AioCompletion *c) { c->release(); }
};
using unique_aio_completion_ptr =
std::unique_ptr<AioCompletion, AioCompletionDeleter>;
/// Invokes the given completion handler. When the type of Result is not void,
/// storage is provided for it and that result is passed as an additional
/// argument to the handler.
template <typename Result>
struct Invoker {
using Signature = void(boost::system::error_code, Result);
Result result;
template <typename Completion>
void dispatch(Completion&& completion, boost::system::error_code ec) {
ceph::async::dispatch(std::move(completion), ec, std::move(result));
}
};
// specialization for Result=void
template <>
struct Invoker<void> {
using Signature = void(boost::system::error_code);
template <typename Completion>
void dispatch(Completion&& completion, boost::system::error_code ec) {
ceph::async::dispatch(std::move(completion), ec);
}
};
template <typename Result>
struct AsyncOp : Invoker<Result> {
unique_aio_completion_ptr aio_completion;
using Signature = typename Invoker<Result>::Signature;
using Completion = ceph::async::Completion<Signature, AsyncOp<Result>>;
static void aio_dispatch(completion_t cb, void *arg) {
// reclaim ownership of the completion
auto p = std::unique_ptr<Completion>{static_cast<Completion*>(arg)};
// move result out of Completion memory being freed
auto op = std::move(p->user_data);
const int ret = op.aio_completion->get_return_value();
boost::system::error_code ec;
if (ret < 0) {
ec.assign(-ret, librados::detail::err_category());
}
op.dispatch(std::move(p), ec);
}
template <typename Executor1, typename CompletionHandler>
static auto create(const Executor1& ex1, CompletionHandler&& handler) {
auto p = Completion::create(ex1, std::move(handler));
p->user_data.aio_completion.reset(
Rados::aio_create_completion(p.get(), aio_dispatch));
return p;
}
};
} // namespace detail
/// Calls IoCtx::aio_read() and arranges for the AioCompletion to call a
/// given handler with signature (boost::system::error_code, bufferlist).
template <typename ExecutionContext, typename CompletionToken>
auto async_read(ExecutionContext& ctx, IoCtx& io, const std::string& oid,
size_t len, uint64_t off, CompletionToken&& token)
{
using Op = detail::AsyncOp<bufferlist>;
using Signature = typename Op::Signature;
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto p = Op::create(ctx.get_executor(), init.completion_handler);
auto& op = p->user_data;
int ret = io.aio_read(oid, op.aio_completion.get(), &op.result, len, off);
if (ret < 0) {
auto ec = boost::system::error_code{-ret, librados::detail::err_category()};
ceph::async::post(std::move(p), ec, bufferlist{});
} else {
p.release(); // release ownership until completion
}
return init.result.get();
}
/// Calls IoCtx::aio_write() and arranges for the AioCompletion to call a
/// given handler with signature (boost::system::error_code).
template <typename ExecutionContext, typename CompletionToken>
auto async_write(ExecutionContext& ctx, IoCtx& io, const std::string& oid,
bufferlist &bl, size_t len, uint64_t off,
CompletionToken&& token)
{
using Op = detail::AsyncOp<void>;
using Signature = typename Op::Signature;
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto p = Op::create(ctx.get_executor(), init.completion_handler);
auto& op = p->user_data;
int ret = io.aio_write(oid, op.aio_completion.get(), bl, len, off);
if (ret < 0) {
auto ec = boost::system::error_code{-ret, librados::detail::err_category()};
ceph::async::post(std::move(p), ec);
} else {
p.release(); // release ownership until completion
}
return init.result.get();
}
/// Calls IoCtx::aio_operate() and arranges for the AioCompletion to call a
/// given handler with signature (boost::system::error_code, bufferlist).
template <typename ExecutionContext, typename CompletionToken>
auto async_operate(ExecutionContext& ctx, IoCtx& io, const std::string& oid,
ObjectReadOperation *read_op, int flags,
CompletionToken&& token)
{
using Op = detail::AsyncOp<bufferlist>;
using Signature = typename Op::Signature;
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto p = Op::create(ctx.get_executor(), init.completion_handler);
auto& op = p->user_data;
int ret = io.aio_operate(oid, op.aio_completion.get(), read_op,
flags, &op.result);
if (ret < 0) {
auto ec = boost::system::error_code{-ret, librados::detail::err_category()};
ceph::async::post(std::move(p), ec, bufferlist{});
} else {
p.release(); // release ownership until completion
}
return init.result.get();
}
/// Calls IoCtx::aio_operate() and arranges for the AioCompletion to call a
/// given handler with signature (boost::system::error_code).
template <typename ExecutionContext, typename CompletionToken>
auto async_operate(ExecutionContext& ctx, IoCtx& io, const std::string& oid,
ObjectWriteOperation *write_op, int flags,
CompletionToken &&token)
{
using Op = detail::AsyncOp<void>;
using Signature = typename Op::Signature;
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto p = Op::create(ctx.get_executor(), init.completion_handler);
auto& op = p->user_data;
int ret = io.aio_operate(oid, op.aio_completion.get(), write_op, flags);
if (ret < 0) {
auto ec = boost::system::error_code{-ret, librados::detail::err_category()};
ceph::async::post(std::move(p), ec);
} else {
p.release(); // release ownership until completion
}
return init.result.get();
}
/// Calls IoCtx::aio_notify() and arranges for the AioCompletion to call a
/// given handler with signature (boost::system::error_code, bufferlist).
template <typename ExecutionContext, typename CompletionToken>
auto async_notify(ExecutionContext& ctx, IoCtx& io, const std::string& oid,
bufferlist& bl, uint64_t timeout_ms, CompletionToken &&token)
{
using Op = detail::AsyncOp<bufferlist>;
using Signature = typename Op::Signature;
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto p = Op::create(ctx.get_executor(), init.completion_handler);
auto& op = p->user_data;
int ret = io.aio_notify(oid, op.aio_completion.get(),
bl, timeout_ms, &op.result);
if (ret < 0) {
auto ec = boost::system::error_code{-ret, librados::detail::err_category()};
ceph::async::post(std::move(p), ec, bufferlist{});
} else {
p.release(); // release ownership until completion
}
return init.result.get();
}
} // namespace librados
#endif // LIBRADOS_ASIO_H
| 8,461 | 36.946188 | 99 | h |
null | ceph-main/src/librados/librados_c.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef LIBRADOS_C_H
#define LIBRADOS_C_H
#include "include/types.h"
#include "include/rados/librados.h"
namespace __librados_base {
struct rados_pool_stat_t {
uint64_t num_bytes;
uint64_t num_kb;
uint64_t num_objects;
uint64_t num_object_clones;
uint64_t num_object_copies;
uint64_t num_objects_missing_on_primary;
uint64_t num_objects_unfound;
uint64_t num_objects_degraded;
uint64_t num_rd;
uint64_t num_rd_kb;
uint64_t num_wr;
uint64_t num_wr_kb;
};
} // namespace __librados_base
#endif // LIBRADOS_C_H
| 636 | 20.233333 | 70 | h |
null | ceph-main/src/librados/librados_util.h | #include <cstdint>
#include "acconfig.h"
#include "include/rados/librados.h"
#include "IoCtxImpl.h"
#ifdef WITH_LTTNG
#include "tracing/librados.h"
#else
#define tracepoint(...)
#endif
uint8_t get_checksum_op_type(rados_checksum_type_t type);
int get_op_flags(int flags);
int translate_flags(int flags);
struct librados::ObjListCtx {
librados::IoCtxImpl dupctx;
librados::IoCtxImpl *ctx;
Objecter::NListContext *nlc;
bool legacy_list_api;
ObjListCtx(IoCtxImpl *c, Objecter::NListContext *nl, bool legacy=false)
: nlc(nl),
legacy_list_api(legacy) {
// Get our own private IoCtxImpl so that namespace setting isn't
// changed by caller between uses.
ctx = &dupctx;
dupctx.dup(*c);
}
~ObjListCtx() {
ctx = NULL;
delete nlc;
}
};
| 780 | 21.314286 | 73 | h |
null | ceph-main/src/librados/snap_set_diff.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef __CEPH_OSDC_SNAP_SET_DIFF_H
#define __CEPH_OSDC_SNAP_SET_DIFF_H
#include "include/common_fwd.h"
#include "include/rados/rados_types.hpp"
#include "include/interval_set.h"
void calc_snap_set_diff(CephContext *cct,
const librados::snap_set_t& snap_set,
librados::snap_t start, librados::snap_t end,
interval_set<uint64_t> *diff, uint64_t *end_size,
bool *end_exists, librados::snap_t *clone_end_snap_id,
bool *whole_object);
#endif
| 555 | 28.263158 | 70 | h |
null | ceph-main/src/libradosstriper/MultiAioCompletionImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Sebastien Ponce <[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_LIBRADOSSTRIPERSTRIPER_MULTIAIOCOMPLETIONIMPL_H
#define CEPH_LIBRADOSSTRIPERSTRIPER_MULTIAIOCOMPLETIONIMPL_H
#include <list>
#include <mutex>
#include "common/ceph_mutex.h"
#include "include/radosstriper/libradosstriper.hpp"
namespace libradosstriper {
struct MultiAioCompletionImpl {
ceph::mutex lock = ceph::make_mutex("MultiAioCompletionImpl lock", false);
ceph::condition_variable cond;
int ref, rval;
int pending_complete, pending_safe;
rados_callback_t callback_complete, callback_safe;
void *callback_complete_arg, *callback_safe_arg;
bool building; ///< true if we are still building this completion
bufferlist bl; /// only used for read case in C api of rados striper
std::list<bufferlist*> bllist; /// keep temporary buffer lists used for destriping
MultiAioCompletionImpl()
: ref(1), rval(0),
pending_complete(0), pending_safe(0),
callback_complete(0), callback_safe(0),
callback_complete_arg(0), callback_safe_arg(0),
building(true) {};
~MultiAioCompletionImpl() {
// deallocate temporary buffer lists
for (std::list<bufferlist*>::iterator it = bllist.begin();
it != bllist.end();
it++) {
delete *it;
}
bllist.clear();
}
int set_complete_callback(void *cb_arg, rados_callback_t cb) {
std::scoped_lock l{lock};
callback_complete = cb;
callback_complete_arg = cb_arg;
return 0;
}
int set_safe_callback(void *cb_arg, rados_callback_t cb) {
std::scoped_lock l{lock};
callback_safe = cb;
callback_safe_arg = cb_arg;
return 0;
}
int wait_for_complete() {
std::unique_lock l{lock};
cond.wait(l, [this] { return !pending_complete; });
return 0;
}
int wait_for_safe() {
std::unique_lock l{lock};
cond.wait(l, [this] { return !pending_safe; });
return 0;
}
bool is_complete() {
std::scoped_lock l{lock};
return pending_complete == 0;
}
bool is_safe() {
std::scoped_lock l{lock};
return pending_safe == 0;
}
void wait_for_complete_and_cb() {
std::unique_lock l{lock};
cond.wait(l, [this] { return !pending_complete && !callback_complete; });
}
void wait_for_safe_and_cb() {
std::unique_lock l{lock};
cond.wait(l, [this] { return !pending_safe && !callback_safe; });
}
bool is_complete_and_cb() {
std::scoped_lock l{lock};
return ((0 == pending_complete) && !callback_complete);
}
bool is_safe_and_cb() {
std::scoped_lock l{lock};
return ((0 == pending_safe) && !callback_safe);
}
int get_return_value() {
std::scoped_lock l{lock};
return rval;
}
void get() {
std::scoped_lock l{lock};
_get();
}
void _get() {
ceph_assert(ceph_mutex_is_locked(lock));
ceph_assert(ref > 0);
++ref;
}
void put() {
lock.lock();
put_unlock();
}
void put_unlock() {
ceph_assert(ref > 0);
int n = --ref;
lock.unlock();
if (!n)
delete this;
}
void add_request() {
std::scoped_lock l{lock};
pending_complete++;
_get();
pending_safe++;
_get();
}
void add_safe_request() {
std::scoped_lock l{lock};
pending_complete++;
_get();
}
void complete() {
ceph_assert(ceph_mutex_is_locked(lock));
if (callback_complete) {
callback_complete(this, callback_complete_arg);
callback_complete = 0;
}
cond.notify_all();
}
void safe() {
ceph_assert(ceph_mutex_is_locked(lock));
if (callback_safe) {
callback_safe(this, callback_safe_arg);
callback_safe = 0;
}
cond.notify_all();
};
void complete_request(ssize_t r);
void safe_request(ssize_t r);
void finish_adding_requests();
};
inline void intrusive_ptr_add_ref(MultiAioCompletionImpl* ptr)
{
ptr->get();
}
inline void intrusive_ptr_release(MultiAioCompletionImpl* ptr)
{
ptr->put();
}
}
#endif // CEPH_LIBRADOSSTRIPERSTRIPER_MULTIAIOCOMPLETIONIMPL_H
| 4,333 | 24.494118 | 84 | h |
null | ceph-main/src/libradosstriper/RadosStriperImpl.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Sebastien Ponce <[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_LIBRADOSSTRIPER_RADOSSTRIPERIMPL_H
#define CEPH_LIBRADOSSTRIPER_RADOSSTRIPERIMPL_H
#include <string>
#include <boost/intrusive_ptr.hpp>
#include "include/rados/librados.h"
#include "include/rados/librados.hpp"
#include "include/radosstriper/libradosstriper.h"
#include "include/radosstriper/libradosstriper.hpp"
#include "MultiAioCompletionImpl.h"
#include "librados/IoCtxImpl.h"
#include "librados/AioCompletionImpl.h"
#include "common/RefCountedObj.h"
#include "common/ceph_context.h"
namespace libradosstriper {
using MultiAioCompletionImplPtr =
boost::intrusive_ptr<MultiAioCompletionImpl>;
struct RadosStriperImpl {
/**
* exception wrapper around an error code
*/
struct ErrorCode {
ErrorCode(int error) : m_code(error) {};
int m_code;
};
/*
* Constructor
* @param cluster_name name of the cluster, can be NULL
* @param client_name has 2 meanings depending on cluster_name
* - if cluster_name is null : this is the client id
* - else : this is the full client name in format type.id
*/
RadosStriperImpl(librados::IoCtx& ioctx, librados::IoCtxImpl *ioctx_impl);
/// Destructor
~RadosStriperImpl() {};
// configuration
int setObjectLayoutStripeUnit(unsigned int stripe_unit);
int setObjectLayoutStripeCount(unsigned int stripe_count);
int setObjectLayoutObjectSize(unsigned int object_size);
// xattrs
int getxattr(const object_t& soid, const char *name, bufferlist& bl);
int setxattr(const object_t& soid, const char *name, bufferlist& bl);
int getxattrs(const object_t& soid, std::map<std::string, bufferlist>& attrset);
int rmxattr(const object_t& soid, const char *name);
// io
int write(const std::string& soid, const bufferlist& bl, size_t len, uint64_t off);
int append(const std::string& soid, const bufferlist& bl, size_t len);
int write_full(const std::string& soid, const bufferlist& bl);
int read(const std::string& soid, bufferlist* pbl, size_t len, uint64_t off);
// asynchronous io
int aio_write(const std::string& soid, librados::AioCompletionImpl *c,
const bufferlist& bl, size_t len, uint64_t off);
int aio_append(const std::string& soid, librados::AioCompletionImpl *c,
const bufferlist& bl, size_t len);
int aio_write_full(const std::string& soid, librados::AioCompletionImpl *c,
const bufferlist& bl);
int aio_read(const std::string& soid, librados::AioCompletionImpl *c,
bufferlist* pbl, size_t len, uint64_t off);
int aio_read(const std::string& soid, librados::AioCompletionImpl *c,
char* buf, size_t len, uint64_t off);
int aio_flush();
// stat, deletion and truncation
int stat(const std::string& soid, uint64_t *psize, time_t *pmtime);
int stat2(const std::string& soid, uint64_t *psize, struct timespec *pts);
template<class TimeType>
struct StatFunction {
typedef int (librados::IoCtxImpl::*Type) (const object_t& oid,
librados::AioCompletionImpl *c,
uint64_t *psize, TimeType *pmtime);
};
template<class TimeType>
int aio_generic_stat(const std::string& soid, librados::AioCompletionImpl *c,
uint64_t *psize, TimeType *pmtime,
typename StatFunction<TimeType>::Type statFunction);
int aio_stat(const std::string& soid, librados::AioCompletionImpl *c,
uint64_t *psize, time_t *pmtime);
int aio_stat2(const std::string& soid, librados::AioCompletionImpl *c,
uint64_t *psize, struct timespec *pts);
int remove(const std::string& soid, int flags=0);
int trunc(const std::string& soid, uint64_t size);
// asynchronous remove. Note that the removal is not 100% parallelized :
// the removal of the first rados object of the striped object will be
// done via a syncrhonous call after the completion of all other removals.
// These are done asynchrounously and in parallel
int aio_remove(const std::string& soid, librados::AioCompletionImpl *c, int flags=0);
// reference counting
void get() {
std::lock_guard l{lock};
m_refCnt ++ ;
}
void put() {
bool deleteme = false;
lock.lock();
m_refCnt --;
if (m_refCnt == 0)
deleteme = true;
cond.notify_all();
lock.unlock();
if (deleteme)
delete this;
}
// objectid manipulation
std::string getObjectId(const object_t& soid, long long unsigned objectno);
// opening and closing of striped objects
void unlockObject(const std::string& soid,
const std::string& lockCookie);
void aio_unlockObject(const std::string& soid,
const std::string& lockCookie,
librados::AioCompletion *c);
// internal versions of IO method
int write_in_open_object(const std::string& soid,
const ceph_file_layout& layout,
const std::string& lockCookie,
const bufferlist& bl,
size_t len,
uint64_t off);
int aio_write_in_open_object(const std::string& soid,
librados::AioCompletionImpl *c,
const ceph_file_layout& layout,
const std::string& lockCookie,
const bufferlist& bl,
size_t len,
uint64_t off);
int internal_aio_write(const std::string& soid,
MultiAioCompletionImplPtr c,
const bufferlist& bl,
size_t len,
uint64_t off,
const ceph_file_layout& layout);
int extract_uint32_attr(std::map<std::string, bufferlist> &attrs,
const std::string& key,
ceph_le32 *value);
int extract_sizet_attr(std::map<std::string, bufferlist> &attrs,
const std::string& key,
size_t *value);
int internal_get_layout_and_size(const std::string& oid,
ceph_file_layout *layout,
uint64_t *size);
int internal_aio_remove(const std::string& soid,
MultiAioCompletionImplPtr multi_completion,
int flags=0);
/**
* opens an existing striped object and takes a shared lock on it
* @return 0 if everything is ok and the lock was taken. -errcode otherwise
* In particulae, if the striped object does not exists, -ENOENT is returned
* In case the return code in not 0, no lock is taken
*/
int openStripedObjectForRead(const std::string& soid,
ceph_file_layout *layout,
uint64_t *size,
std::string *lockCookie);
/**
* opens an existing striped object, takes a shared lock on it
* and sets its size to the size it will have after the write.
* In case the striped object does not exists, it will create it by
* calling createOrOpenStripedObject.
* @param layout this is filled with the layout of the file
* @param size new size of the file (together with isFileSizeAbsolute)
* In case of success, this is filled with the size of the file before the opening
* @param isFileSizeAbsolute if false, this means that the given size should
* be added to the current file size (append mode)
* @return 0 if everything is ok and the lock was taken. -errcode otherwise
* In case the return code in not 0, no lock is taken
*/
int openStripedObjectForWrite(const std::string& soid,
ceph_file_layout *layout,
uint64_t *size,
std::string *lockCookie,
bool isFileSizeAbsolute);
/**
* creates an empty striped object with the given size and opens it calling
* openStripedObjectForWrite, which implies taking a shared lock on it
* Also deals with the cases where the object was created in the mean time
* @param isFileSizeAbsolute if false, this means that the given size should
* be added to the current file size (append mode). This of course only makes
* sense in case the striped object already exists
* @return 0 if everything is ok and the lock was taken. -errcode otherwise
* In case the return code in not 0, no lock is taken
*/
int createAndOpenStripedObject(const std::string& soid,
ceph_file_layout *layout,
uint64_t size,
std::string *lockCookie,
bool isFileSizeAbsolute);
/**
* truncates an object synchronously. Should only be called with size < original_size
*/
int truncate(const std::string& soid,
uint64_t original_size,
uint64_t size,
ceph_file_layout &layout);
/**
* truncates an object asynchronously. Should only be called with size < original_size
* note that the method is not 100% asynchronous, only the removal of rados objects
* is, the (potential) truncation of the rados object residing just at the truncation
* point is synchronous for lack of asynchronous truncation in the rados layer
*/
int aio_truncate(const std::string& soid,
MultiAioCompletionImplPtr c,
uint64_t original_size,
uint64_t size,
ceph_file_layout &layout);
/**
* grows an object (adding 0s). Should only be called with size > original_size
*/
int grow(const std::string& soid,
uint64_t original_size,
uint64_t size,
ceph_file_layout &layout);
/**
* creates a unique identifier
*/
static std::string getUUID();
CephContext *cct() {
return (CephContext*)m_radosCluster.cct();
}
// reference counting
std::condition_variable cond;
int m_refCnt;
std::mutex lock;
// Context
librados::Rados m_radosCluster;
librados::IoCtx m_ioCtx;
librados::IoCtxImpl *m_ioCtxImpl;
// Default layout
ceph_file_layout m_layout;
};
}
#endif
| 9,688 | 33.978339 | 88 | h |