Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
ceph-main/src/rgw/rgw_compression.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <vector>
#include "compressor/Compressor.h"
#include "rgw_putobj.h"
#include "rgw_op.h"
#include "rgw_compression_types.h"
int rgw_compression_info_from_attr(const bufferlist& attr,
bool& need_decompress,
RGWCompressionInfo& cs_info);
int rgw_compression_info_from_attrset(const std::map<std::string, bufferlist>& attrs,
bool& need_decompress,
RGWCompressionInfo& cs_info);
class RGWGetObj_Decompress : public RGWGetObj_Filter
{
CephContext* cct;
CompressorRef compressor;
RGWCompressionInfo* cs_info;
bool partial_content;
std::vector<compression_block>::iterator first_block, last_block;
off_t q_ofs, q_len;
uint64_t cur_ofs;
bufferlist waiting;
public:
RGWGetObj_Decompress(CephContext* cct_,
RGWCompressionInfo* cs_info_,
bool partial_content_,
RGWGetObj_Filter* next);
virtual ~RGWGetObj_Decompress() override {}
int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override;
int fixup_range(off_t& ofs, off_t& end) override;
};
class RGWPutObj_Compress : public rgw::putobj::Pipe
{
CephContext* cct;
bool compressed{false};
CompressorRef compressor;
std::optional<int32_t> compressor_message;
std::vector<compression_block> blocks;
uint64_t compressed_ofs{0};
public:
RGWPutObj_Compress(CephContext* cct_, CompressorRef compressor,
rgw::sal::DataProcessor *next)
: Pipe(next), cct(cct_), compressor(compressor) {}
virtual ~RGWPutObj_Compress() override {};
int process(bufferlist&& data, uint64_t logical_offset) override;
bool is_compressed() { return compressed; }
std::vector<compression_block>& get_compression_blocks() { return blocks; }
std::optional<int32_t> get_compressor_message() { return compressor_message; }
}; /* RGWPutObj_Compress */
| 2,091 | 32.206349 | 85 |
h
|
null |
ceph-main/src/rgw/rgw_compression_types.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
struct compression_block {
uint64_t old_ofs;
uint64_t new_ofs;
uint64_t len;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(old_ofs, bl);
encode(new_ofs, bl);
encode(len, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(old_ofs, bl);
decode(new_ofs, bl);
decode(len, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(compression_block)
struct RGWCompressionInfo {
std::string compression_type;
uint64_t orig_size;
std::optional<int32_t> compressor_message;
std::vector<compression_block> blocks;
RGWCompressionInfo() : compression_type("none"), orig_size(0) {}
RGWCompressionInfo(const RGWCompressionInfo& cs_info) : compression_type(cs_info.compression_type),
orig_size(cs_info.orig_size),
compressor_message(cs_info.compressor_message),
blocks(cs_info.blocks) {}
void encode(bufferlist& bl) const {
ENCODE_START(2, 1, bl);
encode(compression_type, bl);
encode(orig_size, bl);
encode(compressor_message, bl);
encode(blocks, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(compression_type, bl);
decode(orig_size, bl);
if (struct_v >= 2) {
decode(compressor_message, bl);
}
decode(blocks, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(RGWCompressionInfo)
| 2,050 | 25.636364 | 101 |
h
|
null |
ceph-main/src/rgw/rgw_coroutine.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "include/Context.h"
#include "common/ceph_json.h"
#include "rgw_coroutine.h"
// re-include our assert to clobber the system one; fix dout:
#include "include/ceph_assert.h"
#include <boost/asio/yield.hpp>
#define dout_subsys ceph_subsys_rgw
#define dout_context g_ceph_context
using namespace std;
class RGWCompletionManager::WaitContext : public Context {
RGWCompletionManager *manager;
void *opaque;
public:
WaitContext(RGWCompletionManager *_cm, void *_opaque) : manager(_cm), opaque(_opaque) {}
void finish(int r) override {
manager->_wakeup(opaque);
}
};
RGWCompletionManager::RGWCompletionManager(CephContext *_cct) : cct(_cct),
timer(cct, lock)
{
timer.init();
}
RGWCompletionManager::~RGWCompletionManager()
{
std::lock_guard l{lock};
timer.cancel_all_events();
timer.shutdown();
}
void RGWCompletionManager::complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info)
{
std::lock_guard l{lock};
_complete(cn, io_id, user_info);
}
void RGWCompletionManager::register_completion_notifier(RGWAioCompletionNotifier *cn)
{
std::lock_guard l{lock};
if (cn) {
cns.insert(cn);
}
}
void RGWCompletionManager::unregister_completion_notifier(RGWAioCompletionNotifier *cn)
{
std::lock_guard l{lock};
if (cn) {
cns.erase(cn);
}
}
void RGWCompletionManager::_complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info)
{
if (cn) {
cns.erase(cn);
}
if (complete_reqs_set.find(io_id) != complete_reqs_set.end()) {
/* already have completion for this io_id, don't allow multiple completions for it */
return;
}
complete_reqs.push_back(io_completion{io_id, user_info});
cond.notify_all();
}
int RGWCompletionManager::get_next(io_completion *io)
{
std::unique_lock l{lock};
while (complete_reqs.empty()) {
if (going_down) {
return -ECANCELED;
}
cond.wait(l);
}
*io = complete_reqs.front();
complete_reqs_set.erase(io->io_id);
complete_reqs.pop_front();
return 0;
}
bool RGWCompletionManager::try_get_next(io_completion *io)
{
std::lock_guard l{lock};
if (complete_reqs.empty()) {
return false;
}
*io = complete_reqs.front();
complete_reqs_set.erase(io->io_id);
complete_reqs.pop_front();
return true;
}
void RGWCompletionManager::go_down()
{
std::lock_guard l{lock};
for (auto cn : cns) {
cn->unregister();
}
going_down = true;
cond.notify_all();
}
void RGWCompletionManager::wait_interval(void *opaque, const utime_t& interval, void *user_info)
{
std::lock_guard l{lock};
ceph_assert(waiters.find(opaque) == waiters.end());
waiters[opaque] = user_info;
timer.add_event_after(interval, new WaitContext(this, opaque));
}
void RGWCompletionManager::wakeup(void *opaque)
{
std::lock_guard l{lock};
_wakeup(opaque);
}
void RGWCompletionManager::_wakeup(void *opaque)
{
map<void *, void *>::iterator iter = waiters.find(opaque);
if (iter != waiters.end()) {
void *user_id = iter->second;
waiters.erase(iter);
_complete(NULL, rgw_io_id{0, -1} /* no IO id */, user_id);
}
}
RGWCoroutine::~RGWCoroutine() {
for (auto stack : spawned.entries) {
stack->put();
}
}
void RGWCoroutine::init_new_io(RGWIOProvider *io_provider)
{
ceph_assert(stack); // if there's no stack, io_provider won't be uninitialized
stack->init_new_io(io_provider);
}
void RGWCoroutine::set_io_blocked(bool flag) {
if (stack) {
stack->set_io_blocked(flag);
}
}
void RGWCoroutine::set_sleeping(bool flag) {
if (stack) {
stack->set_sleeping(flag);
}
}
int RGWCoroutine::io_block(int ret, int64_t io_id) {
return io_block(ret, rgw_io_id{io_id, -1});
}
int RGWCoroutine::io_block(int ret, const rgw_io_id& io_id) {
if (!stack) {
return 0;
}
if (stack->consume_io_finish(io_id)) {
return 0;
}
set_io_blocked(true);
stack->set_io_blocked_id(io_id);
return ret;
}
void RGWCoroutine::io_complete(const rgw_io_id& io_id) {
if (stack) {
stack->io_complete(io_id);
}
}
void RGWCoroutine::StatusItem::dump(Formatter *f) const {
::encode_json("timestamp", timestamp, f);
::encode_json("status", status, f);
}
stringstream& RGWCoroutine::Status::set_status()
{
std::unique_lock l{lock};
string s = status.str();
status.str(string());
if (!timestamp.is_zero()) {
history.push_back(StatusItem(timestamp, s));
}
if (history.size() > (size_t)max_history) {
history.pop_front();
}
timestamp = ceph_clock_now();
return status;
}
RGWCoroutinesManager::~RGWCoroutinesManager() {
stop();
completion_mgr->put();
if (cr_registry) {
cr_registry->remove(this);
}
}
int64_t RGWCoroutinesManager::get_next_io_id()
{
return (int64_t)++max_io_id;
}
uint64_t RGWCoroutinesManager::get_next_stack_id() {
return (uint64_t)++max_stack_id;
}
RGWCoroutinesStack::RGWCoroutinesStack(CephContext *_cct, RGWCoroutinesManager *_ops_mgr, RGWCoroutine *start) : cct(_cct), ops_mgr(_ops_mgr),
done_flag(false), error_flag(false), blocked_flag(false),
sleep_flag(false), interval_wait_flag(false), is_scheduled(false), is_waiting_for_child(false),
retcode(0), run_count(0),
env(NULL), parent(NULL)
{
id = ops_mgr->get_next_stack_id();
if (start) {
ops.push_back(start);
}
pos = ops.begin();
}
RGWCoroutinesStack::~RGWCoroutinesStack()
{
for (auto op : ops) {
op->put();
}
for (auto stack : spawned.entries) {
stack->put();
}
}
int RGWCoroutinesStack::operate(const DoutPrefixProvider *dpp, RGWCoroutinesEnv *_env)
{
env = _env;
RGWCoroutine *op = *pos;
op->stack = this;
ldpp_dout(dpp, 20) << *op << ": operate()" << dendl;
int r = op->operate_wrapper(dpp);
if (r < 0) {
ldpp_dout(dpp, 20) << *op << ": operate() returned r=" << r << dendl;
}
error_flag = op->is_error();
if (op->is_done()) {
int op_retcode = r;
r = unwind(op_retcode);
op->put();
done_flag = (pos == ops.end());
blocked_flag &= !done_flag;
if (done_flag) {
retcode = op_retcode;
}
return r;
}
/* should r ever be negative at this point? */
ceph_assert(r >= 0);
return 0;
}
string RGWCoroutinesStack::error_str()
{
if (pos != ops.end()) {
return (*pos)->error_str();
}
return string();
}
void RGWCoroutinesStack::call(RGWCoroutine *next_op) {
if (!next_op) {
return;
}
ops.push_back(next_op);
if (pos != ops.end()) {
++pos;
} else {
pos = ops.begin();
}
}
void RGWCoroutinesStack::schedule()
{
env->manager->schedule(env, this);
}
void RGWCoroutinesStack::_schedule()
{
env->manager->_schedule(env, this);
}
RGWCoroutinesStack *RGWCoroutinesStack::spawn(RGWCoroutine *source_op, RGWCoroutine *op, bool wait)
{
if (!op) {
return NULL;
}
rgw_spawned_stacks *s = (source_op ? &source_op->spawned : &spawned);
RGWCoroutinesStack *stack = env->manager->allocate_stack();
s->add_pending(stack);
stack->parent = this;
stack->get(); /* we'll need to collect the stack */
stack->call(op);
env->manager->schedule(env, stack);
if (wait) {
set_blocked_by(stack);
}
return stack;
}
RGWCoroutinesStack *RGWCoroutinesStack::spawn(RGWCoroutine *op, bool wait)
{
return spawn(NULL, op, wait);
}
int RGWCoroutinesStack::wait(const utime_t& interval)
{
RGWCompletionManager *completion_mgr = env->manager->get_completion_mgr();
completion_mgr->wait_interval((void *)this, interval, (void *)this);
set_io_blocked(true);
set_interval_wait(true);
return 0;
}
void RGWCoroutinesStack::wakeup()
{
RGWCompletionManager *completion_mgr = env->manager->get_completion_mgr();
completion_mgr->wakeup((void *)this);
}
void RGWCoroutinesStack::io_complete(const rgw_io_id& io_id)
{
RGWCompletionManager *completion_mgr = env->manager->get_completion_mgr();
completion_mgr->complete(nullptr, io_id, (void *)this);
}
int RGWCoroutinesStack::unwind(int retcode)
{
rgw_spawned_stacks *src_spawned = &(*pos)->spawned;
if (pos == ops.begin()) {
ldout(cct, 15) << "stack " << (void *)this << " end" << dendl;
spawned.inherit(src_spawned);
ops.clear();
pos = ops.end();
return retcode;
}
--pos;
ops.pop_back();
RGWCoroutine *op = *pos;
op->set_retcode(retcode);
op->spawned.inherit(src_spawned);
return 0;
}
void RGWCoroutinesStack::cancel()
{
while (!ops.empty()) {
RGWCoroutine *op = *pos;
unwind(-ECANCELED);
op->put();
}
put();
}
bool RGWCoroutinesStack::collect(RGWCoroutine *op, int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id) /* returns true if needs to be called again */
{
bool need_retry = false;
rgw_spawned_stacks *s = (op ? &op->spawned : &spawned);
*ret = 0;
vector<RGWCoroutinesStack *> new_list;
for (vector<RGWCoroutinesStack *>::iterator iter = s->entries.begin(); iter != s->entries.end(); ++iter) {
RGWCoroutinesStack *stack = *iter;
if (stack == skip_stack || !stack->is_done()) {
new_list.push_back(stack);
if (!stack->is_done()) {
ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " is still running" << dendl;
} else if (stack == skip_stack) {
ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " explicitly skipping stack" << dendl;
}
continue;
}
if (stack_id) {
*stack_id = stack->get_id();
}
int r = stack->get_ret_status();
stack->put();
if (r < 0) {
*ret = r;
ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " encountered error (r=" << r << "), skipping next stacks" << dendl;
new_list.insert(new_list.end(), ++iter, s->entries.end());
need_retry = (iter != s->entries.end());
break;
}
ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " is complete" << dendl;
}
s->entries.swap(new_list);
return need_retry;
}
bool RGWCoroutinesStack::collect_next(RGWCoroutine *op, int *ret, RGWCoroutinesStack **collected_stack) /* returns true if found a stack to collect */
{
rgw_spawned_stacks *s = (op ? &op->spawned : &spawned);
*ret = 0;
if (collected_stack) {
*collected_stack = NULL;
}
for (vector<RGWCoroutinesStack *>::iterator iter = s->entries.begin(); iter != s->entries.end(); ++iter) {
RGWCoroutinesStack *stack = *iter;
if (!stack->is_done()) {
continue;
}
int r = stack->get_ret_status();
if (r < 0) {
*ret = r;
}
if (collected_stack) {
*collected_stack = stack;
}
stack->put();
s->entries.erase(iter);
return true;
}
return false;
}
bool RGWCoroutinesStack::collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id) /* returns true if needs to be called again */
{
return collect(NULL, ret, skip_stack, stack_id);
}
static void _aio_completion_notifier_cb(librados::completion_t cb, void *arg)
{
(static_cast<RGWAioCompletionNotifier *>(arg))->cb();
}
RGWAioCompletionNotifier::RGWAioCompletionNotifier(RGWCompletionManager *_mgr, const rgw_io_id& _io_id, void *_user_data) : completion_mgr(_mgr),
io_id(_io_id),
user_data(_user_data), registered(true) {
c = librados::Rados::aio_create_completion(this, _aio_completion_notifier_cb);
}
RGWAioCompletionNotifier *RGWCoroutinesStack::create_completion_notifier()
{
return ops_mgr->create_completion_notifier(this);
}
RGWCompletionManager *RGWCoroutinesStack::get_completion_mgr()
{
return ops_mgr->get_completion_mgr();
}
bool RGWCoroutinesStack::unblock_stack(RGWCoroutinesStack **s)
{
if (blocking_stacks.empty()) {
return false;
}
set<RGWCoroutinesStack *>::iterator iter = blocking_stacks.begin();
*s = *iter;
blocking_stacks.erase(iter);
(*s)->blocked_by_stack.erase(this);
return true;
}
void RGWCoroutinesManager::report_error(RGWCoroutinesStack *op)
{
if (!op) {
return;
}
string err = op->error_str();
if (err.empty()) {
return;
}
lderr(cct) << "ERROR: failed operation: " << op->error_str() << dendl;
}
void RGWCoroutinesStack::dump(Formatter *f) const {
stringstream ss;
ss << (void *)this;
::encode_json("stack", ss.str(), f);
::encode_json("run_count", run_count, f);
f->open_array_section("ops");
for (auto& i : ops) {
encode_json("op", *i, f);
}
f->close_section();
}
void RGWCoroutinesStack::init_new_io(RGWIOProvider *io_provider)
{
io_provider->set_io_user_info((void *)this);
io_provider->assign_io(env->manager->get_io_id_provider());
}
bool RGWCoroutinesStack::try_io_unblock(const rgw_io_id& io_id)
{
if (!can_io_unblock(io_id)) {
auto p = io_finish_ids.emplace(io_id.id, io_id);
auto& iter = p.first;
bool inserted = p.second;
if (!inserted) { /* could not insert, entry already existed, add channel to completion mask */
iter->second.channels |= io_id.channels;
}
return false;
}
return true;
}
bool RGWCoroutinesStack::consume_io_finish(const rgw_io_id& io_id)
{
auto iter = io_finish_ids.find(io_id.id);
if (iter == io_finish_ids.end()) {
return false;
}
int finish_mask = iter->second.channels;
bool found = (finish_mask & io_id.channels) != 0;
finish_mask &= ~(finish_mask & io_id.channels);
if (finish_mask == 0) {
io_finish_ids.erase(iter);
}
return found;
}
void RGWCoroutinesManager::handle_unblocked_stack(set<RGWCoroutinesStack *>& context_stacks, list<RGWCoroutinesStack *>& scheduled_stacks,
RGWCompletionManager::io_completion& io, int *blocked_count, int *interval_wait_count)
{
ceph_assert(ceph_mutex_is_wlocked(lock));
RGWCoroutinesStack *stack = static_cast<RGWCoroutinesStack *>(io.user_info);
if (context_stacks.find(stack) == context_stacks.end()) {
return;
}
if (!stack->try_io_unblock(io.io_id)) {
return;
}
if (stack->is_io_blocked()) {
--(*blocked_count);
stack->set_io_blocked(false);
if (stack->is_interval_waiting()) {
--(*interval_wait_count);
}
}
stack->set_interval_wait(false);
if (!stack->is_done()) {
if (!stack->is_scheduled) {
scheduled_stacks.push_back(stack);
stack->set_is_scheduled(true);
}
} else {
context_stacks.erase(stack);
stack->put();
}
}
void RGWCoroutinesManager::schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack)
{
std::unique_lock wl{lock};
_schedule(env, stack);
}
void RGWCoroutinesManager::_schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack)
{
ceph_assert(ceph_mutex_is_wlocked(lock));
if (!stack->is_scheduled) {
env->scheduled_stacks->push_back(stack);
stack->set_is_scheduled(true);
}
set<RGWCoroutinesStack *>& context_stacks = run_contexts[env->run_context];
context_stacks.insert(stack);
}
void RGWCoroutinesManager::set_sleeping(RGWCoroutine *cr, bool flag)
{
cr->set_sleeping(flag);
}
void RGWCoroutinesManager::io_complete(RGWCoroutine *cr, const rgw_io_id& io_id)
{
cr->io_complete(io_id);
}
int RGWCoroutinesManager::run(const DoutPrefixProvider *dpp, list<RGWCoroutinesStack *>& stacks)
{
int ret = 0;
int blocked_count = 0;
int interval_wait_count = 0;
bool canceled = false; // set on going_down
RGWCoroutinesEnv env;
bool op_not_blocked;
uint64_t run_context = ++run_context_count;
lock.lock();
set<RGWCoroutinesStack *>& context_stacks = run_contexts[run_context];
list<RGWCoroutinesStack *> scheduled_stacks;
for (auto& st : stacks) {
context_stacks.insert(st);
scheduled_stacks.push_back(st);
st->set_is_scheduled(true);
}
env.run_context = run_context;
env.manager = this;
env.scheduled_stacks = &scheduled_stacks;
for (list<RGWCoroutinesStack *>::iterator iter = scheduled_stacks.begin(); iter != scheduled_stacks.end() && !going_down;) {
RGWCompletionManager::io_completion io;
RGWCoroutinesStack *stack = *iter;
++iter;
scheduled_stacks.pop_front();
if (context_stacks.find(stack) == context_stacks.end()) {
/* stack was probably schedule more than once due to IO, but was since complete */
goto next;
}
env.stack = stack;
lock.unlock();
ret = stack->operate(dpp, &env);
lock.lock();
stack->set_is_scheduled(false);
if (ret < 0) {
ldpp_dout(dpp, 20) << "stack->operate() returned ret=" << ret << dendl;
}
if (stack->is_error()) {
report_error(stack);
}
op_not_blocked = false;
if (stack->is_io_blocked()) {
ldout(cct, 20) << __func__ << ":" << " stack=" << (void *)stack << " is io blocked" << dendl;
if (stack->is_interval_waiting()) {
interval_wait_count++;
}
blocked_count++;
} else if (stack->is_blocked()) {
/* do nothing, we'll re-add the stack when the blocking stack is done,
* or when we're awaken
*/
ldout(cct, 20) << __func__ << ":" << " stack=" << (void *)stack << " is_blocked_by_stack()=" << stack->is_blocked_by_stack()
<< " is_sleeping=" << stack->is_sleeping() << " waiting_for_child()=" << stack->waiting_for_child() << dendl;
} else if (stack->is_done()) {
ldout(cct, 20) << __func__ << ":" << " stack=" << (void *)stack << " is done" << dendl;
RGWCoroutinesStack *s;
while (stack->unblock_stack(&s)) {
if (!s->is_blocked_by_stack() && !s->is_done()) {
if (s->is_io_blocked()) {
if (stack->is_interval_waiting()) {
interval_wait_count++;
}
blocked_count++;
} else {
s->_schedule();
}
}
}
if (stack->parent && stack->parent->waiting_for_child()) {
stack->parent->set_wait_for_child(false);
stack->parent->_schedule();
}
context_stacks.erase(stack);
stack->put();
stack = NULL;
} else {
op_not_blocked = true;
stack->run_count++;
stack->_schedule();
}
if (!op_not_blocked && stack) {
stack->run_count = 0;
}
while (completion_mgr->try_get_next(&io)) {
handle_unblocked_stack(context_stacks, scheduled_stacks, io, &blocked_count, &interval_wait_count);
}
/*
* only account blocked operations that are not in interval_wait, these are stacks that
* were put on a wait without any real IO operations. While we mark these as io_blocked,
* these aren't really waiting for IOs
*/
while (blocked_count - interval_wait_count >= ops_window) {
lock.unlock();
ret = completion_mgr->get_next(&io);
lock.lock();
if (ret < 0) {
ldout(cct, 5) << "completion_mgr.get_next() returned ret=" << ret << dendl;
}
handle_unblocked_stack(context_stacks, scheduled_stacks, io, &blocked_count, &interval_wait_count);
}
next:
while (scheduled_stacks.empty() && blocked_count > 0) {
lock.unlock();
ret = completion_mgr->get_next(&io);
lock.lock();
if (ret < 0) {
ldout(cct, 5) << "completion_mgr.get_next() returned ret=" << ret << dendl;
}
if (going_down) {
ldout(cct, 5) << __func__ << "(): was stopped, exiting" << dendl;
ret = -ECANCELED;
canceled = true;
break;
}
handle_unblocked_stack(context_stacks, scheduled_stacks, io, &blocked_count, &interval_wait_count);
iter = scheduled_stacks.begin();
}
if (canceled) {
break;
}
if (iter == scheduled_stacks.end()) {
iter = scheduled_stacks.begin();
}
}
if (!context_stacks.empty() && !going_down) {
JSONFormatter formatter(true);
formatter.open_array_section("context_stacks");
for (auto& s : context_stacks) {
::encode_json("entry", *s, &formatter);
}
formatter.close_section();
lderr(cct) << __func__ << "(): ERROR: deadlock detected, dumping remaining coroutines:\n";
formatter.flush(*_dout);
*_dout << dendl;
ceph_assert(context_stacks.empty() || going_down); // assert on deadlock
}
for (auto stack : context_stacks) {
ldout(cct, 20) << "clearing stack on run() exit: stack=" << (void *)stack << " nref=" << stack->get_nref() << dendl;
stack->cancel();
}
run_contexts.erase(run_context);
lock.unlock();
return ret;
}
int RGWCoroutinesManager::run(const DoutPrefixProvider *dpp, RGWCoroutine *op)
{
if (!op) {
return 0;
}
list<RGWCoroutinesStack *> stacks;
RGWCoroutinesStack *stack = allocate_stack();
op->get();
stack->call(op);
stacks.push_back(stack);
int r = run(dpp, stacks);
if (r < 0) {
ldpp_dout(dpp, 20) << "run(stacks) returned r=" << r << dendl;
} else {
r = op->get_ret_status();
}
op->put();
return r;
}
RGWAioCompletionNotifier *RGWCoroutinesManager::create_completion_notifier(RGWCoroutinesStack *stack)
{
rgw_io_id io_id{get_next_io_id(), -1};
RGWAioCompletionNotifier *cn = new RGWAioCompletionNotifier(completion_mgr, io_id, (void *)stack);
completion_mgr->register_completion_notifier(cn);
return cn;
}
void RGWCoroutinesManager::dump(Formatter *f) const {
std::shared_lock rl{lock};
f->open_array_section("run_contexts");
for (auto& i : run_contexts) {
f->open_object_section("context");
::encode_json("id", i.first, f);
f->open_array_section("entries");
for (auto& s : i.second) {
::encode_json("entry", *s, f);
}
f->close_section();
f->close_section();
}
f->close_section();
}
RGWCoroutinesStack *RGWCoroutinesManager::allocate_stack() {
return new RGWCoroutinesStack(cct, this);
}
string RGWCoroutinesManager::get_id()
{
if (!id.empty()) {
return id;
}
stringstream ss;
ss << (void *)this;
return ss.str();
}
void RGWCoroutinesManagerRegistry::add(RGWCoroutinesManager *mgr)
{
std::unique_lock wl{lock};
if (managers.find(mgr) == managers.end()) {
managers.insert(mgr);
get();
}
}
void RGWCoroutinesManagerRegistry::remove(RGWCoroutinesManager *mgr)
{
std::unique_lock wl{lock};
if (managers.find(mgr) != managers.end()) {
managers.erase(mgr);
put();
}
}
RGWCoroutinesManagerRegistry::~RGWCoroutinesManagerRegistry()
{
AdminSocket *admin_socket = cct->get_admin_socket();
if (!admin_command.empty()) {
admin_socket->unregister_commands(this);
}
}
int RGWCoroutinesManagerRegistry::hook_to_admin_command(const string& command)
{
AdminSocket *admin_socket = cct->get_admin_socket();
if (!admin_command.empty()) {
admin_socket->unregister_commands(this);
}
admin_command = command;
int r = admin_socket->register_command(admin_command, this,
"dump current coroutines stack state");
if (r < 0) {
lderr(cct) << "ERROR: fail to register admin socket command (r=" << r << ")" << dendl;
return r;
}
return 0;
}
int RGWCoroutinesManagerRegistry::call(std::string_view command,
const cmdmap_t& cmdmap,
const bufferlist&,
Formatter *f,
std::ostream& ss,
bufferlist& out) {
std::shared_lock rl{lock};
::encode_json("cr_managers", *this, f);
return 0;
}
void RGWCoroutinesManagerRegistry::dump(Formatter *f) const {
f->open_array_section("coroutine_managers");
for (auto m : managers) {
::encode_json("entry", *m, f);
}
f->close_section();
}
void RGWCoroutine::call(RGWCoroutine *op)
{
if (op) {
stack->call(op);
} else {
// the call()er expects this to set a retcode
retcode = 0;
}
}
RGWCoroutinesStack *RGWCoroutine::spawn(RGWCoroutine *op, bool wait)
{
return stack->spawn(this, op, wait);
}
bool RGWCoroutine::collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id) /* returns true if needs to be called again */
{
return stack->collect(this, ret, skip_stack, stack_id);
}
bool RGWCoroutine::collect_next(int *ret, RGWCoroutinesStack **collected_stack) /* returns true if found a stack to collect */
{
return stack->collect_next(this, ret, collected_stack);
}
int RGWCoroutine::wait(const utime_t& interval)
{
return stack->wait(interval);
}
void RGWCoroutine::wait_for_child()
{
/* should only wait for child if there is a child that is not done yet, and no complete children */
if (spawned.entries.empty()) {
return;
}
for (vector<RGWCoroutinesStack *>::iterator iter = spawned.entries.begin(); iter != spawned.entries.end(); ++iter) {
if ((*iter)->is_done()) {
return;
}
}
stack->set_wait_for_child(true);
}
string RGWCoroutine::to_str() const
{
return typeid(*this).name();
}
ostream& operator<<(ostream& out, const RGWCoroutine& cr)
{
out << "cr:s=" << (void *)cr.get_stack() << ":op=" << (void *)&cr << ":" << typeid(cr).name();
return out;
}
bool RGWCoroutine::drain_children(int num_cr_left,
RGWCoroutinesStack *skip_stack,
std::optional<std::function<void(uint64_t stack_id, int ret)> > cb)
{
bool done = false;
ceph_assert(num_cr_left >= 0);
if (num_cr_left == 0 && skip_stack) {
num_cr_left = 1;
}
reenter(&drain_status.cr) {
while (num_spawned() > (size_t)num_cr_left) {
yield wait_for_child();
int ret;
uint64_t stack_id;
bool again = false;
do {
again = collect(&ret, skip_stack, &stack_id);
if (ret < 0) {
ldout(cct, 10) << "collect() returned ret=" << ret << dendl;
/* we should have reported this error */
log_error() << "ERROR: collect() returned error (ret=" << ret << ")";
}
if (cb) {
(*cb)(stack_id, ret);
}
} while (again);
}
done = true;
}
return done;
}
bool RGWCoroutine::drain_children(int num_cr_left,
std::optional<std::function<int(uint64_t stack_id, int ret)> > cb)
{
bool done = false;
ceph_assert(num_cr_left >= 0);
reenter(&drain_status.cr) {
while (num_spawned() > (size_t)num_cr_left) {
yield wait_for_child();
int ret;
uint64_t stack_id;
bool again = false;
do {
again = collect(&ret, nullptr, &stack_id);
if (ret < 0) {
ldout(cct, 10) << "collect() returned ret=" << ret << dendl;
/* we should have reported this error */
log_error() << "ERROR: collect() returned error (ret=" << ret << ")";
}
if (cb && !drain_status.should_exit) {
int r = (*cb)(stack_id, ret);
if (r < 0) {
drain_status.ret = r;
drain_status.should_exit = true;
num_cr_left = 0; /* need to drain all */
}
}
} while (again);
}
done = true;
}
return done;
}
void RGWCoroutine::wakeup()
{
if (stack) {
stack->wakeup();
}
}
RGWCoroutinesEnv *RGWCoroutine::get_env() const
{
return stack->get_env();
}
void RGWCoroutine::dump(Formatter *f) const {
if (!description.str().empty()) {
encode_json("description", description.str(), f);
}
encode_json("type", to_str(), f);
if (!spawned.entries.empty()) {
f->open_array_section("spawned");
for (auto& i : spawned.entries) {
char buf[32];
snprintf(buf, sizeof(buf), "%p", (void *)i);
encode_json("stack", string(buf), f);
}
f->close_section();
}
if (!status.history.empty()) {
encode_json("history", status.history, f);
}
if (!status.status.str().empty()) {
f->open_object_section("status");
encode_json("status", status.status.str(), f);
encode_json("timestamp", status.timestamp, f);
f->close_section();
}
}
RGWSimpleCoroutine::~RGWSimpleCoroutine()
{
if (!called_cleanup) {
request_cleanup();
}
}
void RGWSimpleCoroutine::call_cleanup()
{
called_cleanup = true;
request_cleanup();
}
int RGWSimpleCoroutine::operate(const DoutPrefixProvider *dpp)
{
int ret = 0;
reenter(this) {
yield return state_init();
yield return state_send_request(dpp);
yield return state_request_complete();
yield return state_all_complete();
drain_all();
call_cleanup();
return set_state(RGWCoroutine_Done, ret);
}
return 0;
}
int RGWSimpleCoroutine::state_init()
{
int ret = init();
if (ret < 0) {
call_cleanup();
return set_state(RGWCoroutine_Error, ret);
}
return 0;
}
int RGWSimpleCoroutine::state_send_request(const DoutPrefixProvider *dpp)
{
int ret = send_request(dpp);
if (ret < 0) {
call_cleanup();
return set_state(RGWCoroutine_Error, ret);
}
return io_block(0);
}
int RGWSimpleCoroutine::state_request_complete()
{
int ret = request_complete();
if (ret < 0) {
call_cleanup();
return set_state(RGWCoroutine_Error, ret);
}
return 0;
}
int RGWSimpleCoroutine::state_all_complete()
{
int ret = finish();
if (ret < 0) {
call_cleanup();
return set_state(RGWCoroutine_Error, ret);
}
return 0;
}
| 29,156 | 24.779841 | 200 |
cc
|
null |
ceph-main/src/rgw/rgw_coroutine.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#ifdef _ASSERT_H
#define NEED_ASSERT_H
#pragma push_macro("_ASSERT_H")
#endif
#include <boost/asio.hpp>
#include <boost/intrusive_ptr.hpp>
#ifdef NEED_ASSERT_H
#pragma pop_macro("_ASSERT_H")
#endif
#include "include/utime.h"
#include "common/RefCountedObj.h"
#include "common/debug.h"
#include "common/Timer.h"
#include "common/admin_socket.h"
#include "rgw_common.h"
#include "rgw_http_client_types.h"
#include <boost/asio/coroutine.hpp>
#include <atomic>
#define RGW_ASYNC_OPS_MGR_WINDOW 100
class RGWCoroutinesStack;
class RGWCoroutinesManager;
class RGWAioCompletionNotifier;
class RGWCompletionManager : public RefCountedObject {
friend class RGWCoroutinesManager;
CephContext *cct;
struct io_completion {
rgw_io_id io_id;
void *user_info;
};
std::list<io_completion> complete_reqs;
std::set<rgw_io_id> complete_reqs_set;
using NotifierRef = boost::intrusive_ptr<RGWAioCompletionNotifier>;
std::set<NotifierRef> cns;
ceph::mutex lock = ceph::make_mutex("RGWCompletionManager::lock");
ceph::condition_variable cond;
SafeTimer timer;
std::atomic<bool> going_down = { false };
std::map<void *, void *> waiters;
class WaitContext;
protected:
void _wakeup(void *opaque);
void _complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info);
public:
explicit RGWCompletionManager(CephContext *_cct);
virtual ~RGWCompletionManager() override;
void complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info);
int get_next(io_completion *io);
bool try_get_next(io_completion *io);
void go_down();
/*
* wait for interval length to complete user_info
*/
void wait_interval(void *opaque, const utime_t& interval, void *user_info);
void wakeup(void *opaque);
void register_completion_notifier(RGWAioCompletionNotifier *cn);
void unregister_completion_notifier(RGWAioCompletionNotifier *cn);
};
/* a single use librados aio completion notifier that hooks into the RGWCompletionManager */
class RGWAioCompletionNotifier : public RefCountedObject {
librados::AioCompletion *c;
RGWCompletionManager *completion_mgr;
rgw_io_id io_id;
void *user_data;
ceph::mutex lock = ceph::make_mutex("RGWAioCompletionNotifier");
bool registered;
public:
RGWAioCompletionNotifier(RGWCompletionManager *_mgr, const rgw_io_id& _io_id, void *_user_data);
virtual ~RGWAioCompletionNotifier() override {
c->release();
lock.lock();
bool need_unregister = registered;
if (registered) {
completion_mgr->get();
}
registered = false;
lock.unlock();
if (need_unregister) {
completion_mgr->unregister_completion_notifier(this);
completion_mgr->put();
}
}
librados::AioCompletion *completion() {
return c;
}
void unregister() {
std::lock_guard l{lock};
if (!registered) {
return;
}
registered = false;
}
void cb() {
lock.lock();
if (!registered) {
lock.unlock();
put();
return;
}
completion_mgr->get();
registered = false;
lock.unlock();
completion_mgr->complete(this, io_id, user_data);
completion_mgr->put();
put();
}
};
// completion notifier with opaque payload (ie a reference-counted pointer)
template <typename T>
class RGWAioCompletionNotifierWith : public RGWAioCompletionNotifier {
T value;
public:
RGWAioCompletionNotifierWith(RGWCompletionManager *mgr,
const rgw_io_id& io_id, void *user_data,
T value)
: RGWAioCompletionNotifier(mgr, io_id, user_data), value(std::move(value))
{}
};
struct RGWCoroutinesEnv {
uint64_t run_context;
RGWCoroutinesManager *manager;
std::list<RGWCoroutinesStack *> *scheduled_stacks;
RGWCoroutinesStack *stack;
RGWCoroutinesEnv() : run_context(0), manager(NULL), scheduled_stacks(NULL), stack(NULL) {}
};
enum RGWCoroutineState {
RGWCoroutine_Error = -2,
RGWCoroutine_Done = -1,
RGWCoroutine_Run = 0,
};
struct rgw_spawned_stacks {
std::vector<RGWCoroutinesStack *> entries;
rgw_spawned_stacks() {}
void add_pending(RGWCoroutinesStack *s) {
entries.push_back(s);
}
void inherit(rgw_spawned_stacks *source) {
for (auto* entry : source->entries) {
add_pending(entry);
}
source->entries.clear();
}
};
class RGWCoroutine : public RefCountedObject, public boost::asio::coroutine {
friend class RGWCoroutinesStack;
struct StatusItem {
utime_t timestamp;
std::string status;
StatusItem(utime_t& t, const std::string& s) : timestamp(t), status(s) {}
void dump(Formatter *f) const;
};
#define MAX_COROUTINE_HISTORY 10
struct Status {
CephContext *cct;
ceph::shared_mutex lock =
ceph::make_shared_mutex("RGWCoroutine::Status::lock");
int max_history;
utime_t timestamp;
std::stringstream status;
explicit Status(CephContext *_cct) : cct(_cct), max_history(MAX_COROUTINE_HISTORY) {}
std::deque<StatusItem> history;
std::stringstream& set_status();
} status;
std::stringstream description;
protected:
bool _yield_ret;
struct {
boost::asio::coroutine cr;
bool should_exit{false};
int ret{0};
void init() {
cr = boost::asio::coroutine();
should_exit = false;
ret = 0;
}
} drain_status;
CephContext *cct;
RGWCoroutinesStack *stack;
int retcode;
int state;
rgw_spawned_stacks spawned;
std::stringstream error_stream;
int set_state(int s, int ret = 0) {
retcode = ret;
state = s;
return ret;
}
int set_cr_error(int ret) {
return set_state(RGWCoroutine_Error, ret);
}
int set_cr_done() {
return set_state(RGWCoroutine_Done, 0);
}
void set_io_blocked(bool flag);
void reset_description() {
description.str(std::string());
}
std::stringstream& set_description() {
return description;
}
std::stringstream& set_status() {
return status.set_status();
}
std::stringstream& set_status(const std::string& s) {
std::stringstream& status = set_status();
status << s;
return status;
}
virtual int operate_wrapper(const DoutPrefixProvider *dpp) {
return operate(dpp);
}
public:
RGWCoroutine(CephContext *_cct) : status(_cct), _yield_ret(false), cct(_cct), stack(NULL), retcode(0), state(RGWCoroutine_Run) {}
virtual ~RGWCoroutine() override;
virtual int operate(const DoutPrefixProvider *dpp) = 0;
bool is_done() { return (state == RGWCoroutine_Done || state == RGWCoroutine_Error); }
bool is_error() { return (state == RGWCoroutine_Error); }
std::stringstream& log_error() { return error_stream; }
std::string error_str() {
return error_stream.str();
}
void set_retcode(int r) {
retcode = r;
}
int get_ret_status() {
return retcode;
}
void call(RGWCoroutine *op); /* call at the same stack we're in */
RGWCoroutinesStack *spawn(RGWCoroutine *op, bool wait); /* execute on a different stack */
bool collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id = nullptr); /* returns true if needs to be called again */
bool collect_next(int *ret, RGWCoroutinesStack **collected_stack = NULL); /* returns true if found a stack to collect */
int wait(const utime_t& interval);
bool drain_children(int num_cr_left,
RGWCoroutinesStack *skip_stack = nullptr,
std::optional<std::function<void(uint64_t stack_id, int ret)> > cb = std::nullopt); /* returns true if needed to be called again,
cb will be called on completion of every
completion. */
bool drain_children(int num_cr_left,
std::optional<std::function<int(uint64_t stack_id, int ret)> > cb); /* returns true if needed to be called again,
cb will be called on every completion, can filter errors.
A negative return value from cb means that current cr
will need to exit */
void wakeup();
void set_sleeping(bool flag); /* put in sleep, or wakeup from sleep */
size_t num_spawned() {
return spawned.entries.size();
}
void wait_for_child();
virtual std::string to_str() const;
RGWCoroutinesStack *get_stack() const {
return stack;
}
RGWCoroutinesEnv *get_env() const;
void dump(Formatter *f) const;
void init_new_io(RGWIOProvider *io_provider); /* only links the default io id */
int io_block(int ret = 0) {
return io_block(ret, -1);
}
int io_block(int ret, int64_t io_id);
int io_block(int ret, const rgw_io_id& io_id);
void io_complete() {
io_complete(rgw_io_id{});
}
void io_complete(const rgw_io_id& io_id);
};
std::ostream& operator<<(std::ostream& out, const RGWCoroutine& cr);
#define yield_until_true(x) \
do { \
do { \
yield _yield_ret = x; \
} while (!_yield_ret); \
_yield_ret = false; \
} while (0)
#define drain_all() \
drain_status.init(); \
yield_until_true(drain_children(0))
#define drain_all_but(n) \
drain_status.init(); \
yield_until_true(drain_children(n))
#define drain_all_but_stack(stack) \
drain_status.init(); \
yield_until_true(drain_children(1, stack))
#define drain_all_but_stack_cb(stack, cb) \
drain_status.init(); \
yield_until_true(drain_children(1, stack, cb))
#define drain_with_cb(n, cb) \
drain_status.init(); \
yield_until_true(drain_children(n, cb)); \
if (drain_status.should_exit) { \
return set_cr_error(drain_status.ret); \
}
#define drain_all_cb(cb) \
drain_with_cb(0, cb)
#define yield_spawn_window(cr, n, cb) \
do { \
spawn(cr, false); \
drain_with_cb(n, cb); /* this is guaranteed to yield */ \
} while (0)
template <class T>
class RGWConsumerCR : public RGWCoroutine {
std::list<T> product;
public:
explicit RGWConsumerCR(CephContext *_cct) : RGWCoroutine(_cct) {}
bool has_product() {
return !product.empty();
}
void wait_for_product() {
if (!has_product()) {
set_sleeping(true);
}
}
bool consume(T *p) {
if (product.empty()) {
return false;
}
*p = product.front();
product.pop_front();
return true;
}
void receive(const T& p, bool wakeup = true);
void receive(std::list<T>& l, bool wakeup = true);
};
class RGWCoroutinesStack : public RefCountedObject {
friend class RGWCoroutine;
friend class RGWCoroutinesManager;
CephContext *cct;
int64_t id{-1};
RGWCoroutinesManager *ops_mgr;
std::list<RGWCoroutine *> ops;
std::list<RGWCoroutine *>::iterator pos;
rgw_spawned_stacks spawned;
std::set<RGWCoroutinesStack *> blocked_by_stack;
std::set<RGWCoroutinesStack *> blocking_stacks;
std::map<int64_t, rgw_io_id> io_finish_ids;
rgw_io_id io_blocked_id;
bool done_flag;
bool error_flag;
bool blocked_flag;
bool sleep_flag;
bool interval_wait_flag;
bool is_scheduled;
bool is_waiting_for_child;
int retcode;
uint64_t run_count;
protected:
RGWCoroutinesEnv *env;
RGWCoroutinesStack *parent;
RGWCoroutinesStack *spawn(RGWCoroutine *source_op, RGWCoroutine *next_op, bool wait);
bool collect(RGWCoroutine *op, int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id); /* returns true if needs to be called again */
bool collect_next(RGWCoroutine *op, int *ret, RGWCoroutinesStack **collected_stack); /* returns true if found a stack to collect */
public:
RGWCoroutinesStack(CephContext *_cct, RGWCoroutinesManager *_ops_mgr, RGWCoroutine *start = NULL);
virtual ~RGWCoroutinesStack() override;
int64_t get_id() const {
return id;
}
int operate(const DoutPrefixProvider *dpp, RGWCoroutinesEnv *env);
bool is_done() {
return done_flag;
}
bool is_error() {
return error_flag;
}
bool is_blocked_by_stack() {
return !blocked_by_stack.empty();
}
void set_io_blocked(bool flag) {
blocked_flag = flag;
}
void set_io_blocked_id(const rgw_io_id& io_id) {
io_blocked_id = io_id;
}
bool is_io_blocked() {
return blocked_flag && !done_flag;
}
bool can_io_unblock(const rgw_io_id& io_id) {
return ((io_blocked_id.id < 0) ||
io_blocked_id.intersects(io_id));
}
bool try_io_unblock(const rgw_io_id& io_id);
bool consume_io_finish(const rgw_io_id& io_id);
void set_interval_wait(bool flag) {
interval_wait_flag = flag;
}
bool is_interval_waiting() {
return interval_wait_flag;
}
void set_sleeping(bool flag) {
bool wakeup = sleep_flag & !flag;
sleep_flag = flag;
if (wakeup) {
schedule();
}
}
bool is_sleeping() {
return sleep_flag;
}
void set_is_scheduled(bool flag) {
is_scheduled = flag;
}
bool is_blocked() {
return is_blocked_by_stack() || is_sleeping() ||
is_io_blocked() || waiting_for_child() ;
}
void schedule();
void _schedule();
int get_ret_status() {
return retcode;
}
std::string error_str();
void call(RGWCoroutine *next_op);
RGWCoroutinesStack *spawn(RGWCoroutine *next_op, bool wait);
int unwind(int retcode);
int wait(const utime_t& interval);
void wakeup();
void io_complete() {
io_complete(rgw_io_id{});
}
void io_complete(const rgw_io_id& io_id);
bool collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id); /* returns true if needs to be called again */
void cancel();
RGWAioCompletionNotifier *create_completion_notifier();
template <typename T>
RGWAioCompletionNotifier *create_completion_notifier(T value);
RGWCompletionManager *get_completion_mgr();
void set_blocked_by(RGWCoroutinesStack *s) {
blocked_by_stack.insert(s);
s->blocking_stacks.insert(this);
}
void set_wait_for_child(bool flag) {
is_waiting_for_child = flag;
}
bool waiting_for_child() {
return is_waiting_for_child;
}
bool unblock_stack(RGWCoroutinesStack **s);
RGWCoroutinesEnv *get_env() const { return env; }
void dump(Formatter *f) const;
void init_new_io(RGWIOProvider *io_provider);
};
template <class T>
void RGWConsumerCR<T>::receive(std::list<T>& l, bool wakeup)
{
product.splice(product.end(), l);
if (wakeup) {
set_sleeping(false);
}
}
template <class T>
void RGWConsumerCR<T>::receive(const T& p, bool wakeup)
{
product.push_back(p);
if (wakeup) {
set_sleeping(false);
}
}
class RGWCoroutinesManagerRegistry : public RefCountedObject, public AdminSocketHook {
CephContext *cct;
std::set<RGWCoroutinesManager *> managers;
ceph::shared_mutex lock =
ceph::make_shared_mutex("RGWCoroutinesRegistry::lock");
std::string admin_command;
public:
explicit RGWCoroutinesManagerRegistry(CephContext *_cct) : cct(_cct) {}
virtual ~RGWCoroutinesManagerRegistry() override;
void add(RGWCoroutinesManager *mgr);
void remove(RGWCoroutinesManager *mgr);
int hook_to_admin_command(const std::string& command);
int call(std::string_view command, const cmdmap_t& cmdmap,
const bufferlist&,
Formatter *f,
std::ostream& ss,
bufferlist& out) override;
void dump(Formatter *f) const;
};
class RGWCoroutinesManager {
CephContext *cct;
std::atomic<bool> going_down = { false };
std::atomic<int64_t> run_context_count = { 0 };
std::map<uint64_t, std::set<RGWCoroutinesStack *> > run_contexts;
std::atomic<int64_t> max_io_id = { 0 };
std::atomic<uint64_t> max_stack_id = { 0 };
mutable ceph::shared_mutex lock =
ceph::make_shared_mutex("RGWCoroutinesManager::lock");
RGWIOIDProvider io_id_provider;
void handle_unblocked_stack(std::set<RGWCoroutinesStack *>& context_stacks, std::list<RGWCoroutinesStack *>& scheduled_stacks,
RGWCompletionManager::io_completion& io, int *waiting_count, int *interval_wait_count);
protected:
RGWCompletionManager *completion_mgr;
RGWCoroutinesManagerRegistry *cr_registry;
int ops_window;
std::string id;
void put_completion_notifier(RGWAioCompletionNotifier *cn);
public:
RGWCoroutinesManager(CephContext *_cct, RGWCoroutinesManagerRegistry *_cr_registry) : cct(_cct),
cr_registry(_cr_registry), ops_window(RGW_ASYNC_OPS_MGR_WINDOW) {
completion_mgr = new RGWCompletionManager(cct);
if (cr_registry) {
cr_registry->add(this);
}
}
virtual ~RGWCoroutinesManager();
int run(const DoutPrefixProvider *dpp, std::list<RGWCoroutinesStack *>& ops);
int run(const DoutPrefixProvider *dpp, RGWCoroutine *op);
void stop() {
bool expected = false;
if (going_down.compare_exchange_strong(expected, true)) {
completion_mgr->go_down();
}
}
virtual void report_error(RGWCoroutinesStack *op);
RGWAioCompletionNotifier *create_completion_notifier(RGWCoroutinesStack *stack);
template <typename T>
RGWAioCompletionNotifier *create_completion_notifier(RGWCoroutinesStack *stack, T value);
RGWCompletionManager *get_completion_mgr() { return completion_mgr; }
void schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack);
void _schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack);
RGWCoroutinesStack *allocate_stack();
int64_t get_next_io_id();
uint64_t get_next_stack_id();
void set_sleeping(RGWCoroutine *cr, bool flag);
void io_complete(RGWCoroutine *cr, const rgw_io_id& io_id);
virtual std::string get_id();
void dump(Formatter *f) const;
RGWIOIDProvider& get_io_id_provider() {
return io_id_provider;
}
};
template <typename T>
RGWAioCompletionNotifier *RGWCoroutinesManager::create_completion_notifier(RGWCoroutinesStack *stack, T value)
{
rgw_io_id io_id{get_next_io_id(), -1};
RGWAioCompletionNotifier *cn = new RGWAioCompletionNotifierWith<T>(completion_mgr, io_id, (void *)stack, std::move(value));
completion_mgr->register_completion_notifier(cn);
return cn;
}
template <typename T>
RGWAioCompletionNotifier *RGWCoroutinesStack::create_completion_notifier(T value)
{
return ops_mgr->create_completion_notifier(this, std::move(value));
}
class RGWSimpleCoroutine : public RGWCoroutine {
bool called_cleanup;
int operate(const DoutPrefixProvider *dpp) override;
int state_init();
int state_send_request(const DoutPrefixProvider *dpp);
int state_request_complete();
int state_all_complete();
void call_cleanup();
public:
RGWSimpleCoroutine(CephContext *_cct) : RGWCoroutine(_cct), called_cleanup(false) {}
virtual ~RGWSimpleCoroutine() override;
virtual int init() { return 0; }
virtual int send_request(const DoutPrefixProvider *dpp) = 0;
virtual int request_complete() = 0;
virtual int finish() { return 0; }
virtual void request_cleanup() {}
};
| 19,197 | 25.55325 | 153 |
h
|
null |
ceph-main/src/rgw/rgw_cors.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[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 <string.h>
#include <iostream>
#include <map>
#include <boost/algorithm/string.hpp>
#include "include/types.h"
#include "common/debug.h"
#include "include/str_list.h"
#include "common/Formatter.h"
#include "rgw_cors.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
void RGWCORSRule::dump_origins() {
unsigned num_origins = allowed_origins.size();
dout(10) << "Allowed origins : " << num_origins << dendl;
for(auto& origin : allowed_origins) {
dout(10) << origin << "," << dendl;
}
}
void RGWCORSRule::erase_origin_if_present(string& origin, bool *rule_empty) {
set<string>::iterator it = allowed_origins.find(origin);
if (!rule_empty)
return;
*rule_empty = false;
if (it != allowed_origins.end()) {
dout(10) << "Found origin " << origin << ", set size:" <<
allowed_origins.size() << dendl;
allowed_origins.erase(it);
*rule_empty = (allowed_origins.empty());
}
}
/*
* make attrs look-like-this
* does not convert underscores or dashes
*
* Per CORS specification, section 3:
* ===
* "Converting a string to ASCII lowercase" means replacing all characters in the
* range U+0041 LATIN CAPITAL LETTER A to U+005A LATIN CAPITAL LETTER Z with
* the corresponding characters in the range U+0061 LATIN SMALL LETTER A to
* U+007A LATIN SMALL LETTER Z).
* ===
*
* @todo When UTF-8 is allowed in HTTP headers, this function will need to change
*/
string lowercase_http_attr(const string& orig)
{
const char *s = orig.c_str();
char buf[orig.size() + 1];
buf[orig.size()] = '\0';
for (size_t i = 0; i < orig.size(); ++i, ++s) {
buf[i] = tolower(*s);
}
return string(buf);
}
static bool is_string_in_set(set<string>& s, string h) {
if ((s.find("*") != s.end()) ||
(s.find(h) != s.end())) {
return true;
}
/* The header can be Content-*-type, or Content-* */
for(set<string>::iterator it = s.begin();
it != s.end(); ++it) {
size_t off;
if ((off = (*it).find("*"))!=string::npos) {
list<string> ssplit;
unsigned flen = 0;
get_str_list((*it), "* \t", ssplit);
if (off != 0) {
string sl = ssplit.front();
flen = sl.length();
dout(10) << "Finding " << sl << ", in " << h << ", at offset 0" << dendl;
if (!boost::algorithm::starts_with(h,sl))
continue;
ssplit.pop_front();
}
if (off != ((*it).length() - 1)) {
string sl = ssplit.front();
dout(10) << "Finding " << sl << ", in " << h
<< ", at offset not less than " << flen << dendl;
if (h.size() < sl.size() ||
h.compare((h.size() - sl.size()), sl.size(), sl) != 0)
continue;
ssplit.pop_front();
}
if (!ssplit.empty())
continue;
return true;
}
}
return false;
}
bool RGWCORSRule::has_wildcard_origin() {
if (allowed_origins.find("*") != allowed_origins.end())
return true;
return false;
}
bool RGWCORSRule::is_origin_present(const char *o) {
string origin = o;
return is_string_in_set(allowed_origins, origin);
}
bool RGWCORSRule::is_header_allowed(const char *h, size_t len) {
string hdr(h, len);
if(lowercase_allowed_hdrs.empty()) {
set<string>::iterator iter;
for (iter = allowed_hdrs.begin(); iter != allowed_hdrs.end(); ++iter) {
lowercase_allowed_hdrs.insert(lowercase_http_attr(*iter));
}
}
return is_string_in_set(lowercase_allowed_hdrs, lowercase_http_attr(hdr));
}
void RGWCORSRule::format_exp_headers(string& s) {
s = "";
for (const auto& header : exposable_hdrs) {
if (s.length() > 0)
s.append(",");
// these values are sent to clients in a 'Access-Control-Expose-Headers'
// response header, so we escape '\n' to avoid header injection
boost::replace_all_copy(std::back_inserter(s), header, "\n", "\\n");
}
}
RGWCORSRule * RGWCORSConfiguration::host_name_rule(const char *origin) {
for(list<RGWCORSRule>::iterator it_r = rules.begin();
it_r != rules.end(); ++it_r) {
RGWCORSRule& r = (*it_r);
if (r.is_origin_present(origin))
return &r;
}
return NULL;
}
void RGWCORSConfiguration::erase_host_name_rule(string& origin) {
bool rule_empty;
unsigned loop = 0;
/*Erase the host name from that rule*/
dout(10) << "Num of rules : " << rules.size() << dendl;
for(list<RGWCORSRule>::iterator it_r = rules.begin();
it_r != rules.end(); ++it_r, loop++) {
RGWCORSRule& r = (*it_r);
r.erase_origin_if_present(origin, &rule_empty);
dout(10) << "Origin:" << origin << ", rule num:"
<< loop << ", emptying now:" << rule_empty << dendl;
if (rule_empty) {
rules.erase(it_r);
break;
}
}
}
void RGWCORSConfiguration::dump() {
unsigned loop = 1;
unsigned num_rules = rules.size();
dout(10) << "Number of rules: " << num_rules << dendl;
for(list<RGWCORSRule>::iterator it = rules.begin();
it!= rules.end(); ++it, loop++) {
dout(10) << " <<<<<<< Rule " << loop << " >>>>>>> " << dendl;
(*it).dump_origins();
}
}
| 5,513 | 27.42268 | 81 |
cc
|
null |
ceph-main/src/rgw/rgw_cors.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <map>
#include <string>
#include <include/types.h>
#define RGW_CORS_GET 0x1
#define RGW_CORS_PUT 0x2
#define RGW_CORS_HEAD 0x4
#define RGW_CORS_POST 0x8
#define RGW_CORS_DELETE 0x10
#define RGW_CORS_COPY 0x20
#define RGW_CORS_ALL (RGW_CORS_GET | \
RGW_CORS_PUT | \
RGW_CORS_HEAD | \
RGW_CORS_POST | \
RGW_CORS_DELETE | \
RGW_CORS_COPY)
#define CORS_MAX_AGE_INVALID ((uint32_t)-1)
class RGWCORSRule
{
protected:
uint32_t max_age;
uint8_t allowed_methods;
std::string id;
std::set<std::string> allowed_hdrs; /* If you change this, you need to discard lowercase_allowed_hdrs */
std::set<std::string> lowercase_allowed_hdrs; /* Not built until needed in RGWCORSRule::is_header_allowed */
std::set<std::string> allowed_origins;
std::list<std::string> exposable_hdrs;
public:
RGWCORSRule() : max_age(CORS_MAX_AGE_INVALID),allowed_methods(0) {}
RGWCORSRule(std::set<std::string>& o, std::set<std::string>& h,
std::list<std::string>& e, uint8_t f, uint32_t a)
:max_age(a),
allowed_methods(f),
allowed_hdrs(h),
allowed_origins(o),
exposable_hdrs(e) {}
virtual ~RGWCORSRule() {}
std::string& get_id() { return id; }
uint32_t get_max_age() { return max_age; }
uint8_t get_allowed_methods() { return allowed_methods; }
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(max_age, bl);
encode(allowed_methods, bl);
encode(id, bl);
encode(allowed_hdrs, bl);
encode(allowed_origins, bl);
encode(exposable_hdrs, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(max_age, bl);
decode(allowed_methods, bl);
decode(id, bl);
decode(allowed_hdrs, bl);
decode(allowed_origins, bl);
decode(exposable_hdrs, bl);
DECODE_FINISH(bl);
}
bool has_wildcard_origin();
bool is_origin_present(const char *o);
void format_exp_headers(std::string& s);
void erase_origin_if_present(std::string& origin, bool *rule_empty);
void dump_origins();
void dump(Formatter *f) const;
bool is_header_allowed(const char *hdr, size_t len);
};
WRITE_CLASS_ENCODER(RGWCORSRule)
class RGWCORSConfiguration
{
protected:
std::list<RGWCORSRule> rules;
public:
RGWCORSConfiguration() {}
~RGWCORSConfiguration() {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(rules, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(rules, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
std::list<RGWCORSRule>& get_rules() {
return rules;
}
bool is_empty() {
return rules.empty();
}
void get_origins_list(const char *origin, std::list<std::string>& origins);
RGWCORSRule * host_name_rule(const char *origin);
void erase_host_name_rule(std::string& origin);
void dump();
void stack_rule(RGWCORSRule& r) {
rules.push_front(r);
}
};
WRITE_CLASS_ENCODER(RGWCORSConfiguration)
static inline int validate_name_string(std::string_view o) {
if (o.length() == 0)
return -1;
if (o.find_first_of("*") != o.find_last_of("*"))
return -1;
return 0;
}
| 3,817 | 27.281481 | 110 |
h
|
null |
ceph-main/src/rgw/rgw_cors_s3.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[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 <string.h>
#include <limits.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "rgw_cors_s3.h"
#include "rgw_user.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
void RGWCORSRule_S3::to_xml(XMLFormatter& f) {
f.open_object_section("CORSRule");
/*ID if present*/
if (id.length() > 0) {
f.dump_string("ID", id);
}
/*AllowedMethods*/
if (allowed_methods & RGW_CORS_GET)
f.dump_string("AllowedMethod", "GET");
if (allowed_methods & RGW_CORS_PUT)
f.dump_string("AllowedMethod", "PUT");
if (allowed_methods & RGW_CORS_DELETE)
f.dump_string("AllowedMethod", "DELETE");
if (allowed_methods & RGW_CORS_HEAD)
f.dump_string("AllowedMethod", "HEAD");
if (allowed_methods & RGW_CORS_POST)
f.dump_string("AllowedMethod", "POST");
if (allowed_methods & RGW_CORS_COPY)
f.dump_string("AllowedMethod", "COPY");
/*AllowedOrigins*/
for(set<string>::iterator it = allowed_origins.begin();
it != allowed_origins.end();
++it) {
string host = *it;
f.dump_string("AllowedOrigin", host);
}
/*AllowedHeader*/
for(set<string>::iterator it = allowed_hdrs.begin();
it != allowed_hdrs.end(); ++it) {
f.dump_string("AllowedHeader", *it);
}
/*MaxAgeSeconds*/
if (max_age != CORS_MAX_AGE_INVALID) {
f.dump_unsigned("MaxAgeSeconds", max_age);
}
/*ExposeHeader*/
for(list<string>::iterator it = exposable_hdrs.begin();
it != exposable_hdrs.end(); ++it) {
f.dump_string("ExposeHeader", *it);
}
f.close_section();
}
bool RGWCORSRule_S3::xml_end(const char *el) {
XMLObjIter iter = find("AllowedMethod");
XMLObj *obj;
/*Check all the allowedmethods*/
obj = iter.get_next();
if (obj) {
for( ; obj; obj = iter.get_next()) {
const char *s = obj->get_data().c_str();
ldpp_dout(dpp, 10) << "RGWCORSRule::xml_end, el : " << el << ", data : " << s << dendl;
if (strcasecmp(s, "GET") == 0) {
allowed_methods |= RGW_CORS_GET;
} else if (strcasecmp(s, "POST") == 0) {
allowed_methods |= RGW_CORS_POST;
} else if (strcasecmp(s, "DELETE") == 0) {
allowed_methods |= RGW_CORS_DELETE;
} else if (strcasecmp(s, "HEAD") == 0) {
allowed_methods |= RGW_CORS_HEAD;
} else if (strcasecmp(s, "PUT") == 0) {
allowed_methods |= RGW_CORS_PUT;
} else if (strcasecmp(s, "COPY") == 0) {
allowed_methods |= RGW_CORS_COPY;
} else {
return false;
}
}
}
/*Check the id's len, it should be less than 255*/
XMLObj *xml_id = find_first("ID");
if (xml_id != NULL) {
string data = xml_id->get_data();
if (data.length() > 255) {
ldpp_dout(dpp, 0) << "RGWCORSRule has id of length greater than 255" << dendl;
return false;
}
ldpp_dout(dpp, 10) << "RGWCORRule id : " << data << dendl;
id = data;
}
/*Check if there is atleast one AllowedOrigin*/
iter = find("AllowedOrigin");
if (!(obj = iter.get_next())) {
ldpp_dout(dpp, 0) << "RGWCORSRule does not have even one AllowedOrigin" << dendl;
return false;
}
for( ; obj; obj = iter.get_next()) {
ldpp_dout(dpp, 10) << "RGWCORSRule - origin : " << obj->get_data() << dendl;
/*Just take the hostname*/
string host = obj->get_data();
if (validate_name_string(host) != 0)
return false;
allowed_origins.insert(allowed_origins.end(), host);
}
/*Check of max_age*/
iter = find("MaxAgeSeconds");
if ((obj = iter.get_next())) {
char *end = NULL;
unsigned long long ull = strtoull(obj->get_data().c_str(), &end, 10);
if (*end != '\0') {
ldpp_dout(dpp, 0) << "RGWCORSRule's MaxAgeSeconds " << obj->get_data() << " is an invalid integer" << dendl;
return false;
}
if (ull >= 0x100000000ull) {
max_age = CORS_MAX_AGE_INVALID;
} else {
max_age = (uint32_t)ull;
}
ldpp_dout(dpp, 10) << "RGWCORSRule : max_age : " << max_age << dendl;
}
/*Check and update ExposeHeader*/
iter = find("ExposeHeader");
if ((obj = iter.get_next())) {
for(; obj; obj = iter.get_next()) {
ldpp_dout(dpp, 10) << "RGWCORSRule - exp_hdr : " << obj->get_data() << dendl;
exposable_hdrs.push_back(obj->get_data());
}
}
/*Check and update AllowedHeader*/
iter = find("AllowedHeader");
if ((obj = iter.get_next())) {
for(; obj; obj = iter.get_next()) {
ldpp_dout(dpp, 10) << "RGWCORSRule - allowed_hdr : " << obj->get_data() << dendl;
string s = obj->get_data();
if (validate_name_string(s) != 0)
return false;
allowed_hdrs.insert(allowed_hdrs.end(), s);
}
}
return true;
}
void RGWCORSConfiguration_S3::to_xml(ostream& out) {
XMLFormatter f;
f.open_object_section_in_ns("CORSConfiguration", XMLNS_AWS_S3);
for(list<RGWCORSRule>::iterator it = rules.begin();
it != rules.end(); ++it) {
(static_cast<RGWCORSRule_S3 &>(*it)).to_xml(f);
}
f.close_section();
f.flush(out);
}
bool RGWCORSConfiguration_S3::xml_end(const char *el) {
XMLObjIter iter = find("CORSRule");
RGWCORSRule_S3 *obj;
if (!(obj = static_cast<RGWCORSRule_S3 *>(iter.get_next()))) {
ldpp_dout(dpp, 0) << "CORSConfiguration should have atleast one CORSRule" << dendl;
return false;
}
for(; obj; obj = static_cast<RGWCORSRule_S3 *>(iter.get_next())) {
rules.push_back(*obj);
}
return true;
}
class CORSRuleID_S3 : public XMLObj {
public:
CORSRuleID_S3() {}
~CORSRuleID_S3() override {}
};
class CORSRuleAllowedOrigin_S3 : public XMLObj {
public:
CORSRuleAllowedOrigin_S3() {}
~CORSRuleAllowedOrigin_S3() override {}
};
class CORSRuleAllowedMethod_S3 : public XMLObj {
public:
CORSRuleAllowedMethod_S3() {}
~CORSRuleAllowedMethod_S3() override {}
};
class CORSRuleAllowedHeader_S3 : public XMLObj {
public:
CORSRuleAllowedHeader_S3() {}
~CORSRuleAllowedHeader_S3() override {}
};
class CORSRuleMaxAgeSeconds_S3 : public XMLObj {
public:
CORSRuleMaxAgeSeconds_S3() {}
~CORSRuleMaxAgeSeconds_S3() override {}
};
class CORSRuleExposeHeader_S3 : public XMLObj {
public:
CORSRuleExposeHeader_S3() {}
~CORSRuleExposeHeader_S3() override {}
};
XMLObj *RGWCORSXMLParser_S3::alloc_obj(const char *el) {
if (strcmp(el, "CORSConfiguration") == 0) {
return new RGWCORSConfiguration_S3(dpp);
} else if (strcmp(el, "CORSRule") == 0) {
return new RGWCORSRule_S3(dpp);
} else if (strcmp(el, "ID") == 0) {
return new CORSRuleID_S3;
} else if (strcmp(el, "AllowedOrigin") == 0) {
return new CORSRuleAllowedOrigin_S3;
} else if (strcmp(el, "AllowedMethod") == 0) {
return new CORSRuleAllowedMethod_S3;
} else if (strcmp(el, "AllowedHeader") == 0) {
return new CORSRuleAllowedHeader_S3;
} else if (strcmp(el, "MaxAgeSeconds") == 0) {
return new CORSRuleMaxAgeSeconds_S3;
} else if (strcmp(el, "ExposeHeader") == 0) {
return new CORSRuleExposeHeader_S3;
}
return NULL;
}
| 7,425 | 29.064777 | 114 |
cc
|
null |
ceph-main/src/rgw/rgw_cors_s3.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <map>
#include <string>
#include <iosfwd>
#include <include/types.h>
#include <common/Formatter.h>
#include <common/dout.h>
#include "rgw_xml.h"
#include "rgw_cors.h"
class RGWCORSRule_S3 : public RGWCORSRule, public XMLObj
{
const DoutPrefixProvider *dpp;
public:
RGWCORSRule_S3(const DoutPrefixProvider *dpp) : dpp(dpp) {}
~RGWCORSRule_S3() override {}
bool xml_end(const char *el) override;
void to_xml(XMLFormatter& f);
};
class RGWCORSConfiguration_S3 : public RGWCORSConfiguration, public XMLObj
{
const DoutPrefixProvider *dpp;
public:
RGWCORSConfiguration_S3(const DoutPrefixProvider *dpp) : dpp(dpp) {}
~RGWCORSConfiguration_S3() override {}
bool xml_end(const char *el) override;
void to_xml(std::ostream& out);
};
class RGWCORSXMLParser_S3 : public RGWXMLParser
{
const DoutPrefixProvider *dpp;
CephContext *cct;
XMLObj *alloc_obj(const char *el) override;
public:
explicit RGWCORSXMLParser_S3(const DoutPrefixProvider *_dpp, CephContext *_cct) : dpp(_dpp), cct(_cct) {}
};
| 1,504 | 24.508475 | 107 |
h
|
null |
ceph-main/src/rgw/rgw_cors_swift.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <map>
#include <string>
#include <vector>
#include <include/types.h>
#include <include/str_list.h>
#include "rgw_cors.h"
class RGWCORSConfiguration_SWIFT : public RGWCORSConfiguration
{
public:
RGWCORSConfiguration_SWIFT() {}
~RGWCORSConfiguration_SWIFT() {}
int create_update(const char *allow_origins, const char *allow_headers,
const char *expose_headers, const char *max_age) {
std::set<std::string> o, h;
std::list<std::string> e;
unsigned long a = CORS_MAX_AGE_INVALID;
uint8_t flags = RGW_CORS_ALL;
int nr_invalid_names = 0;
auto add_host = [&nr_invalid_names, &o] (auto host) {
if (validate_name_string(host) == 0) {
o.emplace(std::string{host});
} else {
nr_invalid_names++;
}
};
for_each_substr(allow_origins, ";,= \t", add_host);
if (o.empty() || nr_invalid_names > 0) {
return -EINVAL;
}
if (allow_headers) {
int nr_invalid_headers = 0;
auto add_header = [&nr_invalid_headers, &h] (auto allow_header) {
if (validate_name_string(allow_header) == 0) {
h.emplace(std::string{allow_header});
} else {
nr_invalid_headers++;
}
};
for_each_substr(allow_headers, ";,= \t", add_header);
if (h.empty() || nr_invalid_headers > 0) {
return -EINVAL;
}
}
if (expose_headers) {
for_each_substr(expose_headers, ";,= \t",
[&e] (auto expose_header) {
e.emplace_back(std::string(expose_header));
});
}
if (max_age) {
char *end = NULL;
a = strtoul(max_age, &end, 10);
if (a == ULONG_MAX)
a = CORS_MAX_AGE_INVALID;
}
RGWCORSRule rule(o, h, e, flags, a);
stack_rule(rule);
return 0;
}
};
| 2,339 | 26.857143 | 76 |
h
|
null |
ceph-main/src/rgw/rgw_cr_rest.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_cr_rest.h"
#include "rgw_coroutine.h"
// re-include our assert to clobber the system one; fix dout:
#include "include/ceph_assert.h"
#include <boost/asio/yield.hpp>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
RGWCRHTTPGetDataCB::RGWCRHTTPGetDataCB(RGWCoroutinesEnv *_env, RGWCoroutine *_cr, RGWHTTPStreamRWRequest *_req) : env(_env), cr(_cr), req(_req) {
io_id = req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_READ |RGWHTTPClient::HTTPCLIENT_IO_CONTROL);
req->set_in_cb(this);
}
#define GET_DATA_WINDOW_SIZE 2 * 1024 * 1024
int RGWCRHTTPGetDataCB::handle_data(bufferlist& bl, bool *pause) {
if (data.length() < GET_DATA_WINDOW_SIZE / 2) {
notified = false;
}
{
uint64_t bl_len = bl.length();
std::lock_guard l{lock};
if (!got_all_extra_data) {
uint64_t max = extra_data_len - extra_data.length();
if (max > bl_len) {
max = bl_len;
}
bl.splice(0, max, &extra_data);
bl_len -= max;
got_all_extra_data = extra_data.length() == extra_data_len;
}
data.append(bl);
}
uint64_t data_len = data.length();
if (data_len >= GET_DATA_WINDOW_SIZE && !notified) {
notified = true;
env->manager->io_complete(cr, io_id);
}
if (data_len >= 2 * GET_DATA_WINDOW_SIZE) {
*pause = true;
paused = true;
}
return 0;
}
void RGWCRHTTPGetDataCB::claim_data(bufferlist *dest, uint64_t max) {
bool need_to_unpause = false;
{
std::lock_guard l{lock};
if (data.length() == 0) {
return;
}
if (data.length() < max) {
max = data.length();
}
data.splice(0, max, dest);
need_to_unpause = (paused && data.length() <= GET_DATA_WINDOW_SIZE);
}
if (need_to_unpause) {
req->unpause_receive();
}
}
RGWStreamReadHTTPResourceCRF::~RGWStreamReadHTTPResourceCRF()
{
if (req) {
req->cancel();
req->wait(null_yield);
delete req;
}
}
int RGWStreamReadHTTPResourceCRF::init(const DoutPrefixProvider *dpp)
{
env->stack->init_new_io(req);
in_cb.emplace(env, caller, req);
int r = req->send(http_manager);
if (r < 0) {
return r;
}
return 0;
}
int RGWStreamWriteHTTPResourceCRF::send()
{
env->stack->init_new_io(req);
req->set_write_drain_cb(&write_drain_notify_cb);
int r = req->send(http_manager);
if (r < 0) {
return r;
}
return 0;
}
bool RGWStreamReadHTTPResourceCRF::has_attrs()
{
return got_attrs;
}
void RGWStreamReadHTTPResourceCRF::get_attrs(std::map<string, string> *attrs)
{
req->get_out_headers(attrs);
}
int RGWStreamReadHTTPResourceCRF::decode_rest_obj(const DoutPrefixProvider *dpp, map<string, string>& headers, bufferlist& extra_data) {
/* basic generic implementation */
for (auto header : headers) {
const string& val = header.second;
rest_obj.attrs[header.first] = val;
}
return 0;
}
int RGWStreamReadHTTPResourceCRF::read(const DoutPrefixProvider *dpp, bufferlist *out, uint64_t max_size, bool *io_pending)
{
reenter(&read_state) {
io_read_mask = req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_READ | RGWHTTPClient::HTTPCLIENT_IO_CONTROL);
while (!req->is_done() ||
in_cb->has_data()) {
*io_pending = true;
if (!in_cb->has_data()) {
yield caller->io_block(0, io_read_mask);
}
got_attrs = true;
if (need_extra_data() && !got_extra_data) {
if (!in_cb->has_all_extra_data()) {
continue;
}
extra_data.claim_append(in_cb->get_extra_data());
map<string, string> attrs;
req->get_out_headers(&attrs);
int ret = decode_rest_obj(dpp, attrs, extra_data);
if (ret < 0) {
ldout(cct, 0) << "ERROR: " << __func__ << " decode_rest_obj() returned ret=" << ret << dendl;
return ret;
}
got_extra_data = true;
}
*io_pending = false;
in_cb->claim_data(out, max_size);
if (out->length() == 0) {
/* this may happen if we just read the prepended extra_data and didn't have any data
* after. In that case, retry reading, so that caller doesn't assume it's EOF.
*/
continue;
}
if (!req->is_done() || out->length() >= max_size) {
yield;
}
}
}
return 0;
}
bool RGWStreamReadHTTPResourceCRF::is_done()
{
return req->is_done();
}
RGWStreamWriteHTTPResourceCRF::~RGWStreamWriteHTTPResourceCRF()
{
if (req) {
req->cancel();
req->wait(null_yield);
delete req;
}
}
void RGWStreamWriteHTTPResourceCRF::send_ready(const DoutPrefixProvider *dpp, const rgw_rest_obj& rest_obj)
{
req->set_send_length(rest_obj.content_len);
for (auto h : rest_obj.attrs) {
req->append_header(h.first, h.second);
}
}
#define PENDING_WRITES_WINDOW (1 * 1024 * 1024)
void RGWStreamWriteHTTPResourceCRF::write_drain_notify(uint64_t pending_size)
{
lock_guard l(blocked_lock);
if (is_blocked && (pending_size < PENDING_WRITES_WINDOW / 2)) {
env->manager->io_complete(caller, req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_WRITE | RGWHTTPClient::HTTPCLIENT_IO_CONTROL));
is_blocked = false;
}
}
void RGWStreamWriteHTTPResourceCRF::WriteDrainNotify::notify(uint64_t pending_size)
{
crf->write_drain_notify(pending_size);
}
int RGWStreamWriteHTTPResourceCRF::write(bufferlist& data, bool *io_pending)
{
reenter(&write_state) {
while (!req->is_done()) {
*io_pending = false;
if (req->get_pending_send_size() >= PENDING_WRITES_WINDOW) {
*io_pending = true;
{
lock_guard l(blocked_lock);
is_blocked = true;
/* it's ok to unlock here, even if io_complete() arrives before io_block(), it'll wakeup
* correctly */
}
yield caller->io_block(0, req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_WRITE | RGWHTTPClient::HTTPCLIENT_IO_CONTROL));
}
yield req->add_send_data(data);
}
return req->get_status();
}
return 0;
}
int RGWStreamWriteHTTPResourceCRF::drain_writes(bool *need_retry)
{
reenter(&drain_state) {
*need_retry = true;
yield req->finish_write();
*need_retry = !req->is_done();
while (!req->is_done()) {
yield caller->io_block(0, req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_CONTROL));
*need_retry = !req->is_done();
}
map<string, string> headers;
req->get_out_headers(&headers);
handle_headers(headers);
return req->get_req_retcode();
}
return 0;
}
RGWStreamSpliceCR::RGWStreamSpliceCR(CephContext *_cct, RGWHTTPManager *_mgr,
shared_ptr<RGWStreamReadHTTPResourceCRF>& _in_crf,
shared_ptr<RGWStreamWriteHTTPResourceCRF>& _out_crf) : RGWCoroutine(_cct), cct(_cct), http_manager(_mgr),
in_crf(_in_crf), out_crf(_out_crf) {}
RGWStreamSpliceCR::~RGWStreamSpliceCR() { }
int RGWStreamSpliceCR::operate(const DoutPrefixProvider *dpp) {
reenter(this) {
{
int ret = in_crf->init(dpp);
if (ret < 0) {
return set_cr_error(ret);
}
}
do {
bl.clear();
do {
yield {
ret = in_crf->read(dpp, &bl, 4 * 1024 * 1024, &need_retry);
if (ret < 0) {
return set_cr_error(ret);
}
}
if (retcode < 0) {
ldout(cct, 20) << __func__ << ": in_crf->read() retcode=" << retcode << dendl;
return set_cr_error(ret);
}
} while (need_retry);
ldout(cct, 20) << "read " << bl.length() << " bytes" << dendl;
if (!in_crf->has_attrs()) {
assert (bl.length() == 0);
continue;
}
if (!sent_attrs) {
int ret = out_crf->init();
if (ret < 0) {
return set_cr_error(ret);
}
out_crf->send_ready(dpp, in_crf->get_rest_obj());
ret = out_crf->send();
if (ret < 0) {
return set_cr_error(ret);
}
sent_attrs = true;
}
if (bl.length() == 0 && in_crf->is_done()) {
break;
}
total_read += bl.length();
do {
yield {
ldout(cct, 20) << "writing " << bl.length() << " bytes" << dendl;
ret = out_crf->write(bl, &need_retry);
if (ret < 0) {
return set_cr_error(ret);
}
}
if (retcode < 0) {
ldout(cct, 20) << __func__ << ": out_crf->write() retcode=" << retcode << dendl;
return set_cr_error(ret);
}
} while (need_retry);
} while (true);
do {
yield {
int ret = out_crf->drain_writes(&need_retry);
if (ret < 0) {
return set_cr_error(ret);
}
}
} while (need_retry);
return set_cr_done();
}
return 0;
}
| 8,860 | 24.173295 | 145 |
cc
|
null |
ceph-main/src/rgw/rgw_cr_rest.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <boost/intrusive_ptr.hpp>
#include <mutex>
#include "include/ceph_assert.h" // boost header clobbers our assert.h
#include "rgw_coroutine.h"
#include "rgw_rest_conn.h"
struct rgw_rest_obj {
rgw_obj_key key;
uint64_t content_len;
std::map<std::string, std::string> attrs;
std::map<std::string, std::string> custom_attrs;
RGWAccessControlPolicy acls;
void init(const rgw_obj_key& _key) {
key = _key;
}
};
class RGWReadRawRESTResourceCR : public RGWSimpleCoroutine {
bufferlist *result;
protected:
RGWRESTConn *conn;
RGWHTTPManager *http_manager;
std::string path;
param_vec_t params;
param_vec_t extra_headers;
public:
boost::intrusive_ptr<RGWRESTReadResource> http_op;
RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager, const std::string& _path,
rgw_http_param_pair *params, bufferlist *_result)
: RGWSimpleCoroutine(_cct), result(_result), conn(_conn), http_manager(_http_manager),
path(_path), params(make_param_list(params))
{}
RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager, const std::string& _path,
rgw_http_param_pair *params)
: RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager),
path(_path), params(make_param_list(params))
{}
RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager, const std::string& _path,
rgw_http_param_pair *params, param_vec_t &hdrs)
: RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager),
path(_path), params(make_param_list(params)),
extra_headers(hdrs)
{}
RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager, const std::string& _path,
rgw_http_param_pair *params,
std::map <std::string, std::string> *hdrs)
: RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager),
path(_path), params(make_param_list(params)),
extra_headers(make_param_list(hdrs))
{}
~RGWReadRawRESTResourceCR() override {
request_cleanup();
}
int send_request(const DoutPrefixProvider *dpp) override {
auto op = boost::intrusive_ptr<RGWRESTReadResource>(
new RGWRESTReadResource(conn, path, params, &extra_headers, http_manager));
init_new_io(op.get());
int ret = op->aio_read(dpp);
if (ret < 0) {
log_error() << "failed to send http operation: " << op->to_str()
<< " ret=" << ret << std::endl;
op->put();
return ret;
}
std::swap(http_op, op); // store reference in http_op on success
return 0;
}
virtual int wait_result() {
return http_op->wait(result, null_yield);
}
int request_complete() override {
int ret;
ret = wait_result();
auto op = std::move(http_op); // release ref on return
if (ret < 0) {
error_stream << "http operation failed: " << op->to_str()
<< " status=" << op->get_http_status() << std::endl;
op->put();
return ret;
}
op->put();
return 0;
}
void request_cleanup() override {
if (http_op) {
http_op->put();
http_op = NULL;
}
}
};
template <class T>
class RGWReadRESTResourceCR : public RGWReadRawRESTResourceCR {
T *result;
public:
RGWReadRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager, const std::string& _path,
rgw_http_param_pair *params, T *_result)
: RGWReadRawRESTResourceCR(_cct, _conn, _http_manager, _path, params), result(_result)
{}
RGWReadRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager, const std::string& _path,
rgw_http_param_pair *params,
std::map <std::string, std::string> *hdrs,
T *_result)
: RGWReadRawRESTResourceCR(_cct, _conn, _http_manager, _path, params, hdrs), result(_result)
{}
int wait_result() override {
return http_op->wait(result, null_yield);
}
};
template <class T, class E = int>
class RGWSendRawRESTResourceCR: public RGWSimpleCoroutine {
protected:
RGWRESTConn *conn;
RGWHTTPManager *http_manager;
std::string method;
std::string path;
param_vec_t params;
param_vec_t headers;
std::map<std::string, std::string> *attrs;
T *result;
E *err_result;
bufferlist input_bl;
bool send_content_length=false;
boost::intrusive_ptr<RGWRESTSendResource> http_op;
public:
RGWSendRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _method, const std::string& _path,
rgw_http_param_pair *_params,
std::map<std::string, std::string> *_attrs,
bufferlist& _input, T *_result,
bool _send_content_length,
E *_err_result = nullptr)
: RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager),
method(_method), path(_path), params(make_param_list(_params)),
headers(make_param_list(_attrs)), attrs(_attrs),
result(_result), err_result(_err_result),
input_bl(_input), send_content_length(_send_content_length) {}
RGWSendRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _method, const std::string& _path,
rgw_http_param_pair *_params, std::map<std::string, std::string> *_attrs,
T *_result, E *_err_result = nullptr)
: RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager),
method(_method), path(_path), params(make_param_list(_params)), headers(make_param_list(_attrs)), attrs(_attrs), result(_result),
err_result(_err_result) {}
~RGWSendRawRESTResourceCR() override {
request_cleanup();
}
int send_request(const DoutPrefixProvider *dpp) override {
auto op = boost::intrusive_ptr<RGWRESTSendResource>(
new RGWRESTSendResource(conn, method, path, params, &headers, http_manager));
init_new_io(op.get());
int ret = op->aio_send(dpp, input_bl);
if (ret < 0) {
ldpp_subdout(dpp, rgw, 0) << "ERROR: failed to send request" << dendl;
op->put();
return ret;
}
std::swap(http_op, op); // store reference in http_op on success
return 0;
}
int request_complete() override {
int ret;
if (result || err_result) {
ret = http_op->wait(result, null_yield, err_result);
} else {
bufferlist bl;
ret = http_op->wait(&bl, null_yield);
}
auto op = std::move(http_op); // release ref on return
if (ret < 0) {
error_stream << "http operation failed: " << op->to_str()
<< " status=" << op->get_http_status() << std::endl;
lsubdout(cct, rgw, 5) << "failed to wait for op, ret=" << ret
<< ": " << op->to_str() << dendl;
op->put();
return ret;
}
op->put();
return 0;
}
void request_cleanup() override {
if (http_op) {
http_op->put();
http_op = NULL;
}
}
};
template <class S, class T, class E = int>
class RGWSendRESTResourceCR : public RGWSendRawRESTResourceCR<T, E> {
public:
RGWSendRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _method, const std::string& _path,
rgw_http_param_pair *_params, std::map<std::string, std::string> *_attrs,
S& _input, T *_result, E *_err_result = nullptr)
: RGWSendRawRESTResourceCR<T, E>(_cct, _conn, _http_manager, _method, _path, _params, _attrs, _result, _err_result) {
JSONFormatter jf;
encode_json("data", _input, &jf);
std::stringstream ss;
jf.flush(ss);
//bufferlist bl;
this->input_bl.append(ss.str());
}
};
template <class S, class T, class E = int>
class RGWPostRESTResourceCR : public RGWSendRESTResourceCR<S, T, E> {
public:
RGWPostRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _path,
rgw_http_param_pair *_params, S& _input,
T *_result, E *_err_result = nullptr)
: RGWSendRESTResourceCR<S, T, E>(_cct, _conn, _http_manager,
"POST", _path,
_params, nullptr, _input,
_result, _err_result) {}
};
template <class T, class E = int>
class RGWPutRawRESTResourceCR: public RGWSendRawRESTResourceCR <T, E> {
public:
RGWPutRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _path,
rgw_http_param_pair *_params, bufferlist& _input,
T *_result, E *_err_result = nullptr)
: RGWSendRawRESTResourceCR<T, E>(_cct, _conn, _http_manager, "PUT", _path,
_params, nullptr, _input, _result, true, _err_result) {}
};
template <class T, class E = int>
class RGWPostRawRESTResourceCR: public RGWSendRawRESTResourceCR <T, E> {
public:
RGWPostRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _path,
rgw_http_param_pair *_params,
std::map<std::string, std::string> * _attrs,
bufferlist& _input,
T *_result, E *_err_result = nullptr)
: RGWSendRawRESTResourceCR<T, E>(_cct, _conn, _http_manager, "POST", _path,
_params, _attrs, _input, _result, true, _err_result) {}
};
template <class S, class T, class E = int>
class RGWPutRESTResourceCR : public RGWSendRESTResourceCR<S, T, E> {
public:
RGWPutRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _path,
rgw_http_param_pair *_params, S& _input,
T *_result, E *_err_result = nullptr)
: RGWSendRESTResourceCR<S, T, E>(_cct, _conn, _http_manager,
"PUT", _path,
_params, nullptr, _input,
_result, _err_result) {}
RGWPutRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _path,
rgw_http_param_pair *_params,
std::map<std::string, std::string> *_attrs,
S& _input, T *_result, E *_err_result = nullptr)
: RGWSendRESTResourceCR<S, T, E>(_cct, _conn, _http_manager,
"PUT", _path,
_params, _attrs, _input,
_result, _err_result) {}
};
class RGWDeleteRESTResourceCR : public RGWSimpleCoroutine {
RGWRESTConn *conn;
RGWHTTPManager *http_manager;
std::string path;
param_vec_t params;
boost::intrusive_ptr<RGWRESTDeleteResource> http_op;
public:
RGWDeleteRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn,
RGWHTTPManager *_http_manager,
const std::string& _path,
rgw_http_param_pair *_params)
: RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager),
path(_path), params(make_param_list(_params))
{}
~RGWDeleteRESTResourceCR() override {
request_cleanup();
}
int send_request(const DoutPrefixProvider *dpp) override {
auto op = boost::intrusive_ptr<RGWRESTDeleteResource>(
new RGWRESTDeleteResource(conn, path, params, nullptr, http_manager));
init_new_io(op.get());
bufferlist bl;
int ret = op->aio_send(dpp, bl);
if (ret < 0) {
ldpp_subdout(dpp, rgw, 0) << "ERROR: failed to send DELETE request" << dendl;
op->put();
return ret;
}
std::swap(http_op, op); // store reference in http_op on success
return 0;
}
int request_complete() override {
int ret;
bufferlist bl;
ret = http_op->wait(&bl, null_yield);
auto op = std::move(http_op); // release ref on return
if (ret < 0) {
error_stream << "http operation failed: " << op->to_str()
<< " status=" << op->get_http_status() << std::endl;
lsubdout(cct, rgw, 5) << "failed to wait for op, ret=" << ret
<< ": " << op->to_str() << dendl;
op->put();
return ret;
}
op->put();
return 0;
}
void request_cleanup() override {
if (http_op) {
http_op->put();
http_op = NULL;
}
}
};
class RGWCRHTTPGetDataCB : public RGWHTTPStreamRWRequest::ReceiveCB {
ceph::mutex lock = ceph::make_mutex("RGWCRHTTPGetDataCB");
RGWCoroutinesEnv *env;
RGWCoroutine *cr;
RGWHTTPStreamRWRequest *req;
rgw_io_id io_id;
bufferlist data;
bufferlist extra_data;
bool got_all_extra_data{false};
bool paused{false};
bool notified{false};
public:
RGWCRHTTPGetDataCB(RGWCoroutinesEnv *_env, RGWCoroutine *_cr, RGWHTTPStreamRWRequest *_req);
int handle_data(bufferlist& bl, bool *pause) override;
void claim_data(bufferlist *dest, uint64_t max);
bufferlist& get_extra_data() {
return extra_data;
}
bool has_data() {
return (data.length() > 0);
}
bool has_all_extra_data() {
return got_all_extra_data;
}
};
class RGWStreamReadResourceCRF {
protected:
boost::asio::coroutine read_state;
public:
virtual int init(const DoutPrefixProvider *dpp) = 0;
virtual int read(const DoutPrefixProvider *dpp, bufferlist *data, uint64_t max, bool *need_retry) = 0; /* reentrant */
virtual int decode_rest_obj(const DoutPrefixProvider *dpp, std::map<std::string, std::string>& headers, bufferlist& extra_data) = 0;
virtual bool has_attrs() = 0;
virtual void get_attrs(std::map<std::string, std::string> *attrs) = 0;
virtual ~RGWStreamReadResourceCRF() = default;
};
class RGWStreamWriteResourceCRF {
protected:
boost::asio::coroutine write_state;
boost::asio::coroutine drain_state;
public:
virtual int init() = 0;
virtual void send_ready(const DoutPrefixProvider *dpp, const rgw_rest_obj& rest_obj) = 0;
virtual int send() = 0;
virtual int write(bufferlist& data, bool *need_retry) = 0; /* reentrant */
virtual int drain_writes(bool *need_retry) = 0; /* reentrant */
virtual ~RGWStreamWriteResourceCRF() = default;
};
class RGWStreamReadHTTPResourceCRF : public RGWStreamReadResourceCRF {
CephContext *cct;
RGWCoroutinesEnv *env;
RGWCoroutine *caller;
RGWHTTPManager *http_manager;
RGWHTTPStreamRWRequest *req{nullptr};
std::optional<RGWCRHTTPGetDataCB> in_cb;
bufferlist extra_data;
bool got_attrs{false};
bool got_extra_data{false};
rgw_io_id io_read_mask;
protected:
rgw_rest_obj rest_obj;
struct range_info {
bool is_set{false};
uint64_t ofs;
uint64_t size;
} range;
ceph::real_time mtime;
std::string etag;
public:
RGWStreamReadHTTPResourceCRF(CephContext *_cct,
RGWCoroutinesEnv *_env,
RGWCoroutine *_caller,
RGWHTTPManager *_http_manager,
const rgw_obj_key& _src_key) : cct(_cct),
env(_env),
caller(_caller),
http_manager(_http_manager) {
rest_obj.init(_src_key);
}
~RGWStreamReadHTTPResourceCRF();
int init(const DoutPrefixProvider *dpp) override;
int read(const DoutPrefixProvider *dpp, bufferlist *data, uint64_t max, bool *need_retry) override; /* reentrant */
int decode_rest_obj(const DoutPrefixProvider *dpp, std::map<std::string, std::string>& headers, bufferlist& extra_data) override;
bool has_attrs() override;
void get_attrs(std::map<std::string, std::string> *attrs) override;
bool is_done();
virtual bool need_extra_data() { return false; }
void set_req(RGWHTTPStreamRWRequest *r) {
req = r;
}
rgw_rest_obj& get_rest_obj() {
return rest_obj;
}
void set_range(uint64_t ofs, uint64_t size) {
range.is_set = true;
range.ofs = ofs;
range.size = size;
}
};
class RGWStreamWriteHTTPResourceCRF : public RGWStreamWriteResourceCRF {
protected:
RGWCoroutinesEnv *env;
RGWCoroutine *caller;
RGWHTTPManager *http_manager;
using lock_guard = std::lock_guard<std::mutex>;
std::mutex blocked_lock;
bool is_blocked;
RGWHTTPStreamRWRequest *req{nullptr};
struct multipart_info {
bool is_multipart{false};
std::string upload_id;
int part_num{0};
uint64_t part_size;
} multipart;
class WriteDrainNotify : public RGWWriteDrainCB {
RGWStreamWriteHTTPResourceCRF *crf;
public:
explicit WriteDrainNotify(RGWStreamWriteHTTPResourceCRF *_crf) : crf(_crf) {}
void notify(uint64_t pending_size) override;
} write_drain_notify_cb;
public:
RGWStreamWriteHTTPResourceCRF(CephContext *_cct,
RGWCoroutinesEnv *_env,
RGWCoroutine *_caller,
RGWHTTPManager *_http_manager) : env(_env),
caller(_caller),
http_manager(_http_manager),
write_drain_notify_cb(this) {}
virtual ~RGWStreamWriteHTTPResourceCRF();
int init() override {
return 0;
}
void send_ready(const DoutPrefixProvider *dpp, const rgw_rest_obj& rest_obj) override;
int send() override;
int write(bufferlist& data, bool *need_retry) override; /* reentrant */
void write_drain_notify(uint64_t pending_size);
int drain_writes(bool *need_retry) override; /* reentrant */
virtual void handle_headers(const std::map<std::string, std::string>& headers) {}
void set_req(RGWHTTPStreamRWRequest *r) {
req = r;
}
void set_multipart(const std::string& upload_id, int part_num, uint64_t part_size) {
multipart.is_multipart = true;
multipart.upload_id = upload_id;
multipart.part_num = part_num;
multipart.part_size = part_size;
}
};
class RGWStreamSpliceCR : public RGWCoroutine {
CephContext *cct;
RGWHTTPManager *http_manager;
std::string url;
std::shared_ptr<RGWStreamReadHTTPResourceCRF> in_crf;
std::shared_ptr<RGWStreamWriteHTTPResourceCRF> out_crf;
bufferlist bl;
bool need_retry{false};
bool sent_attrs{false};
uint64_t total_read{0};
int ret{0};
public:
RGWStreamSpliceCR(CephContext *_cct, RGWHTTPManager *_mgr,
std::shared_ptr<RGWStreamReadHTTPResourceCRF>& _in_crf,
std::shared_ptr<RGWStreamWriteHTTPResourceCRF>& _out_crf);
~RGWStreamSpliceCR();
int operate(const DoutPrefixProvider *dpp) override;
};
| 19,624 | 32.20643 | 134 |
h
|
null |
ceph-main/src/rgw/rgw_crypt.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/**
* Crypto filters for Put/Post/Get operations.
*/
#include <string_view>
#include <rgw/rgw_op.h>
#include <rgw/rgw_crypt.h>
#include <auth/Crypto.h>
#include <rgw/rgw_b64.h>
#include <rgw/rgw_rest_s3.h>
#include "include/ceph_assert.h"
#include "crypto/crypto_accel.h"
#include "crypto/crypto_plugin.h"
#include "rgw/rgw_kms.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/error/error.h"
#include "rapidjson/error/en.h"
#include <unicode/normalizer2.h> // libicu
#include <openssl/evp.h>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
using namespace rgw;
template<typename M>
class canonical_char_sorter {
private:
const DoutPrefixProvider *dpp;
const icu::Normalizer2* normalizer;
CephContext *cct;
public:
canonical_char_sorter(const DoutPrefixProvider *dpp, CephContext *cct) : dpp(dpp), cct(cct) {
UErrorCode status = U_ZERO_ERROR;
normalizer = icu::Normalizer2::getNFCInstance(status);
if (U_FAILURE(status)) {
ldpp_dout(this->dpp, -1) << "ERROR: can't get nfc instance, error = " << status << dendl;
normalizer = 0;
}
}
bool compare_helper (const M *, const M *);
bool make_string_canonical(rapidjson::Value &,
rapidjson::Document::AllocatorType&);
};
template<typename M>
bool
canonical_char_sorter<M>::compare_helper (const M*a, const M*b)
{
UErrorCode status = U_ZERO_ERROR;
const std::string as{a->name.GetString(), a->name.GetStringLength()},
bs{b->name.GetString(), b->name.GetStringLength()};
icu::UnicodeString aw{icu::UnicodeString::fromUTF8(as)}, bw{icu::UnicodeString::fromUTF8(bs)};
int32_t afl{ aw.countChar32()}, bfl{bw.countChar32()};
std::u32string af, bf;
af.resize(afl); bf.resize(bfl);
auto *astr{af.c_str()}, *bstr{bf.c_str()};
aw.toUTF32((int32_t*)astr, afl, status);
bw.toUTF32((int32_t*)bstr, bfl, status);
bool r{af < bf};
return r;
}
template<typename M>
bool
canonical_char_sorter<M>::make_string_canonical (rapidjson::Value &v, rapidjson::Document::AllocatorType&a)
{
UErrorCode status = U_ZERO_ERROR;
const std::string as{v.GetString(), v.GetStringLength()};
if (!normalizer)
return false;
const icu::UnicodeString aw{icu::UnicodeString::fromUTF8(as)};
icu::UnicodeString an{normalizer->normalize(aw, status)};
if (U_FAILURE(status)) {
ldpp_dout(this->dpp, 5) << "conversion error; code=" << status <<
" on string " << as << dendl;
return false;
}
std::string ans;
an.toUTF8String(ans);
v.SetString(ans.c_str(), ans.length(), a);
return true;
}
typedef
rapidjson::GenericMember<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<> >
MyMember;
template<typename H>
bool
sort_and_write(rapidjson::Value &d, H &writer, canonical_char_sorter<MyMember>& ccs)
{
bool r;
switch(d.GetType()) {
case rapidjson::kObjectType: {
struct comparer {
canonical_char_sorter<MyMember> &r;
comparer(canonical_char_sorter<MyMember> &r) : r(r) {};
bool operator()(const MyMember*a, const MyMember*b) {
return r.compare_helper(a,b);
}
} cmp_functor{ccs};
if (!(r = writer.StartObject()))
break;
std::vector<MyMember*> q;
for (auto &m: d.GetObject())
q.push_back(&m);
std::sort(q.begin(), q.end(), cmp_functor);
for (auto m: q) {
assert(m->name.IsString());
if (!(r = writer.Key(m->name.GetString(), m->name.GetStringLength())))
goto Done;
if (!(r = sort_and_write(m->value, writer, ccs)))
goto Done;
}
r = writer.EndObject();
break; }
case rapidjson::kArrayType:
if (!(r = writer.StartArray()))
break;
for (auto &v: d.GetArray()) {
if (!(r = sort_and_write(v, writer, ccs)))
goto Done;
}
r = writer.EndArray();
break;
default:
r = d.Accept(writer);
break;
}
Done:
return r;
}
enum struct mec_option {
empty = 0, number_ok = 1
};
enum struct mec_error {
success = 0, conversion, number
};
mec_error
make_everything_canonical(rapidjson::Value &d, rapidjson::Document::AllocatorType&a, canonical_char_sorter<MyMember>& ccs, mec_option f = mec_option::empty )
{
mec_error r;
switch(d.GetType()) {
case rapidjson::kObjectType:
for (auto &m: d.GetObject()) {
assert(m.name.IsString());
if (!ccs.make_string_canonical(m.name, a)) {
r = mec_error::conversion;
goto Error;
}
if ((r = make_everything_canonical(m.value, a, ccs, f)) != mec_error::success)
goto Error;
}
break;
case rapidjson::kArrayType:
for (auto &v: d.GetArray()) {
if ((r = make_everything_canonical(v, a, ccs, f)) != mec_error::success)
goto Error;
}
break;
case rapidjson::kStringType:
if (!ccs.make_string_canonical(d, a)) {
r = mec_error::conversion;
goto Error;
}
break;
case rapidjson::kNumberType:
if (static_cast<int>(f) & static_cast<int>(mec_option::number_ok))
break;
r = mec_error::number;
goto Error;
default:
break;
}
r = mec_error::success;
Error:
return r;
}
bool
add_object_to_context(rgw_obj &obj, rapidjson::Document &d)
{
ARN a{obj};
const char aws_s3_arn[] { "aws:s3:arn" };
std::string as{a.to_string()};
rapidjson::Document::AllocatorType &allocator { d.GetAllocator() };
rapidjson::Value name, val;
if (!d.IsObject())
return false;
if (d.HasMember(aws_s3_arn))
return true;
val.SetString(as.c_str(), as.length(), allocator);
name.SetString(aws_s3_arn, sizeof aws_s3_arn - 1, allocator);
d.AddMember(name, val, allocator);
return true;
}
static inline const std::string &
get_tenant_or_id(req_state *s)
{
const std::string &tenant{ s->user->get_tenant() };
if (!tenant.empty()) return tenant;
return s->user->get_id().id;
}
int
make_canonical_context(req_state *s,
std::string_view &context,
std::string &cooked_context)
{
rapidjson::Document d;
bool b = false;
mec_option options {
//mec_option::number_ok : SEE BOTTOM OF FILE
mec_option::empty };
rgw_obj obj;
std::ostringstream oss;
canonical_char_sorter<MyMember> ccs{s, s->cct};
obj.bucket.tenant = get_tenant_or_id(s);
obj.bucket.name = s->bucket->get_name();
obj.key.name = s->object->get_name();
std::string iline;
rapidjson::Document::AllocatorType &allocator { d.GetAllocator() };
try {
iline = rgw::from_base64(context);
} catch (const std::exception& e) {
oss << "bad context: " << e.what();
s->err.message = oss.str();
return -ERR_INVALID_REQUEST;
}
rapidjson::StringStream isw(iline.c_str());
if (!iline.length())
d.SetObject();
// else if (qflag) SEE BOTTOM OF FILE
// d.ParseStream<rapidjson::kParseNumbersAsStringsFlag>(isw);
else
d.ParseStream<rapidjson::kParseFullPrecisionFlag>(isw);
if (isw.Tell() != iline.length()) {
oss << "bad context: did not consume all of input: @ "
<< isw.Tell();
s->err.message = oss.str();
return -ERR_INVALID_REQUEST;
}
if (d.HasParseError()) {
oss << "bad context: parse error: @ " << d.GetErrorOffset()
<< " " << rapidjson::GetParseError_En(d.GetParseError());
s->err.message = oss.str();
return -ERR_INVALID_REQUEST;
}
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> writer(buf);
if (!add_object_to_context(obj, d)) {
ldpp_dout(s, -1) << "ERROR: can't add default value to context" << dendl;
s->err.message = "context: internal error adding defaults";
return -ERR_INVALID_REQUEST;
}
b = make_everything_canonical(d, allocator, ccs, options) == mec_error::success;
if (!b) {
ldpp_dout(s, -1) << "ERROR: can't make canonical json <"
<< context << ">" << dendl;
s->err.message = "context: can't make canonical";
return -ERR_INVALID_REQUEST;
}
b = sort_and_write(d, writer, ccs);
if (!b) {
ldpp_dout(s, 5) << "format error <" << context
<< ">: partial.results=" << buf.GetString() << dendl;
s->err.message = "unable to reformat json";
return -ERR_INVALID_REQUEST;
}
cooked_context = rgw::to_base64(buf.GetString());
return 0;
}
CryptoAccelRef get_crypto_accel(const DoutPrefixProvider* dpp, CephContext *cct, const size_t chunk_size, const size_t max_requests)
{
CryptoAccelRef ca_impl = nullptr;
stringstream ss;
PluginRegistry *reg = cct->get_plugin_registry();
string crypto_accel_type = cct->_conf->plugin_crypto_accelerator;
CryptoPlugin *factory = dynamic_cast<CryptoPlugin*>(reg->get_with_load("crypto", crypto_accel_type));
if (factory == nullptr) {
ldpp_dout(dpp, -1) << __func__ << " cannot load crypto accelerator of type " << crypto_accel_type << dendl;
return nullptr;
}
int err = factory->factory(&ca_impl, &ss, chunk_size, max_requests);
if (err) {
ldpp_dout(dpp, -1) << __func__ << " factory return error " << err <<
" with description: " << ss.str() << dendl;
}
return ca_impl;
}
template <std::size_t KeySizeV, std::size_t IvSizeV>
static inline
bool evp_sym_transform(const DoutPrefixProvider* dpp,
CephContext* const cct,
const EVP_CIPHER* const type,
unsigned char* const out,
const unsigned char* const in,
const size_t size,
const unsigned char* const iv,
const unsigned char* const key,
const bool encrypt)
{
using pctx_t = \
std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>;
pctx_t pctx{ EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free };
if (!pctx) {
return false;
}
if (1 != EVP_CipherInit_ex(pctx.get(), type, nullptr,
nullptr, nullptr, encrypt)) {
ldpp_dout(dpp, 5) << "EVP: failed to 1st initialization stage" << dendl;
return false;
}
// we want to support ciphers that don't use IV at all like AES-256-ECB
if constexpr (static_cast<bool>(IvSizeV)) {
ceph_assert(EVP_CIPHER_CTX_iv_length(pctx.get()) == IvSizeV);
ceph_assert(EVP_CIPHER_CTX_block_size(pctx.get()) == IvSizeV);
}
ceph_assert(EVP_CIPHER_CTX_key_length(pctx.get()) == KeySizeV);
if (1 != EVP_CipherInit_ex(pctx.get(), nullptr, nullptr, key, iv, encrypt)) {
ldpp_dout(dpp, 5) << "EVP: failed to 2nd initialization stage" << dendl;
return false;
}
// disable padding
if (1 != EVP_CIPHER_CTX_set_padding(pctx.get(), 0)) {
ldpp_dout(dpp, 5) << "EVP: cannot disable PKCS padding" << dendl;
return false;
}
// operate!
int written = 0;
ceph_assert(size <= static_cast<size_t>(std::numeric_limits<int>::max()));
if (1 != EVP_CipherUpdate(pctx.get(), out, &written, in, size)) {
ldpp_dout(dpp, 5) << "EVP: EVP_CipherUpdate failed" << dendl;
return false;
}
int finally_written = 0;
static_assert(sizeof(*out) == 1);
if (1 != EVP_CipherFinal_ex(pctx.get(), out + written, &finally_written)) {
ldpp_dout(dpp, 5) << "EVP: EVP_CipherFinal_ex failed" << dendl;
return false;
}
// padding is disabled so EVP_CipherFinal_ex should not append anything
ceph_assert(finally_written == 0);
return (written + finally_written) == static_cast<int>(size);
}
/**
* Encryption in CBC mode. Chunked to 4K blocks. Offset is used as IV for each 4K block.
*
*
*
* A. Encryption
* 1. Input is split to 4K chunks + remainder in one, smaller chunk
* 2. Each full chunk is encrypted separately with CBC chained mode, with initial IV derived from offset
* 3. Last chunk is 16*m + n.
* 4. 16*m bytes are encrypted with CBC chained mode, with initial IV derived from offset
* 5. Last n bytes are xor-ed with pattern obtained by CBC encryption of
* last encrypted 16 byte block <16m-16, 16m-15) with IV = {0}.
* 6. (Special case) If m == 0 then last n bytes are xor-ed with pattern
* obtained by CBC encryption of {0} with IV derived from offset
*
* B. Decryption
* 1. Input is split to 4K chunks + remainder in one, smaller chunk
* 2. Each full chunk is decrypted separately with CBC chained mode, with initial IV derived from offset
* 3. Last chunk is 16*m + n.
* 4. 16*m bytes are decrypted with CBC chained mode, with initial IV derived from offset
* 5. Last n bytes are xor-ed with pattern obtained by CBC ENCRYPTION of
* last (still encrypted) 16 byte block <16m-16,16m-15) with IV = {0}
* 6. (Special case) If m == 0 then last n bytes are xor-ed with pattern
* obtained by CBC ENCRYPTION of {0} with IV derived from offset
*/
class AES_256_CBC : public BlockCrypt {
public:
static const size_t AES_256_KEYSIZE = 256 / 8;
static const size_t AES_256_IVSIZE = 128 / 8;
static const size_t CHUNK_SIZE = 4096;
static const size_t QAT_MIN_SIZE = 65536;
const DoutPrefixProvider* dpp;
private:
static const uint8_t IV[AES_256_IVSIZE];
CephContext* cct;
uint8_t key[AES_256_KEYSIZE];
public:
explicit AES_256_CBC(const DoutPrefixProvider* dpp, CephContext* cct): dpp(dpp), cct(cct) {
}
~AES_256_CBC() {
::ceph::crypto::zeroize_for_security(key, AES_256_KEYSIZE);
}
bool set_key(const uint8_t* _key, size_t key_size) {
if (key_size != AES_256_KEYSIZE) {
return false;
}
memcpy(key, _key, AES_256_KEYSIZE);
return true;
}
size_t get_block_size() {
return CHUNK_SIZE;
}
bool cbc_transform(unsigned char* out,
const unsigned char* in,
const size_t size,
const unsigned char (&iv)[AES_256_IVSIZE],
const unsigned char (&key)[AES_256_KEYSIZE],
bool encrypt)
{
return evp_sym_transform<AES_256_KEYSIZE, AES_256_IVSIZE>(
dpp, cct, EVP_aes_256_cbc(), out, in, size, iv, key, encrypt);
}
bool cbc_transform(unsigned char* out,
const unsigned char* in,
size_t size,
off_t stream_offset,
const unsigned char (&key)[AES_256_KEYSIZE],
bool encrypt,
optional_yield y)
{
static std::atomic<bool> failed_to_get_crypto(false);
CryptoAccelRef crypto_accel;
if (! failed_to_get_crypto.load())
{
static size_t max_requests = g_ceph_context->_conf->rgw_thread_pool_size;
crypto_accel = get_crypto_accel(this->dpp, cct, CHUNK_SIZE, max_requests);
if (!crypto_accel)
failed_to_get_crypto = true;
}
bool result = false;
static std::string accelerator = cct->_conf->plugin_crypto_accelerator;
if (accelerator == "crypto_qat" && crypto_accel != nullptr && size >= QAT_MIN_SIZE) {
// now, batch mode is only for QAT plugin
size_t iv_num = size / CHUNK_SIZE;
if (size % CHUNK_SIZE) ++iv_num;
auto iv = new unsigned char[iv_num][AES_256_IVSIZE];
for (size_t offset = 0, i = 0; offset < size; offset += CHUNK_SIZE, i++) {
prepare_iv(iv[i], stream_offset + offset);
}
if (encrypt) {
result = crypto_accel->cbc_encrypt_batch(out, in, size, iv, key, y);
} else {
result = crypto_accel->cbc_decrypt_batch(out, in, size, iv, key, y);
}
delete[] iv;
}
if (result == false) {
// If QAT don't have free instance, we can fall back to this
result = true;
unsigned char iv[AES_256_IVSIZE];
for (size_t offset = 0; result && (offset < size); offset += CHUNK_SIZE) {
size_t process_size = offset + CHUNK_SIZE <= size ? CHUNK_SIZE : size - offset;
prepare_iv(iv, stream_offset + offset);
if (crypto_accel != nullptr && accelerator != "crypto_qat") {
if (encrypt) {
result = crypto_accel->cbc_encrypt(out + offset, in + offset,
process_size, iv, key, y);
} else {
result = crypto_accel->cbc_decrypt(out + offset, in + offset,
process_size, iv, key, y);
}
} else {
result = cbc_transform(
out + offset, in + offset, process_size,
iv, key, encrypt);
}
}
}
return result;
}
bool encrypt(bufferlist& input,
off_t in_ofs,
size_t size,
bufferlist& output,
off_t stream_offset,
optional_yield y)
{
bool result = false;
size_t aligned_size = size / AES_256_IVSIZE * AES_256_IVSIZE;
size_t unaligned_rest_size = size - aligned_size;
output.clear();
buffer::ptr buf(aligned_size + AES_256_IVSIZE);
unsigned char* buf_raw = reinterpret_cast<unsigned char*>(buf.c_str());
const unsigned char* input_raw = reinterpret_cast<const unsigned char*>(input.c_str());
/* encrypt main bulk of data */
result = cbc_transform(buf_raw,
input_raw + in_ofs,
aligned_size,
stream_offset, key, true, y);
if (result && (unaligned_rest_size > 0)) {
/* remainder to encrypt */
if (aligned_size % CHUNK_SIZE > 0) {
/* use last chunk for unaligned part */
unsigned char iv[AES_256_IVSIZE] = {0};
result = cbc_transform(buf_raw + aligned_size,
buf_raw + aligned_size - AES_256_IVSIZE,
AES_256_IVSIZE,
iv, key, true);
} else {
/* 0 full blocks in current chunk, use IV as base for unaligned part */
unsigned char iv[AES_256_IVSIZE] = {0};
unsigned char data[AES_256_IVSIZE];
prepare_iv(data, stream_offset + aligned_size);
result = cbc_transform(buf_raw + aligned_size,
data,
AES_256_IVSIZE,
iv, key, true);
}
if (result) {
for(size_t i = aligned_size; i < size; i++) {
*(buf_raw + i) ^= *(input_raw + in_ofs + i);
}
}
}
if (result) {
ldpp_dout(this->dpp, 25) << "Encrypted " << size << " bytes"<< dendl;
buf.set_length(size);
output.append(buf);
} else {
ldpp_dout(this->dpp, 5) << "Failed to encrypt" << dendl;
}
return result;
}
bool decrypt(bufferlist& input,
off_t in_ofs,
size_t size,
bufferlist& output,
off_t stream_offset,
optional_yield y)
{
bool result = false;
size_t aligned_size = size / AES_256_IVSIZE * AES_256_IVSIZE;
size_t unaligned_rest_size = size - aligned_size;
output.clear();
buffer::ptr buf(aligned_size + AES_256_IVSIZE);
unsigned char* buf_raw = reinterpret_cast<unsigned char*>(buf.c_str());
unsigned char* input_raw = reinterpret_cast<unsigned char*>(input.c_str());
/* decrypt main bulk of data */
result = cbc_transform(buf_raw,
input_raw + in_ofs,
aligned_size,
stream_offset, key, false, y);
if (result && unaligned_rest_size > 0) {
/* remainder to decrypt */
if (aligned_size % CHUNK_SIZE > 0) {
/*use last chunk for unaligned part*/
unsigned char iv[AES_256_IVSIZE] = {0};
result = cbc_transform(buf_raw + aligned_size,
input_raw + in_ofs + aligned_size - AES_256_IVSIZE,
AES_256_IVSIZE,
iv, key, true);
} else {
/* 0 full blocks in current chunk, use IV as base for unaligned part */
unsigned char iv[AES_256_IVSIZE] = {0};
unsigned char data[AES_256_IVSIZE];
prepare_iv(data, stream_offset + aligned_size);
result = cbc_transform(buf_raw + aligned_size,
data,
AES_256_IVSIZE,
iv, key, true);
}
if (result) {
for(size_t i = aligned_size; i < size; i++) {
*(buf_raw + i) ^= *(input_raw + in_ofs + i);
}
}
}
if (result) {
ldpp_dout(this->dpp, 25) << "Decrypted " << size << " bytes"<< dendl;
buf.set_length(size);
output.append(buf);
} else {
ldpp_dout(this->dpp, 5) << "Failed to decrypt" << dendl;
}
return result;
}
void prepare_iv(unsigned char (&iv)[AES_256_IVSIZE], off_t offset) {
off_t index = offset / AES_256_IVSIZE;
off_t i = AES_256_IVSIZE - 1;
unsigned int val;
unsigned int carry = 0;
while (i>=0) {
val = (index & 0xff) + IV[i] + carry;
iv[i] = val;
carry = val >> 8;
index = index >> 8;
i--;
}
}
};
std::unique_ptr<BlockCrypt> AES_256_CBC_create(const DoutPrefixProvider* dpp, CephContext* cct, const uint8_t* key, size_t len)
{
auto cbc = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(dpp, cct));
cbc->set_key(key, AES_256_KEYSIZE);
return cbc;
}
const uint8_t AES_256_CBC::IV[AES_256_CBC::AES_256_IVSIZE] =
{ 'a', 'e', 's', '2', '5', '6', 'i', 'v', '_', 'c', 't', 'r', '1', '3', '3', '7' };
bool AES_256_ECB_encrypt(const DoutPrefixProvider* dpp,
CephContext* cct,
const uint8_t* key,
size_t key_size,
const uint8_t* data_in,
uint8_t* data_out,
size_t data_size)
{
if (key_size == AES_256_KEYSIZE) {
return evp_sym_transform<AES_256_KEYSIZE, 0 /* no IV in ECB */>(
dpp, cct, EVP_aes_256_ecb(), data_out, data_in, data_size,
nullptr /* no IV in ECB */, key, true /* encrypt */);
} else {
ldpp_dout(dpp, 5) << "Key size must be 256 bits long" << dendl;
return false;
}
}
RGWGetObj_BlockDecrypt::RGWGetObj_BlockDecrypt(const DoutPrefixProvider *dpp,
CephContext* cct,
RGWGetObj_Filter* next,
std::unique_ptr<BlockCrypt> crypt,
optional_yield y)
:
RGWGetObj_Filter(next),
dpp(dpp),
cct(cct),
crypt(std::move(crypt)),
enc_begin_skip(0),
ofs(0),
end(0),
cache(),
y(y)
{
block_size = this->crypt->get_block_size();
}
RGWGetObj_BlockDecrypt::~RGWGetObj_BlockDecrypt() {
}
int RGWGetObj_BlockDecrypt::read_manifest(const DoutPrefixProvider *dpp, bufferlist& manifest_bl) {
parts_len.clear();
RGWObjManifest manifest;
if (manifest_bl.length()) {
auto miter = manifest_bl.cbegin();
try {
decode(manifest, miter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: couldn't decode manifest" << dendl;
return -EIO;
}
RGWObjManifest::obj_iterator mi;
for (mi = manifest.obj_begin(dpp); mi != manifest.obj_end(dpp); ++mi) {
if (mi.get_cur_stripe() == 0) {
parts_len.push_back(0);
}
parts_len.back() += mi.get_stripe_size();
}
if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
for (size_t i = 0; i<parts_len.size(); i++) {
ldpp_dout(dpp, 20) << "Manifest part " << i << ", size=" << parts_len[i] << dendl;
}
}
}
return 0;
}
int RGWGetObj_BlockDecrypt::fixup_range(off_t& bl_ofs, off_t& bl_end) {
off_t inp_ofs = bl_ofs;
off_t inp_end = bl_end;
if (parts_len.size() > 0) {
off_t in_ofs = bl_ofs;
off_t in_end = bl_end;
size_t i = 0;
while (i<parts_len.size() && (in_ofs >= (off_t)parts_len[i])) {
in_ofs -= parts_len[i];
i++;
}
//in_ofs is inside block i
size_t j = 0;
while (j<(parts_len.size() - 1) && (in_end >= (off_t)parts_len[j])) {
in_end -= parts_len[j];
j++;
}
//in_end is inside part j, OR j is the last part
size_t rounded_end = ( in_end & ~(block_size - 1) ) + (block_size - 1);
if (rounded_end > parts_len[j]) {
rounded_end = parts_len[j] - 1;
}
enc_begin_skip = in_ofs & (block_size - 1);
ofs = bl_ofs - enc_begin_skip;
end = bl_end;
bl_end += rounded_end - in_end;
bl_ofs = std::min(bl_ofs - enc_begin_skip, bl_end);
}
else
{
enc_begin_skip = bl_ofs & (block_size - 1);
ofs = bl_ofs & ~(block_size - 1);
end = bl_end;
bl_ofs = bl_ofs & ~(block_size - 1);
bl_end = ( bl_end & ~(block_size - 1) ) + (block_size - 1);
}
ldpp_dout(this->dpp, 20) << "fixup_range [" << inp_ofs << "," << inp_end
<< "] => [" << bl_ofs << "," << bl_end << "]" << dendl;
return 0;
}
int RGWGetObj_BlockDecrypt::process(bufferlist& in, size_t part_ofs, size_t size)
{
bufferlist data;
if (!crypt->decrypt(in, 0, size, data, part_ofs, y)) {
return -ERR_INTERNAL_ERROR;
}
off_t send_size = size - enc_begin_skip;
if (ofs + enc_begin_skip + send_size > end + 1) {
send_size = end + 1 - ofs - enc_begin_skip;
}
int res = next->handle_data(data, enc_begin_skip, send_size);
enc_begin_skip = 0;
ofs += size;
in.splice(0, size);
return res;
}
int RGWGetObj_BlockDecrypt::handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) {
ldpp_dout(this->dpp, 25) << "Decrypt " << bl_len << " bytes" << dendl;
bl.begin(bl_ofs).copy(bl_len, cache);
int res = 0;
size_t part_ofs = ofs;
for (size_t part : parts_len) {
if (part_ofs >= part) {
part_ofs -= part;
} else if (part_ofs + cache.length() >= part) {
// flush data up to part boundaries, aligned or not
res = process(cache, part_ofs, part - part_ofs);
if (res < 0) {
return res;
}
part_ofs = 0;
} else {
break;
}
}
// write up to block boundaries, aligned only
off_t aligned_size = cache.length() & ~(block_size - 1);
if (aligned_size > 0) {
res = process(cache, part_ofs, aligned_size);
}
return res;
}
/**
* flush remainder of data to output
*/
int RGWGetObj_BlockDecrypt::flush() {
ldpp_dout(this->dpp, 25) << "Decrypt flushing " << cache.length() << " bytes" << dendl;
int res = 0;
size_t part_ofs = ofs;
for (size_t part : parts_len) {
if (part_ofs >= part) {
part_ofs -= part;
} else if (part_ofs + cache.length() >= part) {
// flush data up to part boundaries, aligned or not
res = process(cache, part_ofs, part - part_ofs);
if (res < 0) {
return res;
}
part_ofs = 0;
} else {
break;
}
}
// flush up to block boundaries, aligned or not
if (cache.length() > 0) {
res = process(cache, part_ofs, cache.length());
}
return res;
}
RGWPutObj_BlockEncrypt::RGWPutObj_BlockEncrypt(const DoutPrefixProvider *dpp,
CephContext* cct,
rgw::sal::DataProcessor *next,
std::unique_ptr<BlockCrypt> crypt,
optional_yield y)
: Pipe(next),
dpp(dpp),
cct(cct),
crypt(std::move(crypt)),
block_size(this->crypt->get_block_size()),
y(y)
{
}
int RGWPutObj_BlockEncrypt::process(bufferlist&& data, uint64_t logical_offset)
{
ldpp_dout(this->dpp, 25) << "Encrypt " << data.length() << " bytes" << dendl;
// adjust logical offset to beginning of cached data
ceph_assert(logical_offset >= cache.length());
logical_offset -= cache.length();
const bool flush = (data.length() == 0);
cache.claim_append(data);
uint64_t proc_size = cache.length() & ~(block_size - 1);
if (flush) {
proc_size = cache.length();
}
if (proc_size > 0) {
bufferlist in, out;
cache.splice(0, proc_size, &in);
if (!crypt->encrypt(in, 0, proc_size, out, logical_offset, y)) {
return -ERR_INTERNAL_ERROR;
}
int r = Pipe::process(std::move(out), logical_offset);
logical_offset += proc_size;
if (r < 0)
return r;
}
if (flush) {
/*replicate 0-sized handle_data*/
return Pipe::process({}, logical_offset);
}
return 0;
}
std::string create_random_key_selector(CephContext * const cct) {
char random[AES_256_KEYSIZE];
cct->random()->get_bytes(&random[0], sizeof(random));
return std::string(random, sizeof(random));
}
typedef enum {
X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM=0,
X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY,
X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5,
X_AMZ_SERVER_SIDE_ENCRYPTION,
X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID,
X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT,
X_AMZ_SERVER_SIDE_ENCRYPTION_LAST
} crypt_option_e;
struct crypt_option_names {
const std::string post_part_name;
};
static const crypt_option_names crypt_options[] = {
{ "x-amz-server-side-encryption-customer-algorithm"},
{ "x-amz-server-side-encryption-customer-key"},
{ "x-amz-server-side-encryption-customer-key-md5"},
{ "x-amz-server-side-encryption"},
{ "x-amz-server-side-encryption-aws-kms-key-id"},
{ "x-amz-server-side-encryption-context"},
};
struct CryptAttributes {
meta_map_t &x_meta_map;
CryptAttributes(req_state *s)
: x_meta_map(s->info.crypt_attribute_map) {
}
std::string_view get(crypt_option_e option)
{
static_assert(
X_AMZ_SERVER_SIDE_ENCRYPTION_LAST == sizeof(crypt_options)/sizeof(*crypt_options),
"Missing items in crypt_options");
auto hdr { x_meta_map.find(crypt_options[option].post_part_name) };
if (hdr != x_meta_map.end()) {
return std::string_view(hdr->second);
} else {
return std::string_view();
}
}
};
std::string fetch_bucket_key_id(req_state *s)
{
auto kek_iter = s->bucket_attrs.find(RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID);
if (kek_iter == s->bucket_attrs.end())
return std::string();
std::string a_key { kek_iter->second.to_str() };
// early code appends a nul; pretend that didn't happen
auto l { a_key.length() };
if (l > 0 && a_key[l-1] == '\0') {
a_key.resize(--l);
}
return a_key;
}
const std::string cant_expand_key{ "\uFFFD" };
std::string expand_key_name(req_state *s, const std::string_view&t)
{
std::string r;
size_t i, j;
for (i = 0;;) {
i = t.find('%', (j = i));
if (i != j) {
if (i == std::string_view::npos)
r.append( t.substr(j) );
else
r.append( t.substr(j, i-j) );
}
if (i == std::string_view::npos) {
break;
}
if (t[i+1] == '%') {
r.append("%");
i += 2;
continue;
}
if (t.compare(i+1, 9, "bucket_id") == 0) {
r.append(s->bucket->get_marker());
i += 10;
continue;
}
if (t.compare(i+1, 8, "owner_id") == 0) {
r.append(s->bucket->get_info().owner.id);
i += 9;
continue;
}
return cant_expand_key;
}
return r;
}
static int get_sse_s3_bucket_key(req_state *s,
std::string &key_id)
{
int res;
std::string saved_key;
key_id = expand_key_name(s, s->cct->_conf->rgw_crypt_sse_s3_key_template);
if (key_id == cant_expand_key) {
ldpp_dout(s, 5) << "ERROR: unable to expand key_id " <<
s->cct->_conf->rgw_crypt_sse_s3_key_template << " on bucket" << dendl;
s->err.message = "Server side error - unable to expand key_id";
return -EINVAL;
}
saved_key = fetch_bucket_key_id(s);
if (saved_key != "") {
ldpp_dout(s, 5) << "Found KEK ID: " << key_id << dendl;
}
if (saved_key != key_id) {
res = create_sse_s3_bucket_key(s, s->cct, key_id);
if (res != 0) {
return res;
}
bufferlist key_id_bl;
key_id_bl.append(key_id.c_str(), key_id.length());
for (int count = 0; count < 15; ++count) {
rgw::sal::Attrs attrs = s->bucket->get_attrs();
attrs[RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID] = key_id_bl;
res = s->bucket->merge_and_store_attrs(s, attrs, s->yield);
if (res != -ECANCELED) {
break;
}
res = s->bucket->try_refresh_info(s, nullptr, s->yield);
if (res != 0) {
break;
}
}
if (res != 0) {
ldpp_dout(s, 5) << "ERROR: unable to save new key_id on bucket" << dendl;
s->err.message = "Server side error - unable to save key_id";
return res;
}
}
return 0;
}
int rgw_s3_prepare_encrypt(req_state* s,
std::map<std::string, ceph::bufferlist>& attrs,
std::unique_ptr<BlockCrypt>* block_crypt,
std::map<std::string, std::string>& crypt_http_responses)
{
int res = 0;
CryptAttributes crypt_attributes { s };
crypt_http_responses.clear();
{
std::string_view req_sse_ca =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM);
if (! req_sse_ca.empty()) {
if (req_sse_ca != "AES256") {
ldpp_dout(s, 5) << "ERROR: Invalid value for header "
<< "x-amz-server-side-encryption-customer-algorithm"
<< dendl;
s->err.message = "The requested encryption algorithm is not valid, must be AES256.";
return -ERR_INVALID_ENCRYPTION_ALGORITHM;
}
if (s->cct->_conf->rgw_crypt_require_ssl &&
!rgw_transport_is_secure(s->cct, *s->info.env)) {
ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl;
return -ERR_INVALID_REQUEST;
}
std::string key_bin;
try {
key_bin = from_base64(
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY) );
} catch (...) {
ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_encrypt invalid encryption "
<< "key which contains character that is not base64 encoded."
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key.";
return -EINVAL;
}
if (key_bin.size() != AES_256_CBC::AES_256_KEYSIZE) {
ldpp_dout(s, 5) << "ERROR: invalid encryption key size" << dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key.";
return -EINVAL;
}
std::string_view keymd5 =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5);
std::string keymd5_bin;
try {
keymd5_bin = from_base64(keymd5);
} catch (...) {
ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_encrypt invalid encryption key "
<< "md5 which contains character that is not base64 encoded."
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key md5.";
return -EINVAL;
}
if (keymd5_bin.size() != CEPH_CRYPTO_MD5_DIGESTSIZE) {
ldpp_dout(s, 5) << "ERROR: Invalid key md5 size" << dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key md5.";
return -EINVAL;
}
MD5 key_hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
key_hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
unsigned char key_hash_res[CEPH_CRYPTO_MD5_DIGESTSIZE];
key_hash.Update(reinterpret_cast<const unsigned char*>(key_bin.c_str()), key_bin.size());
key_hash.Final(key_hash_res);
if (memcmp(key_hash_res, keymd5_bin.c_str(), CEPH_CRYPTO_MD5_DIGESTSIZE) != 0) {
ldpp_dout(s, 5) << "ERROR: Invalid key md5 hash" << dendl;
s->err.message = "The calculated MD5 hash of the key did not match the hash that was provided.";
return -EINVAL;
}
set_attr(attrs, RGW_ATTR_CRYPT_MODE, "SSE-C-AES256");
set_attr(attrs, RGW_ATTR_CRYPT_KEYMD5, keymd5_bin);
if (block_crypt) {
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(key_bin.c_str()), AES_256_KEYSIZE);
*block_crypt = std::move(aes);
}
crypt_http_responses["x-amz-server-side-encryption-customer-algorithm"] = "AES256";
crypt_http_responses["x-amz-server-side-encryption-customer-key-MD5"] = std::string(keymd5);
return 0;
} else {
std::string_view customer_key =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY);
if (!customer_key.empty()) {
ldpp_dout(s, 5) << "ERROR: SSE-C encryption request is missing the header "
<< "x-amz-server-side-encryption-customer-algorithm"
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide a valid encryption algorithm.";
return -EINVAL;
}
std::string_view customer_key_md5 =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5);
if (!customer_key_md5.empty()) {
ldpp_dout(s, 5) << "ERROR: SSE-C encryption request is missing the header "
<< "x-amz-server-side-encryption-customer-algorithm"
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide a valid encryption algorithm.";
return -EINVAL;
}
}
/* AMAZON server side encryption with KMS (key management service) */
std::string_view req_sse =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION);
if (! req_sse.empty()) {
if (s->cct->_conf->rgw_crypt_require_ssl &&
!rgw_transport_is_secure(s->cct, *s->info.env)) {
ldpp_dout(s, 5) << "ERROR: insecure request, rgw_crypt_require_ssl is set" << dendl;
return -ERR_INVALID_REQUEST;
}
if (req_sse == "aws:kms") {
std::string_view context =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT);
std::string cooked_context;
if ((res = make_canonical_context(s, context, cooked_context)))
return res;
std::string_view key_id =
crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID);
if (key_id.empty()) {
ldpp_dout(s, 5) << "ERROR: not provide a valid key id" << dendl;
s->err.message = "Server Side Encryption with KMS managed key requires "
"HTTP header x-amz-server-side-encryption-aws-kms-key-id";
return -EINVAL;
}
/* try to retrieve actual key */
std::string key_selector = create_random_key_selector(s->cct);
set_attr(attrs, RGW_ATTR_CRYPT_MODE, "SSE-KMS");
set_attr(attrs, RGW_ATTR_CRYPT_KEYID, key_id);
set_attr(attrs, RGW_ATTR_CRYPT_KEYSEL, key_selector);
set_attr(attrs, RGW_ATTR_CRYPT_CONTEXT, cooked_context);
std::string actual_key;
res = make_actual_key_from_kms(s, s->cct, attrs, actual_key);
if (res != 0) {
ldpp_dout(s, 5) << "ERROR: failed to retrieve actual key from key_id: " << key_id << dendl;
s->err.message = "Failed to retrieve the actual key, kms-keyid: " + std::string(key_id);
return res;
}
if (actual_key.size() != AES_256_KEYSIZE) {
ldpp_dout(s, 5) << "ERROR: key obtained from key_id:" <<
key_id << " is not 256 bit size" << dendl;
s->err.message = "KMS provided an invalid key for the given kms-keyid.";
return -EINVAL;
}
if (block_crypt) {
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE);
*block_crypt = std::move(aes);
}
::ceph::crypto::zeroize_for_security(actual_key.data(), actual_key.length());
crypt_http_responses["x-amz-server-side-encryption"] = "aws:kms";
crypt_http_responses["x-amz-server-side-encryption-aws-kms-key-id"] = std::string(key_id);
crypt_http_responses["x-amz-server-side-encryption-context"] = std::move(cooked_context);
return 0;
} else if (req_sse == "AES256") {
/* SSE-S3: fall through to logic to look for vault or test key */
} else {
ldpp_dout(s, 5) << "ERROR: Invalid value for header x-amz-server-side-encryption"
<< dendl;
s->err.message = "Server Side Encryption with KMS managed key requires "
"HTTP header x-amz-server-side-encryption : aws:kms or AES256";
return -EINVAL;
}
} else {
/*no encryption*/
return 0;
}
/* from here on we are only handling SSE-S3 (req_sse=="AES256") */
if (s->cct->_conf->rgw_crypt_sse_s3_backend == "vault") {
ldpp_dout(s, 5) << "RGW_ATTR_BUCKET_ENCRYPTION ALGO: "
<< req_sse << dendl;
std::string_view context = "";
std::string cooked_context;
if ((res = make_canonical_context(s, context, cooked_context)))
return res;
std::string key_id;
res = get_sse_s3_bucket_key(s, key_id);
if (res != 0) {
return res;
}
std::string key_selector = create_random_key_selector(s->cct);
set_attr(attrs, RGW_ATTR_CRYPT_KEYSEL, key_selector);
set_attr(attrs, RGW_ATTR_CRYPT_CONTEXT, cooked_context);
set_attr(attrs, RGW_ATTR_CRYPT_MODE, "AES256");
set_attr(attrs, RGW_ATTR_CRYPT_KEYID, key_id);
std::string actual_key;
res = make_actual_key_from_sse_s3(s, s->cct, attrs, actual_key);
if (res != 0) {
ldpp_dout(s, 5) << "ERROR: failed to retrieve actual key from key_id: " << key_id << dendl;
s->err.message = "Failed to retrieve the actual key";
return res;
}
if (actual_key.size() != AES_256_KEYSIZE) {
ldpp_dout(s, 5) << "ERROR: key obtained from key_id:" <<
key_id << " is not 256 bit size" << dendl;
s->err.message = "SSE-S3 provided an invalid key for the given keyid.";
return -EINVAL;
}
if (block_crypt) {
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE);
*block_crypt = std::move(aes);
}
::ceph::crypto::zeroize_for_security(actual_key.data(), actual_key.length());
crypt_http_responses["x-amz-server-side-encryption"] = "AES256";
return 0;
}
/* SSE-S3 and no backend, check if there is a test key */
if (s->cct->_conf->rgw_crypt_default_encryption_key != "") {
std::string master_encryption_key;
try {
master_encryption_key = from_base64(s->cct->_conf->rgw_crypt_default_encryption_key);
} catch (...) {
ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_encrypt invalid default encryption key "
<< "which contains character that is not base64 encoded."
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key.";
return -EINVAL;
}
if (master_encryption_key.size() != 256 / 8) {
ldpp_dout(s, 0) << "ERROR: failed to decode 'rgw crypt default encryption key' to 256 bit string" << dendl;
/* not an error to return; missing encryption does not inhibit processing */
return 0;
}
set_attr(attrs, RGW_ATTR_CRYPT_MODE, "RGW-AUTO");
std::string key_selector = create_random_key_selector(s->cct);
set_attr(attrs, RGW_ATTR_CRYPT_KEYSEL, key_selector);
uint8_t actual_key[AES_256_KEYSIZE];
if (AES_256_ECB_encrypt(s, s->cct,
reinterpret_cast<const uint8_t*>(master_encryption_key.c_str()), AES_256_KEYSIZE,
reinterpret_cast<const uint8_t*>(key_selector.c_str()),
actual_key, AES_256_KEYSIZE) != true) {
::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key));
return -EIO;
}
if (block_crypt) {
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(actual_key), AES_256_KEYSIZE);
*block_crypt = std::move(aes);
}
::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key));
return 0;
}
s->err.message = "Request specifies Server Side Encryption "
"but server configuration does not support this.";
return -EINVAL;
}
}
int rgw_s3_prepare_decrypt(req_state* s,
map<string, bufferlist>& attrs,
std::unique_ptr<BlockCrypt>* block_crypt,
std::map<std::string, std::string>& crypt_http_responses)
{
int res = 0;
std::string stored_mode = get_str_attribute(attrs, RGW_ATTR_CRYPT_MODE);
ldpp_dout(s, 15) << "Encryption mode: " << stored_mode << dendl;
const char *req_sse = s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION", NULL);
if (nullptr != req_sse && (s->op == OP_GET || s->op == OP_HEAD)) {
return -ERR_INVALID_REQUEST;
}
if (stored_mode == "SSE-C-AES256") {
if (s->cct->_conf->rgw_crypt_require_ssl &&
!rgw_transport_is_secure(s->cct, *s->info.env)) {
ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl;
return -ERR_INVALID_REQUEST;
}
const char *req_cust_alg =
s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM", NULL);
if (nullptr == req_cust_alg) {
ldpp_dout(s, 5) << "ERROR: Request for SSE-C encrypted object missing "
<< "x-amz-server-side-encryption-customer-algorithm"
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide a valid encryption algorithm.";
return -EINVAL;
} else if (strcmp(req_cust_alg, "AES256") != 0) {
ldpp_dout(s, 5) << "ERROR: The requested encryption algorithm is not valid, must be AES256." << dendl;
s->err.message = "The requested encryption algorithm is not valid, must be AES256.";
return -ERR_INVALID_ENCRYPTION_ALGORITHM;
}
std::string key_bin;
try {
key_bin = from_base64(s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY", ""));
} catch (...) {
ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_decrypt invalid encryption key "
<< "which contains character that is not base64 encoded."
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key.";
return -EINVAL;
}
if (key_bin.size() != AES_256_CBC::AES_256_KEYSIZE) {
ldpp_dout(s, 5) << "ERROR: Invalid encryption key size" << dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key.";
return -EINVAL;
}
std::string keymd5 =
s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5", "");
std::string keymd5_bin;
try {
keymd5_bin = from_base64(keymd5);
} catch (...) {
ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_decrypt invalid encryption key md5 "
<< "which contains character that is not base64 encoded."
<< dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key md5.";
return -EINVAL;
}
if (keymd5_bin.size() != CEPH_CRYPTO_MD5_DIGESTSIZE) {
ldpp_dout(s, 5) << "ERROR: Invalid key md5 size " << dendl;
s->err.message = "Requests specifying Server Side Encryption with Customer "
"provided keys must provide an appropriate secret key md5.";
return -EINVAL;
}
MD5 key_hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
key_hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
uint8_t key_hash_res[CEPH_CRYPTO_MD5_DIGESTSIZE];
key_hash.Update(reinterpret_cast<const unsigned char*>(key_bin.c_str()), key_bin.size());
key_hash.Final(key_hash_res);
if ((memcmp(key_hash_res, keymd5_bin.c_str(), CEPH_CRYPTO_MD5_DIGESTSIZE) != 0) ||
(get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYMD5) != keymd5_bin)) {
s->err.message = "The calculated MD5 hash of the key did not match the hash that was provided.";
return -EINVAL;
}
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(key_bin.c_str()), AES_256_CBC::AES_256_KEYSIZE);
if (block_crypt) *block_crypt = std::move(aes);
crypt_http_responses["x-amz-server-side-encryption-customer-algorithm"] = "AES256";
crypt_http_responses["x-amz-server-side-encryption-customer-key-MD5"] = keymd5;
return 0;
}
if (stored_mode == "SSE-KMS") {
if (s->cct->_conf->rgw_crypt_require_ssl &&
!rgw_transport_is_secure(s->cct, *s->info.env)) {
ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl;
return -ERR_INVALID_REQUEST;
}
/* try to retrieve actual key */
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
std::string actual_key;
res = reconstitute_actual_key_from_kms(s, s->cct, attrs, actual_key);
if (res != 0) {
ldpp_dout(s, 10) << "ERROR: failed to retrieve actual key from key_id: " << key_id << dendl;
s->err.message = "Failed to retrieve the actual key, kms-keyid: " + key_id;
return res;
}
if (actual_key.size() != AES_256_KEYSIZE) {
ldpp_dout(s, 0) << "ERROR: key obtained from key_id:" <<
key_id << " is not 256 bit size" << dendl;
s->err.message = "KMS provided an invalid key for the given kms-keyid.";
return -EINVAL;
}
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE);
actual_key.replace(0, actual_key.length(), actual_key.length(), '\000');
if (block_crypt) *block_crypt = std::move(aes);
crypt_http_responses["x-amz-server-side-encryption"] = "aws:kms";
crypt_http_responses["x-amz-server-side-encryption-aws-kms-key-id"] = key_id;
return 0;
}
if (stored_mode == "RGW-AUTO") {
std::string master_encryption_key;
try {
master_encryption_key = from_base64(std::string(s->cct->_conf->rgw_crypt_default_encryption_key));
} catch (...) {
ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_decrypt invalid default encryption key "
<< "which contains character that is not base64 encoded."
<< dendl;
s->err.message = "The default encryption key is not valid base64.";
return -EINVAL;
}
if (master_encryption_key.size() != 256 / 8) {
ldpp_dout(s, 0) << "ERROR: failed to decode 'rgw crypt default encryption key' to 256 bit string" << dendl;
return -EIO;
}
std::string attr_key_selector = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYSEL);
if (attr_key_selector.size() != AES_256_CBC::AES_256_KEYSIZE) {
ldpp_dout(s, 0) << "ERROR: missing or invalid " RGW_ATTR_CRYPT_KEYSEL << dendl;
return -EIO;
}
uint8_t actual_key[AES_256_KEYSIZE];
if (AES_256_ECB_encrypt(s, s->cct,
reinterpret_cast<const uint8_t*>(master_encryption_key.c_str()),
AES_256_KEYSIZE,
reinterpret_cast<const uint8_t*>(attr_key_selector.c_str()),
actual_key, AES_256_KEYSIZE) != true) {
::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key));
return -EIO;
}
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(actual_key, AES_256_KEYSIZE);
::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key));
if (block_crypt) *block_crypt = std::move(aes);
return 0;
}
/* SSE-S3 */
if (stored_mode == "AES256") {
if (s->cct->_conf->rgw_crypt_require_ssl &&
!rgw_transport_is_secure(s->cct, *s->info.env)) {
ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl;
return -ERR_INVALID_REQUEST;
}
/* try to retrieve actual key */
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
std::string actual_key;
res = reconstitute_actual_key_from_sse_s3(s, s->cct, attrs, actual_key);
if (res != 0) {
ldpp_dout(s, 10) << "ERROR: failed to retrieve actual key" << dendl;
s->err.message = "Failed to retrieve the actual key";
return res;
}
if (actual_key.size() != AES_256_KEYSIZE) {
ldpp_dout(s, 0) << "ERROR: key obtained " <<
"is not 256 bit size" << dendl;
s->err.message = "SSE-S3 provided an invalid key for the given keyid.";
return -EINVAL;
}
auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct));
aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE);
actual_key.replace(0, actual_key.length(), actual_key.length(), '\000');
if (block_crypt) *block_crypt = std::move(aes);
crypt_http_responses["x-amz-server-side-encryption"] = "AES256";
return 0;
}
/*no decryption*/
return 0;
}
int rgw_remove_sse_s3_bucket_key(req_state *s)
{
int res;
auto key_id { expand_key_name(s, s->cct->_conf->rgw_crypt_sse_s3_key_template) };
auto saved_key { fetch_bucket_key_id(s) };
size_t i;
if (key_id == cant_expand_key) {
ldpp_dout(s, 5) << "ERROR: unable to expand key_id " <<
s->cct->_conf->rgw_crypt_sse_s3_key_template << " on bucket" << dendl;
s->err.message = "Server side error - unable to expand key_id";
return -EINVAL;
}
if (saved_key == "") {
return 0;
} else if (saved_key != key_id) {
ldpp_dout(s, 5) << "Found but will not delete strange KEK ID: " << saved_key << dendl;
return 0;
}
i = s->cct->_conf->rgw_crypt_sse_s3_key_template.find("%bucket_id");
if (i == std::string_view::npos) {
ldpp_dout(s, 5) << "Kept valid KEK ID: " << saved_key << dendl;
return 0;
}
ldpp_dout(s, 5) << "Removing valid KEK ID: " << saved_key << dendl;
res = remove_sse_s3_bucket_key(s, s->cct, saved_key);
if (res != 0) {
ldpp_dout(s, 0) << "ERROR: Unable to remove KEK ID: " << saved_key << " got " << res << dendl;
}
return res;
}
/*********************************************************************
* "BOTTOM OF FILE"
* I've left some commented out lines above. They are there for
* a reason, which I will explain. The "canonical" json constructed
* by the code above as a crypto context must take a json object and
* turn it into a unique determinstic fixed form. For most json
* types this is easy. The hardest problem that is handled above is
* detailing with unicode strings; they must be turned into
* NFC form and sorted in a fixed order. Numbers, however,
* are another story. Json makes no distinction between integers
* and floating point, and both types have their problems.
* Integers can overflow, so very large numbers are a problem.
* Floating point is even worse; not all floating point numbers
* can be represented accurately in c++ data types, and there
* are many quirks regarding how overflow, underflow, and loss
* of significance are handled.
*
* In this version of the code, I took the simplest answer, I
* reject all numbers altogether. This is not ideal, but it's
* the only choice that is guaranteed to be future compatible.
* AWS S3 does not guarantee to support numbers at all; but it
* actually converts all numbers into strings right off.
* This has the interesting property that 7 and 007 are different,
* but that 007 and "007" are the same. I would rather
* treat numbers as a string of digits and have logic
* to produce the "most compact" equivalent form. This can
* fix all the overflow/underflow problems, but it requires
* fixing the json parser part, and I put that problem off.
*
* The commented code above indicates places in this code that
* will need to be revised depending on future work in this area.
* Removing those comments makes that work harder.
* February 25, 2021
*********************************************************************/
| 57,311 | 35.434838 | 157 |
cc
|
null |
ceph-main/src/rgw/rgw_crypt.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/**
* Crypto filters for Put/Post/Get operations.
*/
#pragma once
#include <string_view>
#include <rgw/rgw_op.h>
#include <rgw/rgw_rest.h>
#include <rgw/rgw_rest_s3.h>
#include "rgw_putobj.h"
#include "common/async/yield_context.h"
/**
* \brief Interface for block encryption methods
*
* Encrypts and decrypts data.
* Operations are performed in context of larger stream being divided into blocks.
* Each block can be processed independently, but only as a whole.
* Part block cannot be properly processed.
* Each request must start on block-aligned offset.
* Each request should have length that is multiply of block size.
* Request with unaligned length is only acceptable for last part of stream.
*/
class BlockCrypt {
public:
BlockCrypt(){};
virtual ~BlockCrypt(){};
/**
* Determines size of encryption block.
* This is usually multiply of key size.
* It determines size of chunks that should be passed to \ref encrypt and \ref decrypt.
*/
virtual size_t get_block_size() = 0;
/**
* Encrypts data.
* Argument \ref stream_offset shows where in generalized stream chunk is located.
* Input for encryption is \ref input buffer, with relevant data in range <in_ofs, in_ofs+size).
* \ref input and \output may not be the same buffer.
*
* \params
* input - source buffer of data
* in_ofs - offset of chunk inside input
* size - size of chunk, must be chunk-aligned unless last part is processed
* output - destination buffer to encrypt to
* stream_offset - location of <in_ofs,in_ofs+size) chunk in data stream, must be chunk-aligned
* \return true iff successfully encrypted
*/
virtual bool encrypt(bufferlist& input,
off_t in_ofs,
size_t size,
bufferlist& output,
off_t stream_offset,
optional_yield y) = 0;
/**
* Decrypts data.
* Argument \ref stream_offset shows where in generalized stream chunk is located.
* Input for decryption is \ref input buffer, with relevant data in range <in_ofs, in_ofs+size).
* \ref input and \output may not be the same buffer.
*
* \params
* input - source buffer of data
* in_ofs - offset of chunk inside input
* size - size of chunk, must be chunk-aligned unless last part is processed
* output - destination buffer to encrypt to
* stream_offset - location of <in_ofs,in_ofs+size) chunk in data stream, must be chunk-aligned
* \return true iff successfully encrypted
*/
virtual bool decrypt(bufferlist& input,
off_t in_ofs,
size_t size,
bufferlist& output,
off_t stream_offset,
optional_yield y) = 0;
};
static const size_t AES_256_KEYSIZE = 256 / 8;
bool AES_256_ECB_encrypt(const DoutPrefixProvider* dpp,
CephContext* cct,
const uint8_t* key,
size_t key_size,
const uint8_t* data_in,
uint8_t* data_out,
size_t data_size);
class RGWGetObj_BlockDecrypt : public RGWGetObj_Filter {
const DoutPrefixProvider *dpp;
CephContext* cct;
std::unique_ptr<BlockCrypt> crypt; /**< already configured stateless BlockCrypt
for operations when enough data is accumulated */
off_t enc_begin_skip; /**< amount of data to skip from beginning of received data */
off_t ofs; /**< stream offset of data we expect to show up next through \ref handle_data */
off_t end; /**< stream offset of last byte that is requested */
bufferlist cache; /**< stores extra data that could not (yet) be processed by BlockCrypt */
size_t block_size; /**< snapshot of \ref BlockCrypt.get_block_size() */
optional_yield y;
int process(bufferlist& cipher, size_t part_ofs, size_t size);
protected:
std::vector<size_t> parts_len; /**< size of parts of multipart object, parsed from manifest */
public:
RGWGetObj_BlockDecrypt(const DoutPrefixProvider *dpp,
CephContext* cct,
RGWGetObj_Filter* next,
std::unique_ptr<BlockCrypt> crypt,
optional_yield y);
virtual ~RGWGetObj_BlockDecrypt();
virtual int fixup_range(off_t& bl_ofs,
off_t& bl_end) override;
virtual int handle_data(bufferlist& bl,
off_t bl_ofs,
off_t bl_len) override;
virtual int flush() override;
int read_manifest(const DoutPrefixProvider *dpp, bufferlist& manifest_bl);
}; /* RGWGetObj_BlockDecrypt */
class RGWPutObj_BlockEncrypt : public rgw::putobj::Pipe
{
const DoutPrefixProvider *dpp;
CephContext* cct;
std::unique_ptr<BlockCrypt> crypt; /**< already configured stateless BlockCrypt
for operations when enough data is accumulated */
bufferlist cache; /**< stores extra data that could not (yet) be processed by BlockCrypt */
const size_t block_size; /**< snapshot of \ref BlockCrypt.get_block_size() */
optional_yield y;
public:
RGWPutObj_BlockEncrypt(const DoutPrefixProvider *dpp,
CephContext* cct,
rgw::sal::DataProcessor *next,
std::unique_ptr<BlockCrypt> crypt,
optional_yield y);
int process(bufferlist&& data, uint64_t logical_offset) override;
}; /* RGWPutObj_BlockEncrypt */
int rgw_s3_prepare_encrypt(req_state* s,
std::map<std::string, ceph::bufferlist>& attrs,
std::unique_ptr<BlockCrypt>* block_crypt,
std::map<std::string,
std::string>& crypt_http_responses);
int rgw_s3_prepare_decrypt(req_state* s,
std::map<std::string, ceph::bufferlist>& attrs,
std::unique_ptr<BlockCrypt>* block_crypt,
std::map<std::string,
std::string>& crypt_http_responses);
static inline void set_attr(std::map<std::string, bufferlist>& attrs,
const char* key,
std::string_view value)
{
bufferlist bl;
bl.append(value.data(), value.size());
attrs[key] = std::move(bl);
}
static inline std::string get_str_attribute(std::map<std::string, bufferlist>& attrs,
const char *name)
{
auto iter = attrs.find(name);
if (iter == attrs.end()) {
return {};
}
return iter->second.to_str();
}
int rgw_remove_sse_s3_bucket_key(req_state *s);
| 6,873 | 37.188889 | 98 |
h
|
null |
ceph-main/src/rgw/rgw_crypt_sanitize.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* rgw_crypt_sanitize.cc
*
* Created on: Mar 3, 2017
* Author: adam
*/
#include "rgw_common.h"
#include "rgw_crypt_sanitize.h"
#include "boost/algorithm/string/predicate.hpp"
namespace rgw {
namespace crypt_sanitize {
const char* HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY = "HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY";
const char* x_amz_server_side_encryption_customer_key = "x-amz-server-side-encryption-customer-key";
const char* dollar_x_amz_server_side_encryption_customer_key = "$x-amz-server-side-encryption-customer-key";
const char* suppression_message = "=suppressed due to key presence=";
std::ostream& operator<<(std::ostream& out, const env& e) {
if (g_ceph_context->_conf->rgw_crypt_suppress_logs) {
if (boost::algorithm::iequals(
e.name,
HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY))
{
out << suppression_message;
return out;
}
if (boost::algorithm::iequals(e.name, "QUERY_STRING") &&
boost::algorithm::ifind_first(
e.value,
x_amz_server_side_encryption_customer_key))
{
out << suppression_message;
return out;
}
}
out << e.value;
return out;
}
std::ostream& operator<<(std::ostream& out, const x_meta_map& x) {
if (g_ceph_context->_conf->rgw_crypt_suppress_logs &&
boost::algorithm::iequals(x.name, x_amz_server_side_encryption_customer_key))
{
out << suppression_message;
return out;
}
out << x.value;
return out;
}
std::ostream& operator<<(std::ostream& out, const s3_policy& x) {
if (g_ceph_context->_conf->rgw_crypt_suppress_logs &&
boost::algorithm::iequals(x.name, dollar_x_amz_server_side_encryption_customer_key))
{
out << suppression_message;
return out;
}
out << x.value;
return out;
}
std::ostream& operator<<(std::ostream& out, const auth& x) {
if (g_ceph_context->_conf->rgw_crypt_suppress_logs &&
x.s->info.env->get(HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, nullptr) != nullptr)
{
out << suppression_message;
return out;
}
out << x.value;
return out;
}
std::ostream& operator<<(std::ostream& out, const log_content& x) {
if (g_ceph_context->_conf->rgw_crypt_suppress_logs &&
boost::algorithm::ifind_first(x.buf, x_amz_server_side_encryption_customer_key)) {
out << suppression_message;
return out;
}
out << x.buf;
return out;
}
}
}
| 2,505 | 27.157303 | 110 |
cc
|
null |
ceph-main/src/rgw/rgw_crypt_sanitize.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string_view>
#include "rgw_common.h"
namespace rgw {
namespace crypt_sanitize {
/*
* Temporary container for suppressing printing if variable contains secret key.
*/
struct env {
std::string_view name;
std::string_view value;
env(std::string_view name, std::string_view value)
: name(name), value(value) {}
};
/*
* Temporary container for suppressing printing if aws meta attributes contains secret key.
*/
struct x_meta_map {
std::string_view name;
std::string_view value;
x_meta_map(std::string_view name, std::string_view value)
: name(name), value(value) {}
};
/*
* Temporary container for suppressing printing if s3_policy calculation variable contains secret key.
*/
struct s3_policy {
std::string_view name;
std::string_view value;
s3_policy(std::string_view name, std::string_view value)
: name(name), value(value) {}
};
/*
* Temporary container for suppressing printing if auth string contains secret key.
*/
struct auth {
const req_state* const s;
std::string_view value;
auth(const req_state* const s, std::string_view value)
: s(s), value(value) {}
};
/*
* Temporary container for suppressing printing if log made from civetweb may contain secret key.
*/
struct log_content {
const std::string_view buf;
explicit log_content(const std::string_view buf)
: buf(buf) {}
};
std::ostream& operator<<(std::ostream& out, const env& e);
std::ostream& operator<<(std::ostream& out, const x_meta_map& x);
std::ostream& operator<<(std::ostream& out, const s3_policy& x);
std::ostream& operator<<(std::ostream& out, const auth& x);
std::ostream& operator<<(std::ostream& out, const log_content& x);
}
}
| 1,789 | 24.942029 | 102 |
h
|
null |
ceph-main/src/rgw/rgw_d3n_cacherequest.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <fcntl.h>
#include <stdlib.h>
#include <aio.h>
#include "include/rados/librados.hpp"
#include "include/Context.h"
#include "common/async/completion.h"
#include <errno.h>
#include "common/error_code.h"
#include "common/errno.h"
#include "rgw_aio.h"
#include "rgw_cache.h"
struct D3nGetObjData {
std::mutex d3n_lock;
};
struct D3nL1CacheRequest {
~D3nL1CacheRequest() {
lsubdout(g_ceph_context, rgw_datacache, 30) << "D3nDataCache: " << __func__ << "(): Read From Cache, complete" << dendl;
}
// unique_ptr with custom deleter for struct aiocb
struct libaio_aiocb_deleter {
void operator()(struct aiocb* c) {
if(c->aio_fildes > 0) {
if( ::close(c->aio_fildes) != 0) {
lsubdout(g_ceph_context, rgw_datacache, 2) << "D3nDataCache: " << __func__ << "(): Error - can't close file, errno=" << -errno << dendl;
}
}
delete c;
}
};
using unique_aio_cb_ptr = std::unique_ptr<struct aiocb, libaio_aiocb_deleter>;
struct AsyncFileReadOp {
bufferlist result;
unique_aio_cb_ptr aio_cb;
using Signature = void(boost::system::error_code, bufferlist);
using Completion = ceph::async::Completion<Signature, AsyncFileReadOp>;
int init_async_read(const DoutPrefixProvider *dpp, const std::string& location, off_t read_ofs, off_t read_len, void* arg) {
ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): location=" << location << dendl;
aio_cb.reset(new struct aiocb);
memset(aio_cb.get(), 0, sizeof(struct aiocb));
aio_cb->aio_fildes = TEMP_FAILURE_RETRY(::open(location.c_str(), O_RDONLY|O_CLOEXEC|O_BINARY));
if(aio_cb->aio_fildes < 0) {
int err = errno;
ldpp_dout(dpp, 1) << "ERROR: D3nDataCache: " << __func__ << "(): can't open " << location << " : " << cpp_strerror(err) << dendl;
return -err;
}
if (g_conf()->rgw_d3n_l1_fadvise != POSIX_FADV_NORMAL)
posix_fadvise(aio_cb->aio_fildes, 0, 0, g_conf()->rgw_d3n_l1_fadvise);
bufferptr bp(read_len);
aio_cb->aio_buf = bp.c_str();
result.append(std::move(bp));
aio_cb->aio_nbytes = read_len;
aio_cb->aio_offset = read_ofs;
aio_cb->aio_sigevent.sigev_notify = SIGEV_THREAD;
aio_cb->aio_sigevent.sigev_notify_function = libaio_cb_aio_dispatch;
aio_cb->aio_sigevent.sigev_notify_attributes = nullptr;
aio_cb->aio_sigevent.sigev_value.sival_ptr = arg;
return 0;
}
static void libaio_cb_aio_dispatch(sigval sigval) {
lsubdout(g_ceph_context, rgw_datacache, 20) << "D3nDataCache: " << __func__ << "()" << dendl;
auto p = std::unique_ptr<Completion>{static_cast<Completion*>(sigval.sival_ptr)};
auto op = std::move(p->user_data);
const int ret = -aio_error(op.aio_cb.get());
boost::system::error_code ec;
if (ret < 0) {
ec.assign(-ret, boost::system::system_category());
}
ceph::async::dispatch(std::move(p), ec, std::move(op.result));
}
template <typename Executor1, typename CompletionHandler>
static auto create(const Executor1& ex1, CompletionHandler&& handler) {
auto p = Completion::create(ex1, std::move(handler));
return p;
}
};
template <typename ExecutionContext, typename CompletionToken>
auto async_read(const DoutPrefixProvider *dpp, ExecutionContext& ctx, const std::string& location,
off_t read_ofs, off_t read_len, CompletionToken&& token) {
using Op = AsyncFileReadOp;
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;
ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): location=" << location << dendl;
int ret = op.init_async_read(dpp, location, read_ofs, read_len, p.get());
if(0 == ret) {
ret = ::aio_read(op.aio_cb.get());
}
ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): ::aio_read(), ret=" << ret << dendl;
if(ret < 0) {
auto ec = boost::system::error_code{-ret, boost::system::system_category()};
ceph::async::post(std::move(p), ec, bufferlist{});
} else {
// coverity[leaked_storage:SUPPRESS]
(void)p.release();
}
return init.result.get();
}
struct d3n_libaio_handler {
rgw::Aio* throttle = nullptr;
rgw::AioResult& r;
// read callback
void operator()(boost::system::error_code ec, bufferlist bl) const {
r.result = -ec.value();
r.data = std::move(bl);
throttle->put(r);
}
};
void file_aio_read_abstract(const DoutPrefixProvider *dpp, boost::asio::io_context& context, yield_context yield,
std::string& cache_location, off_t read_ofs, off_t read_len,
rgw::Aio* aio, rgw::AioResult& r) {
using namespace boost::asio;
async_completion<yield_context, void()> init(yield);
auto ex = get_associated_executor(init.completion_handler);
ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): oid=" << r.obj.oid << dendl;
async_read(dpp, context, cache_location+"/"+url_encode(r.obj.oid, true), read_ofs, read_len, bind_executor(ex, d3n_libaio_handler{aio, r}));
}
};
| 5,402 | 36.006849 | 146 |
h
|
null |
ceph-main/src/rgw/rgw_dencoder.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_common.h"
#include "rgw_rados.h"
#include "rgw_zone.h"
#include "rgw_log.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_cache.h"
#include "rgw_meta_sync_status.h"
#include "rgw_data_sync.h"
#include "rgw_multi.h"
#include "rgw_bucket_encryption.h"
#include "common/Formatter.h"
using namespace std;
static string shadow_ns = RGW_OBJ_NS_SHADOW;
void obj_version::generate_test_instances(list<obj_version*>& o)
{
obj_version *v = new obj_version;
v->ver = 5;
v->tag = "tag";
o.push_back(v);
o.push_back(new obj_version);
}
void RGWBucketEncryptionConfig::generate_test_instances(std::list<RGWBucketEncryptionConfig*>& o)
{
auto *bc = new RGWBucketEncryptionConfig("aws:kms", "some:key", true);
o.push_back(bc);
bc = new RGWBucketEncryptionConfig("AES256");
o.push_back(bc);
o.push_back(new RGWBucketEncryptionConfig);
}
| 981 | 22.380952 | 97 |
cc
|
null |
ceph-main/src/rgw/rgw_dmclock.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
* 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.
*
*/
#pragma once
#include "dmclock/src/dmclock_server.h"
namespace rgw::dmclock {
// TODO: implement read vs write
enum class client_id {
admin, //< /admin apis
auth, //< swift auth, sts
data, //< PutObj, GetObj
metadata, //< bucket operations, object metadata
count
};
// TODO move these to dmclock/types or so in submodule
using crimson::dmclock::Cost;
using crimson::dmclock::ClientInfo;
enum class scheduler_t {
none,
throttler,
dmclock
};
inline scheduler_t get_scheduler_t(CephContext* const cct)
{
const auto scheduler_type = cct->_conf.get_val<std::string>("rgw_scheduler_type");
if (scheduler_type == "dmclock")
return scheduler_t::dmclock;
else if (scheduler_type == "throttler")
return scheduler_t::throttler;
else
return scheduler_t::none;
}
} // namespace rgw::dmclock
| 1,430 | 26 | 84 |
h
|
null |
ceph-main/src/rgw/rgw_dmclock_async_scheduler.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "common/async/completion.h"
#include "rgw_dmclock_async_scheduler.h"
#include "rgw_dmclock_scheduler.h"
namespace rgw::dmclock {
AsyncScheduler::~AsyncScheduler()
{
cancel();
if (observer) {
cct->_conf.remove_observer(this);
}
}
const char** AsyncScheduler::get_tracked_conf_keys() const
{
if (observer) {
return observer->get_tracked_conf_keys();
}
static const char* keys[] = { "rgw_max_concurrent_requests", nullptr };
return keys;
}
void AsyncScheduler::handle_conf_change(const ConfigProxy& conf,
const std::set<std::string>& changed)
{
if (observer) {
observer->handle_conf_change(conf, changed);
}
if (changed.count("rgw_max_concurrent_requests")) {
auto new_max = conf.get_val<int64_t>("rgw_max_concurrent_requests");
max_requests = new_max > 0 ? new_max : std::numeric_limits<int64_t>::max();
}
queue.update_client_infos();
schedule(crimson::dmclock::TimeZero);
}
int AsyncScheduler::schedule_request_impl(const client_id& client,
const ReqParams& params,
const Time& time, const Cost& cost,
optional_yield yield_ctx)
{
ceph_assert(yield_ctx);
auto &yield = yield_ctx.get_yield_context();
boost::system::error_code ec;
async_request(client, params, time, cost, yield[ec]);
if (ec){
if (ec == boost::system::errc::resource_unavailable_try_again)
return -EAGAIN;
else
return -ec.value();
}
return 0;
}
void AsyncScheduler::request_complete()
{
--outstanding_requests;
if(auto c = counters(client_id::count)){
c->inc(throttle_counters::l_outstanding, -1);
}
schedule(crimson::dmclock::TimeZero);
}
void AsyncScheduler::cancel()
{
ClientSums sums;
queue.remove_by_req_filter([&] (RequestRef&& request) {
inc(sums, request->client, request->cost);
auto c = static_cast<Completion*>(request.release());
Completion::dispatch(std::unique_ptr<Completion>{c},
boost::asio::error::operation_aborted,
PhaseType::priority);
return true;
});
timer.cancel();
for (size_t i = 0; i < client_count; i++) {
if (auto c = counters(static_cast<client_id>(i))) {
on_cancel(c, sums[i]);
}
}
}
void AsyncScheduler::cancel(const client_id& client)
{
ClientSum sum;
queue.remove_by_client(client, false, [&] (RequestRef&& request) {
sum.count++;
sum.cost += request->cost;
auto c = static_cast<Completion*>(request.release());
Completion::dispatch(std::unique_ptr<Completion>{c},
boost::asio::error::operation_aborted,
PhaseType::priority);
});
if (auto c = counters(client)) {
on_cancel(c, sum);
}
schedule(crimson::dmclock::TimeZero);
}
void AsyncScheduler::schedule(const Time& time)
{
timer.expires_at(Clock::from_double(time));
timer.async_wait([this] (boost::system::error_code ec) {
// process requests unless the wait was canceled. note that a canceled
// wait may execute after this AsyncScheduler destructs
if (ec != boost::asio::error::operation_aborted) {
process(get_time());
}
});
}
void AsyncScheduler::process(const Time& now)
{
// must run in the executor. we should only invoke completion handlers if the
// executor is running
assert(get_executor().running_in_this_thread());
ClientSums rsums, psums;
while (outstanding_requests < max_requests) {
auto pull = queue.pull_request(now);
if (pull.is_none()) {
// no pending requests, cancel the timer
timer.cancel();
break;
}
if (pull.is_future()) {
// update the timer based on the future time
schedule(pull.getTime());
break;
}
++outstanding_requests;
if(auto c = counters(client_id::count)){
c->inc(throttle_counters::l_outstanding);
}
// complete the request
auto& r = pull.get_retn();
auto client = r.client;
auto phase = r.phase;
auto started = r.request->started;
auto cost = r.request->cost;
auto c = static_cast<Completion*>(r.request.release());
Completion::post(std::unique_ptr<Completion>{c},
boost::system::error_code{}, phase);
if (auto c = counters(client)) {
auto lat = Clock::from_double(now) - Clock::from_double(started);
if (phase == PhaseType::reservation) {
inc(rsums, client, cost);
c->tinc(queue_counters::l_res_latency, lat);
} else {
inc(psums, client, cost);
c->tinc(queue_counters::l_prio_latency, lat);
}
}
}
if (outstanding_requests >= max_requests) {
if(auto c = counters(client_id::count)){
c->inc(throttle_counters::l_throttle);
}
}
for (size_t i = 0; i < client_count; i++) {
if (auto c = counters(static_cast<client_id>(i))) {
on_process(c, rsums[i], psums[i]);
}
}
}
} // namespace rgw::dmclock
| 5,178 | 27.146739 | 79 |
cc
|
null |
ceph-main/src/rgw/rgw_dmclock_async_scheduler.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 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.
*
*/
#pragma once
#include "common/async/completion.h"
#include <boost/asio.hpp>
#include "rgw_dmclock_scheduler.h"
#include "rgw_dmclock_scheduler_ctx.h"
namespace rgw::dmclock {
namespace async = ceph::async;
/*
* A dmclock request scheduling service for use with boost::asio.
*
* An asynchronous dmclock priority queue, where scheduled requests complete
* on a boost::asio executor.
*/
class AsyncScheduler : public md_config_obs_t, public Scheduler {
public:
template <typename ...Args> // args forwarded to PullPriorityQueue ctor
AsyncScheduler(CephContext *cct, boost::asio::io_context& context,
GetClientCounters&& counters, md_config_obs_t *observer,
Args&& ...args);
~AsyncScheduler();
using executor_type = boost::asio::io_context::executor_type;
/// return the default executor for async_request() callbacks
executor_type get_executor() noexcept {
return timer.get_executor();
}
/// submit an async request for dmclock scheduling. the given completion
/// handler will be invoked with (error_code, PhaseType) when the request
/// is ready or canceled. on success, this grants a throttle unit that must
/// be returned with a call to request_complete()
template <typename CompletionToken>
auto async_request(const client_id& client, const ReqParams& params,
const Time& time, Cost cost, CompletionToken&& token);
/// returns a throttle unit granted by async_request()
void request_complete() override;
/// cancel all queued requests, invoking their completion handlers with an
/// operation_aborted error and default-constructed result
void cancel();
/// cancel all queued requests for a given client, invoking their completion
/// handler with an operation_aborted error and default-constructed result
void cancel(const client_id& client);
const char** get_tracked_conf_keys() const override;
void handle_conf_change(const ConfigProxy& conf,
const std::set<std::string>& changed) override;
private:
int schedule_request_impl(const client_id& client, const ReqParams& params,
const Time& time, const Cost& cost,
optional_yield yield_ctx) override;
static constexpr bool IsDelayed = false;
using Queue = crimson::dmclock::PullPriorityQueue<client_id, Request, IsDelayed>;
using RequestRef = typename Queue::RequestRef;
Queue queue; //< dmclock priority queue
using Signature = void(boost::system::error_code, PhaseType);
using Completion = async::Completion<Signature, async::AsBase<Request>>;
using Clock = ceph::coarse_real_clock;
using Timer = boost::asio::basic_waitable_timer<Clock,
boost::asio::wait_traits<Clock>, executor_type>;
Timer timer; //< timer for the next scheduled request
CephContext *const cct;
md_config_obs_t *const observer; //< observer to update ClientInfoFunc
GetClientCounters counters; //< provides per-client perf counters
/// max request throttle
std::atomic<int64_t> max_requests;
std::atomic<int64_t> outstanding_requests = 0;
/// set a timer to process the next request
void schedule(const Time& time);
/// process ready requests, then schedule the next pending request
void process(const Time& now);
};
template <typename ...Args>
AsyncScheduler::AsyncScheduler(CephContext *cct, boost::asio::io_context& context,
GetClientCounters&& counters,
md_config_obs_t *observer, Args&& ...args)
: queue(std::forward<Args>(args)...),
timer(context), cct(cct), observer(observer),
counters(std::move(counters)),
max_requests(cct->_conf.get_val<int64_t>("rgw_max_concurrent_requests"))
{
if (max_requests <= 0) {
max_requests = std::numeric_limits<int64_t>::max();
}
if (observer) {
cct->_conf.add_observer(this);
}
}
template <typename CompletionToken>
auto AsyncScheduler::async_request(const client_id& client,
const ReqParams& params,
const Time& time, Cost cost,
CompletionToken&& token)
{
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto ex1 = get_executor();
auto& handler = init.completion_handler;
// allocate the Request and add it to the queue
auto completion = Completion::create(ex1, std::move(handler),
Request{client, time, cost});
// cast to unique_ptr<Request>
auto req = RequestRef{std::move(completion)};
int r = queue.add_request(std::move(req), client, params, time, cost);
if (r == 0) {
// schedule an immediate call to process() on the executor
schedule(crimson::dmclock::TimeZero);
if (auto c = counters(client)) {
c->inc(queue_counters::l_qlen);
c->inc(queue_counters::l_cost, cost);
}
} else {
// post the error code
boost::system::error_code ec(r, boost::system::system_category());
// cast back to Completion
auto completion = static_cast<Completion*>(req.release());
async::post(std::unique_ptr<Completion>{completion},
ec, PhaseType::priority);
if (auto c = counters(client)) {
c->inc(queue_counters::l_limit);
c->inc(queue_counters::l_limit_cost, cost);
}
}
return init.result.get();
}
class SimpleThrottler : public md_config_obs_t, public dmclock::Scheduler {
public:
SimpleThrottler(CephContext *cct) :
max_requests(cct->_conf.get_val<int64_t>("rgw_max_concurrent_requests")),
counters(cct, "simple-throttler")
{
if (max_requests <= 0) {
max_requests = std::numeric_limits<int64_t>::max();
}
cct->_conf.add_observer(this);
}
const char** get_tracked_conf_keys() const override {
static const char* keys[] = { "rgw_max_concurrent_requests", nullptr };
return keys;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set<std::string>& changed) override
{
if (changed.count("rgw_max_concurrent_requests")) {
auto new_max = conf.get_val<int64_t>("rgw_max_concurrent_requests");
max_requests = new_max > 0 ? new_max : std::numeric_limits<int64_t>::max();
}
}
void request_complete() override {
--outstanding_requests;
if (auto c = counters();
c != nullptr) {
c->inc(throttle_counters::l_outstanding, -1);
}
}
private:
int schedule_request_impl(const client_id&, const ReqParams&,
const Time&, const Cost&,
optional_yield) override {
if (outstanding_requests++ >= max_requests) {
if (auto c = counters();
c != nullptr) {
c->inc(throttle_counters::l_outstanding);
c->inc(throttle_counters::l_throttle);
}
return -EAGAIN;
}
return 0 ;
}
std::atomic<int64_t> max_requests;
std::atomic<int64_t> outstanding_requests = 0;
ThrottleCounters counters;
};
} // namespace rgw::dmclock
| 7,424 | 33.059633 | 83 |
h
|
null |
ceph-main/src/rgw/rgw_dmclock_scheduler.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
* (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.
*
*/
#pragma once
#include "common/ceph_time.h"
#include "common/ceph_context.h"
#include "common/config.h"
#include "common/async/yield_context.h"
#include "rgw_dmclock.h"
namespace rgw::dmclock {
using crimson::dmclock::ReqParams;
using crimson::dmclock::PhaseType;
using crimson::dmclock::AtLimit;
using crimson::dmclock::Time;
using crimson::dmclock::get_time;
/// function to provide client counters
using GetClientCounters = std::function<PerfCounters*(client_id)>;
struct Request {
client_id client;
Time started;
Cost cost;
};
enum class ReqState {
Wait,
Ready,
Cancelled
};
template <typename F>
class Completer {
public:
Completer(F &&f): f(std::move(f)) {}
// Default constructor is needed as we need to create an empty completer
// that'll be move assigned later in process request
Completer() = default;
~Completer() {
if (f) {
f();
}
}
Completer(const Completer&) = delete;
Completer& operator=(const Completer&) = delete;
Completer(Completer&& other) = default;
Completer& operator=(Completer&& other) = default;
private:
F f;
};
using SchedulerCompleter = Completer<std::function<void()>>;
class Scheduler {
public:
auto schedule_request(const client_id& client, const ReqParams& params,
const Time& time, const Cost& cost,
optional_yield yield)
{
int r = schedule_request_impl(client,params,time,cost,yield);
return std::make_pair(r,SchedulerCompleter(std::bind(&Scheduler::request_complete,this)));
}
virtual void request_complete() {};
virtual ~Scheduler() {};
private:
virtual int schedule_request_impl(const client_id&, const ReqParams&,
const Time&, const Cost&,
optional_yield) = 0;
};
} // namespace rgw::dmclock
| 2,173 | 23.988506 | 94 |
h
|
null |
ceph-main/src/rgw/rgw_dmclock_scheduler_ctx.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
* (C) 2019 SUSE Linux LLC
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "rgw_dmclock_scheduler_ctx.h"
namespace rgw::dmclock {
ClientConfig::ClientConfig(CephContext *cct)
{
update(cct->_conf);
}
ClientInfo* ClientConfig::operator()(client_id client)
{
return &clients[static_cast<size_t>(client)];
}
const char** ClientConfig::get_tracked_conf_keys() const
{
static const char* keys[] = {
"rgw_dmclock_admin_res",
"rgw_dmclock_admin_wgt",
"rgw_dmclock_admin_lim",
"rgw_dmclock_auth_res",
"rgw_dmclock_auth_wgt",
"rgw_dmclock_auth_lim",
"rgw_dmclock_data_res",
"rgw_dmclock_data_wgt",
"rgw_dmclock_data_lim",
"rgw_dmclock_metadata_res",
"rgw_dmclock_metadata_wgt",
"rgw_dmclock_metadata_lim",
"rgw_max_concurrent_requests",
nullptr
};
return keys;
}
void ClientConfig::update(const ConfigProxy& conf)
{
clients.clear();
static_assert(0 == static_cast<int>(client_id::admin));
clients.emplace_back(conf.get_val<double>("rgw_dmclock_admin_res"),
conf.get_val<double>("rgw_dmclock_admin_wgt"),
conf.get_val<double>("rgw_dmclock_admin_lim"));
static_assert(1 == static_cast<int>(client_id::auth));
clients.emplace_back(conf.get_val<double>("rgw_dmclock_auth_res"),
conf.get_val<double>("rgw_dmclock_auth_wgt"),
conf.get_val<double>("rgw_dmclock_auth_lim"));
static_assert(2 == static_cast<int>(client_id::data));
clients.emplace_back(conf.get_val<double>("rgw_dmclock_data_res"),
conf.get_val<double>("rgw_dmclock_data_wgt"),
conf.get_val<double>("rgw_dmclock_data_lim"));
static_assert(3 == static_cast<int>(client_id::metadata));
clients.emplace_back(conf.get_val<double>("rgw_dmclock_metadata_res"),
conf.get_val<double>("rgw_dmclock_metadata_wgt"),
conf.get_val<double>("rgw_dmclock_metadata_lim"));
}
void ClientConfig::handle_conf_change(const ConfigProxy& conf,
const std::set<std::string>& changed)
{
update(conf);
}
ClientCounters::ClientCounters(CephContext *cct)
{
clients[static_cast<size_t>(client_id::admin)] =
queue_counters::build(cct, "dmclock-admin");
clients[static_cast<size_t>(client_id::auth)] =
queue_counters::build(cct, "dmclock-auth");
clients[static_cast<size_t>(client_id::data)] =
queue_counters::build(cct, "dmclock-data");
clients[static_cast<size_t>(client_id::metadata)] =
queue_counters::build(cct, "dmclock-metadata");
clients[static_cast<size_t>(client_id::count)] =
throttle_counters::build(cct, "dmclock-scheduler");
}
void inc(ClientSums& sums, client_id client, Cost cost)
{
auto& sum = sums[static_cast<size_t>(client)];
sum.count++;
sum.cost += cost;
}
void on_cancel(PerfCounters *c, const ClientSum& sum)
{
if (sum.count) {
c->dec(queue_counters::l_qlen, sum.count);
c->inc(queue_counters::l_cancel, sum.count);
}
if (sum.cost) {
c->dec(queue_counters::l_cost, sum.cost);
c->inc(queue_counters::l_cancel_cost, sum.cost);
}
}
void on_process(PerfCounters* c, const ClientSum& rsum, const ClientSum& psum)
{
if (rsum.count) {
c->inc(queue_counters::l_res, rsum.count);
}
if (rsum.cost) {
c->inc(queue_counters::l_res_cost, rsum.cost);
}
if (psum.count) {
c->inc(queue_counters::l_prio, psum.count);
}
if (psum.cost) {
c->inc(queue_counters::l_prio_cost, psum.cost);
}
if (rsum.count + psum.count) {
c->dec(queue_counters::l_qlen, rsum.count + psum.count);
}
if (rsum.cost + psum.cost) {
c->dec(queue_counters::l_cost, rsum.cost + psum.cost);
}
}
} // namespace rgw::dmclock
namespace queue_counters {
PerfCountersRef build(CephContext *cct, const std::string& name)
{
if (!cct->_conf->throttler_perf_counter) {
return {};
}
PerfCountersBuilder b(cct, name, l_first, l_last);
b.add_u64(l_qlen, "qlen", "Queue size");
b.add_u64(l_cost, "cost", "Cost of queued requests");
b.add_u64_counter(l_res, "res", "Requests satisfied by reservation");
b.add_u64_counter(l_res_cost, "res_cost", "Cost satisfied by reservation");
b.add_u64_counter(l_prio, "prio", "Requests satisfied by priority");
b.add_u64_counter(l_prio_cost, "prio_cost", "Cost satisfied by priority");
b.add_u64_counter(l_limit, "limit", "Requests rejected by limit");
b.add_u64_counter(l_limit_cost, "limit_cost", "Cost rejected by limit");
b.add_u64_counter(l_cancel, "cancel", "Cancels");
b.add_u64_counter(l_cancel_cost, "cancel_cost", "Canceled cost");
b.add_time_avg(l_res_latency, "res latency", "Reservation latency");
b.add_time_avg(l_prio_latency, "prio latency", "Priority latency");
auto logger = PerfCountersRef{ b.create_perf_counters(), cct };
cct->get_perfcounters_collection()->add(logger.get());
return logger;
}
} // namespace queue_counters
namespace throttle_counters {
PerfCountersRef build(CephContext *cct, const std::string& name)
{
if (!cct->_conf->throttler_perf_counter) {
return {};
}
PerfCountersBuilder b(cct, name, l_first, l_last);
b.add_u64(l_throttle, "throttle", "Requests throttled");
b.add_u64(l_outstanding, "outstanding", "Outstanding Requests");
auto logger = PerfCountersRef{ b.create_perf_counters(), cct };
cct->get_perfcounters_collection()->add(logger.get());
return logger;
}
} // namespace throttle_counters
| 5,839 | 31.625698 | 78 |
cc
|
null |
ceph-main/src/rgw/rgw_dmclock_scheduler_ctx.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "common/perf_counters.h"
#include "common/ceph_context.h"
#include "common/config.h"
#include "rgw_dmclock.h"
namespace queue_counters {
enum {
l_first = 427150,
l_qlen,
l_cost,
l_res,
l_res_cost,
l_prio,
l_prio_cost,
l_limit,
l_limit_cost,
l_cancel,
l_cancel_cost,
l_res_latency,
l_prio_latency,
l_last,
};
PerfCountersRef build(CephContext *cct, const std::string& name);
} // namespace queue_counters
namespace throttle_counters {
enum {
l_first = 437219,
l_throttle,
l_outstanding,
l_last
};
PerfCountersRef build(CephContext *cct, const std::string& name);
} // namespace throttle
namespace rgw::dmclock {
// the last client counter would be for global scheduler stats
static constexpr auto counter_size = static_cast<size_t>(client_id::count) + 1;
/// array of per-client counters to serve as GetClientCounters
class ClientCounters {
std::array<PerfCountersRef, counter_size> clients;
public:
ClientCounters(CephContext *cct);
PerfCounters* operator()(client_id client) const {
return clients[static_cast<size_t>(client)].get();
}
};
class ThrottleCounters {
PerfCountersRef counters;
public:
ThrottleCounters(CephContext* const cct,const std::string& name):
counters(throttle_counters::build(cct, name)) {}
PerfCounters* operator()() const {
return counters.get();
}
};
struct ClientSum {
uint64_t count{0};
Cost cost{0};
};
constexpr auto client_count = static_cast<size_t>(client_id::count);
using ClientSums = std::array<ClientSum, client_count>;
void inc(ClientSums& sums, client_id client, Cost cost);
void on_cancel(PerfCounters *c, const ClientSum& sum);
void on_process(PerfCounters* c, const ClientSum& rsum, const ClientSum& psum);
class ClientConfig : public md_config_obs_t {
std::vector<ClientInfo> clients;
void update(const ConfigProxy &conf);
public:
ClientConfig(CephContext *cct);
ClientInfo* operator()(client_id client);
const char** get_tracked_conf_keys() const override;
void handle_conf_change(const ConfigProxy& conf,
const std::set<std::string>& changed) override;
};
class SchedulerCtx {
public:
SchedulerCtx(CephContext* const cct) : sched_t(get_scheduler_t(cct))
{
if(sched_t == scheduler_t::dmclock) {
dmc_client_config = std::make_shared<ClientConfig>(cct);
// we don't have a move only cref std::function yet
dmc_client_counters = std::make_optional<ClientCounters>(cct);
}
}
// We need to construct a std::function from a NonCopyable object
ClientCounters& get_dmc_client_counters() { return dmc_client_counters.value(); }
ClientConfig* const get_dmc_client_config() const { return dmc_client_config.get(); }
private:
scheduler_t sched_t;
std::shared_ptr<ClientConfig> dmc_client_config {nullptr};
std::optional<ClientCounters> dmc_client_counters {std::nullopt};
};
} // namespace rgw::dmclock
| 3,159 | 25.333333 | 87 |
h
|
null |
ceph-main/src/rgw/rgw_dmclock_sync_scheduler.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_dmclock_scheduler.h"
#include "rgw_dmclock_sync_scheduler.h"
#include "rgw_dmclock_scheduler_ctx.h"
namespace rgw::dmclock {
SyncScheduler::~SyncScheduler()
{
cancel();
}
int SyncScheduler::add_request(const client_id& client, const ReqParams& params,
const Time& time, Cost cost)
{
std::mutex req_mtx;
std::condition_variable req_cv;
ReqState rstate {ReqState::Wait};
auto req = SyncRequest{client, time, cost, req_mtx, req_cv, rstate, counters};
int r = queue.add_request_time(req, client, params, time, cost);
if (r == 0) {
if (auto c = counters(client)) {
c->inc(queue_counters::l_qlen);
c->inc(queue_counters::l_cost, cost);
}
queue.request_completed();
// Perform a blocking wait until the request callback is called
{
std::unique_lock lock{req_mtx};
req_cv.wait(lock, [&rstate] {return rstate != ReqState::Wait;});
}
if (rstate == ReqState::Cancelled) {
//FIXME: decide on error code for cancelled request
r = -ECONNABORTED;
}
} else {
// post the error code
if (auto c = counters(client)) {
c->inc(queue_counters::l_limit);
c->inc(queue_counters::l_limit_cost, cost);
}
}
return r;
}
void SyncScheduler::handle_request_cb(const client_id &c,
std::unique_ptr<SyncRequest> req,
PhaseType phase, Cost cost)
{
{ std::lock_guard<std::mutex> lg(req->req_mtx);
req->req_state = ReqState::Ready;
req->req_cv.notify_one();
}
if (auto ctr = req->counters(c)) {
auto lat = Clock::from_double(get_time()) - Clock::from_double(req->started);
if (phase == PhaseType::reservation){
ctr->tinc(queue_counters::l_res_latency, lat);
ctr->inc(queue_counters::l_res);
if (cost) ctr->inc(queue_counters::l_res_cost);
} else if (phase == PhaseType::priority){
ctr->tinc(queue_counters::l_prio_latency, lat);
ctr->inc(queue_counters::l_prio);
if (cost) ctr->inc(queue_counters::l_prio_cost);
}
ctr->dec(queue_counters::l_qlen);
if (cost) ctr->dec(queue_counters::l_cost);
}
}
void SyncScheduler::cancel(const client_id& client)
{
ClientSum sum;
queue.remove_by_client(client, false, [&](RequestRef&& request)
{
sum.count++;
sum.cost += request->cost;
{
std::lock_guard <std::mutex> lg(request->req_mtx);
request->req_state = ReqState::Cancelled;
request->req_cv.notify_one();
}
});
if (auto c = counters(client)) {
on_cancel(c, sum);
}
queue.request_completed();
}
void SyncScheduler::cancel()
{
ClientSums sums;
queue.remove_by_req_filter([&](RequestRef&& request) -> bool
{
inc(sums, request->client, request->cost);
{
std::lock_guard<std::mutex> lg(request->req_mtx);
request->req_state = ReqState::Cancelled;
request->req_cv.notify_one();
}
return true;
});
for (size_t i = 0; i < client_count; i++) {
if (auto c = counters(static_cast<client_id>(i))) {
on_cancel(c, sums[i]);
}
}
}
} // namespace rgw::dmclock
| 3,340 | 27.313559 | 81 |
cc
|
null |
ceph-main/src/rgw/rgw_dmclock_sync_scheduler.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 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.
*
*/
#pragma once
#include "rgw_dmclock_scheduler.h"
#include "rgw_dmclock_scheduler_ctx.h"
namespace rgw::dmclock {
// For a blocking SyncRequest we hold a reference to a cv and the caller must
// ensure the lifetime
struct SyncRequest : public Request {
std::mutex& req_mtx;
std::condition_variable& req_cv;
ReqState& req_state;
GetClientCounters& counters;
explicit SyncRequest(client_id _id, Time started, Cost cost,
std::mutex& mtx, std::condition_variable& _cv,
ReqState& _state, GetClientCounters& counters):
Request{_id, started, cost}, req_mtx(mtx), req_cv(_cv), req_state(_state), counters(counters) {};
};
class SyncScheduler: public Scheduler {
public:
template <typename ...Args>
SyncScheduler(CephContext *cct, GetClientCounters&& counters,
Args&& ...args);
~SyncScheduler();
// submit a blocking request for dmclock scheduling, this function waits until
// the request is ready.
int add_request(const client_id& client, const ReqParams& params,
const Time& time, Cost cost);
void cancel();
void cancel(const client_id& client);
static void handle_request_cb(const client_id& c, std::unique_ptr<SyncRequest> req,
PhaseType phase, Cost cost);
private:
int schedule_request_impl(const client_id& client, const ReqParams& params,
const Time& time, const Cost& cost,
optional_yield _y [[maybe_unused]]) override
{
return add_request(client, params, time, cost);
}
static constexpr bool IsDelayed = false;
using Queue = crimson::dmclock::PushPriorityQueue<client_id, SyncRequest, IsDelayed>;
using RequestRef = typename Queue::RequestRef;
using Clock = ceph::coarse_real_clock;
Queue queue;
CephContext const *cct;
GetClientCounters counters; //< provides per-client perf counters
};
template <typename ...Args>
SyncScheduler::SyncScheduler(CephContext *cct, GetClientCounters&& counters,
Args&& ...args):
queue(std::forward<Args>(args)...), cct(cct), counters(std::move(counters))
{}
} // namespace rgw::dmclock
| 2,478 | 30.782051 | 101 |
h
|
null |
ceph-main/src/rgw/rgw_env.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_common.h"
#include "rgw_log.h"
#include <string>
#include <map>
#include "include/ceph_assert.h"
#include "rgw_crypt_sanitize.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
void RGWEnv::init(CephContext *cct)
{
conf.init(cct);
}
void RGWEnv::set(std::string name, std::string val)
{
env_map[std::move(name)] = std::move(val);
}
void RGWEnv::init(CephContext *cct, char **envp)
{
const char *p;
env_map.clear();
for (int i=0; (p = envp[i]); ++i) {
string s(p);
int pos = s.find('=');
if (pos <= 0) // should never be 0
continue;
string name = s.substr(0, pos);
string val = s.substr(pos + 1);
env_map[name] = val;
}
init(cct);
}
const char *rgw_conf_get(const map<string, string, ltstr_nocase>& conf_map, const char *name, const char *def_val)
{
auto iter = conf_map.find(name);
if (iter == conf_map.end())
return def_val;
return iter->second.c_str();
}
boost::optional<const std::string&> rgw_conf_get_optional(const map<string, string, ltstr_nocase>& conf_map, const std::string& name)
{
auto iter = conf_map.find(name);
if (iter == conf_map.end())
return boost::none;
return boost::optional<const std::string&>(iter->second);
}
const char *RGWEnv::get(const char *name, const char *def_val) const
{
return rgw_conf_get(env_map, name, def_val);
}
boost::optional<const std::string&>
RGWEnv::get_optional(const std::string& name) const
{
return rgw_conf_get_optional(env_map, name);
}
int rgw_conf_get_int(const map<string, string, ltstr_nocase>& conf_map, const char *name, int def_val)
{
auto iter = conf_map.find(name);
if (iter == conf_map.end())
return def_val;
const char *s = iter->second.c_str();
return atoi(s);
}
int RGWEnv::get_int(const char *name, int def_val) const
{
return rgw_conf_get_int(env_map, name, def_val);
}
bool rgw_conf_get_bool(const map<string, string, ltstr_nocase>& conf_map, const char *name, bool def_val)
{
auto iter = conf_map.find(name);
if (iter == conf_map.end())
return def_val;
const char *s = iter->second.c_str();
return rgw_str_to_bool(s, def_val);
}
bool RGWEnv::get_bool(const char *name, bool def_val)
{
return rgw_conf_get_bool(env_map, name, def_val);
}
size_t RGWEnv::get_size(const char *name, size_t def_val) const
{
const auto iter = env_map.find(name);
if (iter == env_map.end())
return def_val;
size_t sz;
try{
sz = stoull(iter->second);
} catch(...){
/* it is very unlikely that we'll ever encounter out_of_range, but let's
return the default eitherway */
sz = def_val;
}
return sz;
}
bool RGWEnv::exists(const char *name) const
{
return env_map.find(name)!= env_map.end();
}
bool RGWEnv::exists_prefix(const char *prefix) const
{
if (env_map.empty() || prefix == NULL)
return false;
const auto iter = env_map.lower_bound(prefix);
if (iter == env_map.end())
return false;
return (strncmp(iter->first.c_str(), prefix, strlen(prefix)) == 0);
}
void RGWEnv::remove(const char *name)
{
map<string, string, ltstr_nocase>::iterator iter = env_map.find(name);
if (iter != env_map.end())
env_map.erase(iter);
}
void RGWConf::init(CephContext *cct)
{
enable_ops_log = cct->_conf->rgw_enable_ops_log;
enable_usage_log = cct->_conf->rgw_enable_usage_log;
defer_to_bucket_acls = 0; // default
if (cct->_conf->rgw_defer_to_bucket_acls == "recurse") {
defer_to_bucket_acls = RGW_DEFER_TO_BUCKET_ACLS_RECURSE;
} else if (cct->_conf->rgw_defer_to_bucket_acls == "full_control") {
defer_to_bucket_acls = RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL;
}
}
| 3,767 | 22.698113 | 133 |
cc
|
null |
ceph-main/src/rgw/rgw_es_main.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <list>
#include <string>
#include <iostream>
#include "global/global_init.h"
#include "global/global_context.h"
#include "common/ceph_argparse.h"
#include "common/ceph_json.h"
#include "rgw_es_query.h"
using namespace std;
int main(int argc, char *argv[])
{
auto args = argv_to_vec(argc, argv);
auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_UTILITY, 0);
common_init_finish(g_ceph_context);
string expr;
if (argc > 1) {
expr = argv[1];
} else {
expr = "age >= 30";
}
ESQueryCompiler es_query(expr, nullptr, "x-amz-meta-");
map<string, string, ltstr_nocase> aliases = { { "key", "name" },
{ "etag", "meta.etag" },
{ "size", "meta.size" },
{ "mtime", "meta.mtime" },
{ "lastmodified", "meta.mtime" },
{ "contenttype", "meta.contenttype" },
};
es_query.set_field_aliases(&aliases);
map<string, ESEntityTypeMap::EntityType> generic_map = { {"bucket", ESEntityTypeMap::ES_ENTITY_STR},
{"name", ESEntityTypeMap::ES_ENTITY_STR},
{"instance", ESEntityTypeMap::ES_ENTITY_STR},
{"meta.etag", ESEntityTypeMap::ES_ENTITY_STR},
{"meta.contenttype", ESEntityTypeMap::ES_ENTITY_STR},
{"meta.mtime", ESEntityTypeMap::ES_ENTITY_DATE},
{"meta.size", ESEntityTypeMap::ES_ENTITY_INT} };
ESEntityTypeMap gm(generic_map);
es_query.set_generic_type_map(&gm);
map<string, ESEntityTypeMap::EntityType> custom_map = { {"str", ESEntityTypeMap::ES_ENTITY_STR},
{"int", ESEntityTypeMap::ES_ENTITY_INT},
{"date", ESEntityTypeMap::ES_ENTITY_DATE} };
ESEntityTypeMap em(custom_map);
es_query.set_custom_type_map(&em);
string err;
bool valid = es_query.compile(&err);
if (!valid) {
cout << "failed to compile query: " << err << std::endl;
return EINVAL;
}
JSONFormatter f;
encode_json("root", es_query, &f);
f.flush(cout);
return 0;
}
| 2,598 | 32.753247 | 112 |
cc
|
null |
ceph-main/src/rgw/rgw_es_query.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <list>
#include <map>
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include "common/ceph_json.h"
#include "rgw_common.h"
#include "rgw_es_query.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
bool pop_front(list<string>& l, string *s)
{
if (l.empty()) {
return false;
}
*s = l.front();
l.pop_front();
return true;
}
map<string, int> operator_map = {
{ "or", 1 },
{ "and", 2 },
{ "<", 3 },
{ "<=", 3 },
{ "==", 3 },
{ "!=", 3 },
{ ">=", 3 },
{ ">", 3 },
};
bool is_operator(const string& s)
{
return (operator_map.find(s) != operator_map.end());
}
int operand_value(const string& op)
{
auto i = operator_map.find(op);
if (i == operator_map.end()) {
return 0;
}
return i->second;
}
int check_precedence(const string& op1, const string& op2)
{
return operand_value(op1) - operand_value(op2);
}
static bool infix_to_prefix(list<string>& source, list<string> *out)
{
list<string> operator_stack;
list<string> operand_stack;
operator_stack.push_front("(");
source.push_back(")");
for (string& entity : source) {
if (entity == "(") {
operator_stack.push_front(entity);
} else if (entity == ")") {
string popped_operator;
if (!pop_front(operator_stack, &popped_operator)) {
return false;
}
while (popped_operator != "(") {
operand_stack.push_front(popped_operator);
if (!pop_front(operator_stack, &popped_operator)) {
return false;
}
}
} else if (is_operator(entity)) {
string popped_operator;
if (!pop_front(operator_stack, &popped_operator)) {
return false;
}
int precedence = check_precedence(popped_operator, entity);
while (precedence >= 0) {
operand_stack.push_front(popped_operator);
if (!pop_front(operator_stack, &popped_operator)) {
return false;
}
precedence = check_precedence(popped_operator, entity);
}
operator_stack.push_front(popped_operator);
operator_stack.push_front(entity);
} else {
operand_stack.push_front(entity);
}
}
if (!operator_stack.empty()) {
return false;
}
out->swap(operand_stack);
return true;
}
class ESQueryNode {
protected:
ESQueryCompiler *compiler;
public:
ESQueryNode(ESQueryCompiler *_compiler) : compiler(_compiler) {}
virtual ~ESQueryNode() {}
virtual bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) = 0;
virtual void dump(Formatter *f) const = 0;
};
static bool alloc_node(ESQueryCompiler *compiler, ESQueryStack *s, ESQueryNode **pnode, string *perr);
class ESQueryNode_Bool : public ESQueryNode {
string op;
ESQueryNode *first{nullptr};
ESQueryNode *second{nullptr};
public:
explicit ESQueryNode_Bool(ESQueryCompiler *compiler) : ESQueryNode(compiler) {}
ESQueryNode_Bool(ESQueryCompiler *compiler, const string& _op, ESQueryNode *_first, ESQueryNode *_second) :ESQueryNode(compiler), op(_op), first(_first), second(_second) {}
bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override {
bool valid = s->pop(&op);
if (!valid) {
*perr = "incorrect expression";
return false;
}
valid = alloc_node(compiler, s, &first, perr) &&
alloc_node(compiler, s, &second, perr);
if (!valid) {
return false;
}
*pnode = this;
return true;
}
virtual ~ESQueryNode_Bool() {
delete first;
delete second;
}
void dump(Formatter *f) const override {
f->open_object_section("bool");
const char *section = (op == "and" ? "must" : "should");
f->open_array_section(section);
encode_json("entry", *first, f);
encode_json("entry", *second, f);
f->close_section();
f->close_section();
}
};
class ESQueryNodeLeafVal {
public:
ESQueryNodeLeafVal() = default;
virtual ~ESQueryNodeLeafVal() {}
virtual bool init(const string& str_val, string *perr) = 0;
virtual void encode_json(const string& field, Formatter *f) const = 0;
};
class ESQueryNodeLeafVal_Str : public ESQueryNodeLeafVal {
string val;
public:
ESQueryNodeLeafVal_Str() {}
bool init(const string& str_val, string *perr) override {
val = str_val;
return true;
}
void encode_json(const string& field, Formatter *f) const override {
::encode_json(field.c_str(), val.c_str(), f);
}
};
class ESQueryNodeLeafVal_Int : public ESQueryNodeLeafVal {
int64_t val{0};
public:
ESQueryNodeLeafVal_Int() {}
bool init(const string& str_val, string *perr) override {
string err;
val = strict_strtoll(str_val.c_str(), 10, &err);
if (!err.empty()) {
*perr = string("failed to parse integer: ") + err;
return false;
}
return true;
}
void encode_json(const string& field, Formatter *f) const override {
::encode_json(field.c_str(), val, f);
}
};
class ESQueryNodeLeafVal_Date : public ESQueryNodeLeafVal {
ceph::real_time val;
public:
ESQueryNodeLeafVal_Date() {}
bool init(const string& str_val, string *perr) override {
if (parse_time(str_val.c_str(), &val) < 0) {
*perr = string("failed to parse date: ") + str_val;
return false;
}
return true;
}
void encode_json(const string& field, Formatter *f) const override {
string s;
rgw_to_iso8601(val, &s);
::encode_json(field.c_str(), s, f);
}
};
class ESQueryNode_Op : public ESQueryNode {
protected:
string op;
string field;
string str_val;
ESQueryNodeLeafVal *val{nullptr};
ESEntityTypeMap::EntityType entity_type{ESEntityTypeMap::ES_ENTITY_NONE};
bool allow_restricted{false};
bool val_from_str(string *perr) {
switch (entity_type) {
case ESEntityTypeMap::ES_ENTITY_DATE:
val = new ESQueryNodeLeafVal_Date;
break;
case ESEntityTypeMap::ES_ENTITY_INT:
val = new ESQueryNodeLeafVal_Int;
break;
default:
val = new ESQueryNodeLeafVal_Str;
}
return val->init(str_val, perr);
}
bool do_init(ESQueryNode **pnode, string *perr) {
field = compiler->unalias_field(field);
ESQueryNode *effective_node;
if (!handle_nested(&effective_node, perr)) {
return false;
}
if (!val_from_str(perr)) {
return false;
}
*pnode = effective_node;
return true;
}
public:
ESQueryNode_Op(ESQueryCompiler *compiler) : ESQueryNode(compiler) {}
~ESQueryNode_Op() {
delete val;
}
virtual bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override {
bool valid = s->pop(&op) &&
s->pop(&str_val) &&
s->pop(&field);
if (!valid) {
*perr = "invalid expression";
return false;
}
return do_init(pnode, perr);
}
bool handle_nested(ESQueryNode **pnode, string *perr);
void set_allow_restricted(bool allow) {
allow_restricted = allow;
}
virtual void dump(Formatter *f) const override = 0;
};
class ESQueryNode_Op_Equal : public ESQueryNode_Op {
public:
explicit ESQueryNode_Op_Equal(ESQueryCompiler *compiler) : ESQueryNode_Op(compiler) {}
ESQueryNode_Op_Equal(ESQueryCompiler *compiler, const string& f, const string& v) : ESQueryNode_Op(compiler) {
op = "==";
field = f;
str_val = v;
}
bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override {
if (op.empty()) {
return ESQueryNode_Op::init(s, pnode, perr);
}
return do_init(pnode, perr);
}
virtual void dump(Formatter *f) const override {
f->open_object_section("term");
val->encode_json(field, f);
f->close_section();
}
};
class ESQueryNode_Op_NotEqual : public ESQueryNode_Op {
public:
explicit ESQueryNode_Op_NotEqual(ESQueryCompiler *compiler) : ESQueryNode_Op(compiler) {}
ESQueryNode_Op_NotEqual(ESQueryCompiler *compiler, const string& f, const string& v) : ESQueryNode_Op(compiler) {
op = "!=";
field = f;
str_val = v;
}
bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override {
if (op.empty()) {
return ESQueryNode_Op::init(s, pnode, perr);
}
return do_init(pnode, perr);
}
virtual void dump(Formatter *f) const override {
f->open_object_section("bool");
f->open_object_section("must_not");
f->open_object_section("term");
val->encode_json(field, f);
f->close_section();
f->close_section();
f->close_section();
}
};
class ESQueryNode_Op_Range : public ESQueryNode_Op {
string range_str;
public:
ESQueryNode_Op_Range(ESQueryCompiler *compiler, const string& rs) : ESQueryNode_Op(compiler), range_str(rs) {}
virtual void dump(Formatter *f) const override {
f->open_object_section("range");
f->open_object_section(field.c_str());
val->encode_json(range_str, f);
f->close_section();
f->close_section();
}
};
class ESQueryNode_Op_Nested_Parent : public ESQueryNode_Op {
public:
ESQueryNode_Op_Nested_Parent(ESQueryCompiler *compiler) : ESQueryNode_Op(compiler) {}
virtual string get_custom_leaf_field_name() = 0;
};
template <class T>
class ESQueryNode_Op_Nested : public ESQueryNode_Op_Nested_Parent {
string name;
ESQueryNode *next;
public:
ESQueryNode_Op_Nested(ESQueryCompiler *compiler, const string& _name, ESQueryNode *_next) : ESQueryNode_Op_Nested_Parent(compiler),
name(_name), next(_next) {}
~ESQueryNode_Op_Nested() {
delete next;
}
virtual void dump(Formatter *f) const override {
f->open_object_section("nested");
string s = string("meta.custom-") + type_str();
encode_json("path", s.c_str(), f);
f->open_object_section("query");
f->open_object_section("bool");
f->open_array_section("must");
f->open_object_section("entry");
f->open_object_section("match");
string n = s + ".name";
encode_json(n.c_str(), name.c_str(), f);
f->close_section();
f->close_section();
encode_json("entry", *next, f);
f->close_section();
f->close_section();
f->close_section();
f->close_section();
}
string type_str() const;
string get_custom_leaf_field_name() override {
return string("meta.custom-") + type_str() + ".value";
}
};
template<>
string ESQueryNode_Op_Nested<string>::type_str() const {
return "string";
}
template<>
string ESQueryNode_Op_Nested<int64_t>::type_str() const {
return "int";
}
template<>
string ESQueryNode_Op_Nested<ceph::real_time>::type_str() const {
return "date";
}
bool ESQueryNode_Op::handle_nested(ESQueryNode **pnode, string *perr)
{
string field_name = field;
const string& custom_prefix = compiler->get_custom_prefix();
if (!boost::algorithm::starts_with(field_name, custom_prefix)) {
*pnode = this;
auto m = compiler->get_generic_type_map();
if (m) {
bool found = m->find(field_name, &entity_type) &&
(allow_restricted || !compiler->is_restricted(field_name));
if (!found) {
*perr = string("unexpected generic field '") + field_name + "'";
}
return found;
}
*perr = "query parser does not support generic types";
return false;
}
field_name = field_name.substr(custom_prefix.size());
auto m = compiler->get_custom_type_map();
if (m) {
m->find(field_name, &entity_type);
/* ignoring returned bool, for now just treat it as string */
}
ESQueryNode_Op_Nested_Parent *new_node;
switch (entity_type) {
case ESEntityTypeMap::ES_ENTITY_INT:
new_node = new ESQueryNode_Op_Nested<int64_t>(compiler, field_name, this);
break;
case ESEntityTypeMap::ES_ENTITY_DATE:
new_node = new ESQueryNode_Op_Nested<ceph::real_time>(compiler, field_name, this);
break;
default:
new_node = new ESQueryNode_Op_Nested<string>(compiler, field_name, this);
}
field = new_node->get_custom_leaf_field_name();
*pnode = new_node;
return true;
}
static bool is_bool_op(const string& str)
{
return (str == "or" || str == "and");
}
static bool alloc_node(ESQueryCompiler *compiler, ESQueryStack *s, ESQueryNode **pnode, string *perr)
{
string op;
bool valid = s->peek(&op);
if (!valid) {
*perr = "incorrect expression";
return false;
}
ESQueryNode *node;
if (is_bool_op(op)) {
node = new ESQueryNode_Bool(compiler);
} else if (op == "==") {
node = new ESQueryNode_Op_Equal(compiler);
} else if (op == "!=") {
node = new ESQueryNode_Op_NotEqual(compiler);
} else {
static map<string, string> range_op_map = {
{ "<", "lt"},
{ "<=", "lte"},
{ ">=", "gte"},
{ ">", "gt"},
};
auto iter = range_op_map.find(op);
if (iter == range_op_map.end()) {
*perr = string("invalid operator: ") + op;
return false;
}
node = new ESQueryNode_Op_Range(compiler, iter->second);
}
if (!node->init(s, pnode, perr)) {
delete node;
return false;
}
return true;
}
bool is_key_char(char c)
{
switch (c) {
case '(':
case ')':
case '<':
case '>':
case '!':
case '@':
case ',':
case ';':
case ':':
case '\\':
case '"':
case '/':
case '[':
case ']':
case '?':
case '=':
case '{':
case '}':
case ' ':
case '\t':
return false;
};
return (isascii(c) > 0);
}
static bool is_op_char(char c)
{
switch (c) {
case '!':
case '<':
case '=':
case '>':
return true;
};
return false;
}
static bool is_val_char(char c)
{
if (isspace(c)) {
return false;
}
return (c != ')');
}
void ESInfixQueryParser::skip_whitespace(const char *str, int size, int& pos) {
while (pos < size && isspace(str[pos])) {
++pos;
}
}
bool ESInfixQueryParser::get_next_token(bool (*filter)(char)) {
skip_whitespace(str, size, pos);
int token_start = pos;
while (pos < size && filter(str[pos])) {
++pos;
}
if (pos == token_start) {
return false;
}
string token = string(str + token_start, pos - token_start);
args.push_back(token);
return true;
}
bool ESInfixQueryParser::parse_condition() {
/*
* condition: <key> <operator> <val>
*
* whereas key: needs to conform to http header field restrictions
* operator: one of the following: < <= == != >= >
* val: ascii, terminated by either space or ')' (or end of string)
*/
/* parse key */
bool valid = get_next_token(is_key_char) &&
get_next_token(is_op_char) &&
get_next_token(is_val_char);
if (!valid) {
return false;
}
return true;
}
bool ESInfixQueryParser::parse_and_or() {
skip_whitespace(str, size, pos);
if (pos + 3 <= size && strncmp(str + pos, "and", 3) == 0) {
pos += 3;
args.push_back("and");
return true;
}
if (pos + 2 <= size && strncmp(str + pos, "or", 2) == 0) {
pos += 2;
args.push_back("or");
return true;
}
return false;
}
bool ESInfixQueryParser::parse_specific_char(const char *pchar) {
skip_whitespace(str, size, pos);
if (pos >= size) {
return false;
}
if (str[pos] != *pchar) {
return false;
}
args.push_back(pchar);
++pos;
return true;
}
bool ESInfixQueryParser::parse_open_bracket() {
return parse_specific_char("(");
}
bool ESInfixQueryParser::parse_close_bracket() {
return parse_specific_char(")");
}
bool ESInfixQueryParser::parse(list<string> *result) {
/*
* expression: [(]<condition>[[and/or]<condition>][)][and/or]...
*/
while (pos < size) {
parse_open_bracket();
if (!parse_condition()) {
return false;
}
parse_close_bracket();
parse_and_or();
}
result->swap(args);
return true;
}
bool ESQueryCompiler::convert(list<string>& infix, string *perr) {
list<string> prefix;
if (!infix_to_prefix(infix, &prefix)) {
*perr = "invalid query";
return false;
}
stack.assign(prefix);
if (!alloc_node(this, &stack, &query_root, perr)) {
return false;
}
if (!stack.done()) {
*perr = "invalid query";
return false;
}
return true;
}
ESQueryCompiler::~ESQueryCompiler() {
delete query_root;
}
bool ESQueryCompiler::compile(string *perr) {
list<string> infix;
if (!parser.parse(&infix)) {
*perr = "failed to parse query";
return false;
}
if (!convert(infix, perr)) {
return false;
}
for (auto& c : eq_conds) {
ESQueryNode_Op_Equal *eq_node = new ESQueryNode_Op_Equal(this, c.first, c.second);
eq_node->set_allow_restricted(true); /* can access restricted fields */
ESQueryNode *effective_node;
if (!eq_node->init(nullptr, &effective_node, perr)) {
delete eq_node;
return false;
}
query_root = new ESQueryNode_Bool(this, "and", effective_node, query_root);
}
return true;
}
void ESQueryCompiler::dump(Formatter *f) const {
encode_json("query", *query_root, f);
}
| 16,899 | 23.246772 | 174 |
cc
|
null |
ceph-main/src/rgw/rgw_es_query.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "rgw_string.h"
class ESQueryStack {
std::list<std::string> l;
std::list<std::string>::iterator iter;
public:
explicit ESQueryStack(std::list<std::string>& src) {
assign(src);
}
ESQueryStack() {}
void assign(std::list<std::string>& src) {
l.swap(src);
iter = l.begin();
}
bool peek(std::string *dest) {
if (done()) {
return false;
}
*dest = *iter;
return true;
}
bool pop(std::string *dest) {
bool valid = peek(dest);
if (!valid) {
return false;
}
++iter;
return true;
}
bool done() {
return (iter == l.end());
}
};
class ESInfixQueryParser {
std::string query;
int size;
const char *str;
int pos{0};
std::list<std::string> args;
void skip_whitespace(const char *str, int size, int& pos);
bool get_next_token(bool (*filter)(char));
bool parse_condition();
bool parse_and_or();
bool parse_specific_char(const char *pchar);
bool parse_open_bracket();
bool parse_close_bracket();
public:
explicit ESInfixQueryParser(const std::string& _query) : query(_query), size(query.size()), str(query.c_str()) {}
bool parse(std::list<std::string> *result);
};
class ESQueryNode;
struct ESEntityTypeMap {
enum EntityType {
ES_ENTITY_NONE = 0,
ES_ENTITY_STR = 1,
ES_ENTITY_INT = 2,
ES_ENTITY_DATE = 3,
};
std::map<std::string, EntityType> m;
explicit ESEntityTypeMap(std::map<std::string, EntityType>& _m) : m(_m) {}
bool find(const std::string& entity, EntityType *ptype) {
auto i = m.find(entity);
if (i != m.end()) {
*ptype = i->second;
return true;
}
*ptype = ES_ENTITY_NONE;
return false;
}
};
class ESQueryCompiler {
ESInfixQueryParser parser;
ESQueryStack stack;
ESQueryNode *query_root{nullptr};
std::string custom_prefix;
bool convert(std::list<std::string>& infix, std::string *perr);
std::list<std::pair<std::string, std::string> > eq_conds;
ESEntityTypeMap *generic_type_map{nullptr};
ESEntityTypeMap *custom_type_map{nullptr};
std::map<std::string, std::string, ltstr_nocase> *field_aliases = nullptr;
std::set<std::string> *restricted_fields = nullptr;
public:
ESQueryCompiler(const std::string& query,
std::list<std::pair<std::string, std::string> > *prepend_eq_conds,
const std::string& _custom_prefix)
: parser(query), custom_prefix(_custom_prefix) {
if (prepend_eq_conds) {
eq_conds = std::move(*prepend_eq_conds);
}
}
~ESQueryCompiler();
bool compile(std::string *perr);
void dump(Formatter *f) const;
void set_generic_type_map(ESEntityTypeMap *entity_map) {
generic_type_map = entity_map;
}
ESEntityTypeMap *get_generic_type_map() {
return generic_type_map;
}
const std::string& get_custom_prefix() { return custom_prefix; }
void set_custom_type_map(ESEntityTypeMap *entity_map) {
custom_type_map = entity_map;
}
ESEntityTypeMap *get_custom_type_map() {
return custom_type_map;
}
void set_field_aliases(std::map<std::string, std::string, ltstr_nocase> *fa) {
field_aliases = fa;
}
std::string unalias_field(const std::string& field) {
if (!field_aliases) {
return field;
}
auto i = field_aliases->find(field);
if (i == field_aliases->end()) {
return field;
}
return i->second;
}
void set_restricted_fields(std::set<std::string> *rf) {
restricted_fields = rf;
}
bool is_restricted(const std::string& f) {
return (restricted_fields && restricted_fields->find(f) != restricted_fields->end());
}
};
| 3,705 | 21.460606 | 115 |
h
|
null |
ceph-main/src/rgw/rgw_file.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "include/compat.h"
#include "include/rados/rgw_file.h"
#include <sys/types.h>
#include <sys/stat.h>
#include "rgw_lib.h"
#include "rgw_resolve.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_frontend.h"
#include "rgw_request.h"
#include "rgw_process.h"
#include "rgw_rest_user.h"
#include "rgw_rest_s3.h"
#include "rgw_os_lib.h"
#include "rgw_auth_s3.h"
#include "rgw_user.h"
#include "rgw_bucket.h"
#include "rgw_zone.h"
#include "rgw_file.h"
#include "rgw_lib_frontend.h"
#include "rgw_perf_counters.h"
#include "common/errno.h"
#include "services/svc_zone.h"
#include <atomic>
#define dout_subsys ceph_subsys_rgw
using namespace std;
using namespace rgw;
namespace rgw {
const string RGWFileHandle::root_name = "/";
std::atomic<uint32_t> RGWLibFS::fs_inst_counter;
uint32_t RGWLibFS::write_completion_interval_s = 10;
ceph::timer<ceph::mono_clock> RGWLibFS::write_timer{
ceph::construct_suspended};
inline int valid_fs_bucket_name(const string& name) {
int rc = valid_s3_bucket_name(name, false /* relaxed */);
if (rc != 0) {
if (name.size() > 255)
return -ENAMETOOLONG;
return -EINVAL;
}
return 0;
}
inline int valid_fs_object_name(const string& name) {
int rc = valid_s3_object_name(name);
if (rc != 0) {
if (name.size() > 1024)
return -ENAMETOOLONG;
return -EINVAL;
}
return 0;
}
class XattrHash
{
public:
std::size_t operator()(const rgw_xattrstr& att) const noexcept {
return XXH64(att.val, att.len, 5882300);
}
};
class XattrEqual
{
public:
bool operator()(const rgw_xattrstr& lhs, const rgw_xattrstr& rhs) const {
return ((lhs.len == rhs.len) &&
(strncmp(lhs.val, rhs.val, lhs.len) == 0));
}
};
/* well-known attributes */
static const std::unordered_set<
rgw_xattrstr, XattrHash, XattrEqual> rgw_exposed_attrs = {
rgw_xattrstr{const_cast<char*>(RGW_ATTR_ETAG), sizeof(RGW_ATTR_ETAG)-1}
};
static inline bool is_exposed_attr(const rgw_xattrstr& k) {
return (rgw_exposed_attrs.find(k) != rgw_exposed_attrs.end());
}
LookupFHResult RGWLibFS::stat_bucket(RGWFileHandle* parent, const char *path,
RGWLibFS::BucketStats& bs,
uint32_t flags)
{
LookupFHResult fhr{nullptr, 0};
std::string bucket_name{path};
RGWStatBucketRequest req(cct, user->clone(), bucket_name, bs);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc == 0) &&
(req.get_ret() == 0) &&
(req.matched())) {
fhr = lookup_fh(parent, path,
(flags & RGWFileHandle::FLAG_LOCKED)|
RGWFileHandle::FLAG_CREATE|
RGWFileHandle::FLAG_BUCKET);
if (get<0>(fhr)) {
RGWFileHandle* rgw_fh = get<0>(fhr);
if (! (flags & RGWFileHandle::FLAG_LOCKED)) {
rgw_fh->mtx.lock();
}
rgw_fh->set_times(req.get_ctime());
/* restore attributes */
auto ux_key = req.get_attr(RGW_ATTR_UNIX_KEY1);
auto ux_attrs = req.get_attr(RGW_ATTR_UNIX1);
if (ux_key && ux_attrs) {
DecodeAttrsResult dar = rgw_fh->decode_attrs(ux_key, ux_attrs);
if (get<0>(dar) || get<1>(dar)) {
update_fh(rgw_fh);
}
}
if (! (flags & RGWFileHandle::FLAG_LOCKED)) {
rgw_fh->mtx.unlock();
}
}
}
return fhr;
}
LookupFHResult RGWLibFS::fake_leaf(RGWFileHandle* parent,
const char *path,
enum rgw_fh_type type,
struct stat *st, uint32_t st_mask,
uint32_t flags)
{
/* synthesize a minimal handle from parent, path, type, and st */
using std::get;
flags |= RGWFileHandle::FLAG_CREATE;
switch (type) {
case RGW_FS_TYPE_DIRECTORY:
flags |= RGWFileHandle::FLAG_DIRECTORY;
break;
default:
/* file */
break;
};
LookupFHResult fhr = lookup_fh(parent, path, flags);
if (get<0>(fhr)) {
RGWFileHandle* rgw_fh = get<0>(fhr);
if (st) {
lock_guard guard(rgw_fh->mtx);
if (st_mask & RGW_SETATTR_SIZE) {
rgw_fh->set_size(st->st_size);
}
if (st_mask & RGW_SETATTR_MTIME) {
rgw_fh->set_times(st->st_mtim);
}
} /* st */
} /* rgw_fh */
return fhr;
} /* RGWLibFS::fake_leaf */
LookupFHResult RGWLibFS::stat_leaf(RGWFileHandle* parent,
const char *path,
enum rgw_fh_type type,
uint32_t flags)
{
/* find either-of <object_name>, <object_name/>, only one of
* which should exist; atomicity? */
using std::get;
LookupFHResult fhr{nullptr, 0};
/* XXX the need for two round-trip operations to identify file or
* directory leaf objects is unecessary--the current proposed
* mechanism to avoid this is to store leaf object names with an
* object locator w/o trailing slash */
std::string obj_path = parent->format_child_name(path, false);
for (auto ix : { 0, 1, 2 }) {
switch (ix) {
case 0:
{
/* type hint */
if (type == RGW_FS_TYPE_DIRECTORY)
continue;
RGWStatObjRequest req(cct, user->clone(),
parent->bucket_name(), obj_path,
RGWStatObjRequest::FLAG_NONE);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc == 0) &&
(req.get_ret() == 0)) {
fhr = lookup_fh(parent, path, RGWFileHandle::FLAG_CREATE);
if (get<0>(fhr)) {
RGWFileHandle* rgw_fh = get<0>(fhr);
lock_guard guard(rgw_fh->mtx);
rgw_fh->set_size(req.get_size());
rgw_fh->set_times(req.get_mtime());
/* restore attributes */
auto ux_key = req.get_attr(RGW_ATTR_UNIX_KEY1);
auto ux_attrs = req.get_attr(RGW_ATTR_UNIX1);
rgw_fh->set_etag(*(req.get_attr(RGW_ATTR_ETAG)));
rgw_fh->set_acls(*(req.get_attr(RGW_ATTR_ACL)));
if (!(flags & RGWFileHandle::FLAG_IN_CB) &&
ux_key && ux_attrs) {
DecodeAttrsResult dar = rgw_fh->decode_attrs(ux_key, ux_attrs);
if (get<0>(dar) || get<1>(dar)) {
update_fh(rgw_fh);
}
}
}
goto done;
}
}
break;
case 1:
{
/* try dir form */
/* type hint */
if (type == RGW_FS_TYPE_FILE)
continue;
obj_path += "/";
RGWStatObjRequest req(cct, user->clone(),
parent->bucket_name(), obj_path,
RGWStatObjRequest::FLAG_NONE);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc == 0) &&
(req.get_ret() == 0)) {
fhr = lookup_fh(parent, path, RGWFileHandle::FLAG_DIRECTORY);
if (get<0>(fhr)) {
RGWFileHandle* rgw_fh = get<0>(fhr);
lock_guard guard(rgw_fh->mtx);
rgw_fh->set_size(req.get_size());
rgw_fh->set_times(req.get_mtime());
/* restore attributes */
auto ux_key = req.get_attr(RGW_ATTR_UNIX_KEY1);
auto ux_attrs = req.get_attr(RGW_ATTR_UNIX1);
rgw_fh->set_etag(*(req.get_attr(RGW_ATTR_ETAG)));
rgw_fh->set_acls(*(req.get_attr(RGW_ATTR_ACL)));
if (!(flags & RGWFileHandle::FLAG_IN_CB) &&
ux_key && ux_attrs) {
DecodeAttrsResult dar = rgw_fh->decode_attrs(ux_key, ux_attrs);
if (get<0>(dar) || get<1>(dar)) {
update_fh(rgw_fh);
}
}
}
goto done;
}
}
break;
case 2:
{
std::string object_name{path};
RGWStatLeafRequest req(cct, user->clone(),
parent, object_name);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc == 0) &&
(req.get_ret() == 0)) {
if (req.matched) {
/* we need rgw object's key name equal to file name, if
* not return NULL */
if ((flags & RGWFileHandle::FLAG_EXACT_MATCH) &&
!req.exact_matched) {
lsubdout(get_context(), rgw, 15)
<< __func__
<< ": stat leaf not exact match file name = "
<< path << dendl;
goto done;
}
fhr = lookup_fh(parent, path,
RGWFileHandle::FLAG_CREATE|
((req.is_dir) ?
RGWFileHandle::FLAG_DIRECTORY :
RGWFileHandle::FLAG_NONE));
/* XXX we don't have an object--in general, there need not
* be one (just a path segment in some other object). In
* actual leaf an object exists, but we'd need another round
* trip to get attrs */
if (get<0>(fhr)) {
/* for now use the parent object's mtime */
RGWFileHandle* rgw_fh = get<0>(fhr);
lock_guard guard(rgw_fh->mtx);
rgw_fh->set_mtime(parent->get_mtime());
}
}
}
}
break;
default:
/* not reached */
break;
}
}
done:
return fhr;
} /* RGWLibFS::stat_leaf */
int RGWLibFS::read(RGWFileHandle* rgw_fh, uint64_t offset, size_t length,
size_t* bytes_read, void* buffer, uint32_t flags)
{
if (! rgw_fh->is_file())
return -EINVAL;
if (rgw_fh->deleted())
return -ESTALE;
RGWReadRequest req(get_context(), user->clone(), rgw_fh, offset, length, buffer);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc == 0) &&
((rc = req.get_ret()) == 0)) {
lock_guard guard(rgw_fh->mtx);
rgw_fh->set_atime(real_clock::to_timespec(real_clock::now()));
*bytes_read = req.nread;
}
return rc;
}
int RGWLibFS::readlink(RGWFileHandle* rgw_fh, uint64_t offset, size_t length,
size_t* bytes_read, void* buffer, uint32_t flags)
{
if (! rgw_fh->is_link())
return -EINVAL;
if (rgw_fh->deleted())
return -ESTALE;
RGWReadRequest req(get_context(), user->clone(), rgw_fh, offset, length, buffer);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc == 0) &&
((rc = req.get_ret()) == 0)) {
lock_guard(rgw_fh->mtx);
rgw_fh->set_atime(real_clock::to_timespec(real_clock::now()));
*bytes_read = req.nread;
}
return rc;
}
int RGWLibFS::unlink(RGWFileHandle* rgw_fh, const char* name, uint32_t flags)
{
int rc = 0;
BucketStats bs;
RGWFileHandle* parent = nullptr;
RGWFileHandle* bkt_fh = nullptr;
if (unlikely(flags & RGWFileHandle::FLAG_UNLINK_THIS)) {
/* LOCKED */
parent = rgw_fh->get_parent();
} else {
/* atomicity */
parent = rgw_fh;
LookupFHResult fhr = lookup_fh(parent, name, RGWFileHandle::FLAG_LOCK);
rgw_fh = get<0>(fhr);
/* LOCKED */
}
if (parent->is_root()) {
/* a bucket may have an object storing Unix attributes, check
* for and delete it */
LookupFHResult fhr;
fhr = stat_bucket(parent, name, bs, (rgw_fh) ?
RGWFileHandle::FLAG_LOCKED :
RGWFileHandle::FLAG_NONE);
bkt_fh = get<0>(fhr);
if (unlikely(! bkt_fh)) {
/* implies !rgw_fh, so also !LOCKED */
return -ENOENT;
}
if (bs.num_entries > 1) {
unref(bkt_fh); /* return stat_bucket ref */
if (likely(!! rgw_fh)) { /* return lock and ref from
* lookup_fh (or caller in the
* special case of
* RGWFileHandle::FLAG_UNLINK_THIS) */
rgw_fh->mtx.unlock();
unref(rgw_fh);
}
return -ENOTEMPTY;
} else {
/* delete object w/key "<bucket>/" (uxattrs), if any */
string oname{"/"};
RGWDeleteObjRequest req(cct, user->clone(), bkt_fh->bucket_name(), oname);
rc = g_rgwlib->get_fe()->execute_req(&req);
/* don't care if ENOENT */
unref(bkt_fh);
}
string bname{name};
RGWDeleteBucketRequest req(cct, user->clone(), bname);
rc = g_rgwlib->get_fe()->execute_req(&req);
if (! rc) {
rc = req.get_ret();
}
} else {
/*
* leaf object
*/
if (! rgw_fh) {
/* XXX for now, peform a hard lookup to deduce the type of
* object to be deleted ("foo" vs. "foo/")--also, ensures
* atomicity at this endpoint */
struct rgw_file_handle *fh;
rc = rgw_lookup(get_fs(), parent->get_fh(), name, &fh,
nullptr /* st */, 0 /* mask */,
RGW_LOOKUP_FLAG_NONE);
if (!! rc)
return rc;
/* rgw_fh ref+ */
rgw_fh = get_rgwfh(fh);
rgw_fh->mtx.lock(); /* LOCKED */
}
std::string oname = rgw_fh->relative_object_name();
if (rgw_fh->is_dir()) {
/* for the duration of our cache timer, trust positive
* child cache */
if (rgw_fh->has_children()) {
rgw_fh->mtx.unlock();
unref(rgw_fh);
return(-ENOTEMPTY);
}
oname += "/";
}
RGWDeleteObjRequest req(cct, user->clone(), parent->bucket_name(), oname);
rc = g_rgwlib->get_fe()->execute_req(&req);
if (! rc) {
rc = req.get_ret();
}
}
/* ENOENT when raced with other s3 gateway */
if (! rc || rc == -ENOENT) {
rgw_fh->flags |= RGWFileHandle::FLAG_DELETED;
fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh,
RGWFileHandle::FHCache::FLAG_LOCK);
}
if (! rc) {
real_time t = real_clock::now();
parent->set_mtime(real_clock::to_timespec(t));
parent->set_ctime(real_clock::to_timespec(t));
}
rgw_fh->mtx.unlock();
unref(rgw_fh);
return rc;
} /* RGWLibFS::unlink */
int RGWLibFS::rename(RGWFileHandle* src_fh, RGWFileHandle* dst_fh,
const char *_src_name, const char *_dst_name)
{
/* XXX initial implementation: try-copy, and delete if copy
* succeeds */
int rc = -EINVAL;
real_time t;
std::string src_name{_src_name};
std::string dst_name{_dst_name};
/* atomicity */
LookupFHResult fhr = lookup_fh(src_fh, _src_name, RGWFileHandle::FLAG_LOCK);
RGWFileHandle* rgw_fh = get<0>(fhr);
/* should not happen */
if (! rgw_fh) {
ldout(get_context(), 0) << __func__
<< " BUG no such src renaming path="
<< src_name
<< dendl;
goto out;
}
/* forbid renaming of directories (unreasonable at scale) */
if (rgw_fh->is_dir()) {
ldout(get_context(), 12) << __func__
<< " rejecting attempt to rename directory path="
<< rgw_fh->full_object_name()
<< dendl;
rc = -EPERM;
goto unlock;
}
/* forbid renaming open files (violates intent, for now) */
if (rgw_fh->is_open()) {
ldout(get_context(), 12) << __func__
<< " rejecting attempt to rename open file path="
<< rgw_fh->full_object_name()
<< dendl;
rc = -EPERM;
goto unlock;
}
t = real_clock::now();
for (int ix : {0, 1}) {
switch (ix) {
case 0:
{
RGWCopyObjRequest req(cct, user->clone(), src_fh, dst_fh, src_name, dst_name);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if ((rc != 0) ||
((rc = req.get_ret()) != 0)) {
ldout(get_context(), 1)
<< __func__
<< " rename step 0 failed src="
<< src_fh->full_object_name() << " " << src_name
<< " dst=" << dst_fh->full_object_name()
<< " " << dst_name
<< "rc " << rc
<< dendl;
goto unlock;
}
ldout(get_context(), 12)
<< __func__
<< " rename step 0 success src="
<< src_fh->full_object_name() << " " << src_name
<< " dst=" << dst_fh->full_object_name()
<< " " << dst_name
<< " rc " << rc
<< dendl;
/* update dst change id */
dst_fh->set_times(t);
}
break;
case 1:
{
rc = this->unlink(rgw_fh /* LOCKED */, _src_name,
RGWFileHandle::FLAG_UNLINK_THIS);
/* !LOCKED, -ref */
if (! rc) {
ldout(get_context(), 12)
<< __func__
<< " rename step 1 success src="
<< src_fh->full_object_name() << " " << src_name
<< " dst=" << dst_fh->full_object_name()
<< " " << dst_name
<< " rc " << rc
<< dendl;
/* update src change id */
src_fh->set_times(t);
} else {
ldout(get_context(), 1)
<< __func__
<< " rename step 1 failed src="
<< src_fh->full_object_name() << " " << src_name
<< " dst=" << dst_fh->full_object_name()
<< " " << dst_name
<< " rc " << rc
<< dendl;
}
}
goto out;
default:
ceph_abort();
} /* switch */
} /* ix */
unlock:
rgw_fh->mtx.unlock(); /* !LOCKED */
unref(rgw_fh); /* -ref */
out:
return rc;
} /* RGWLibFS::rename */
MkObjResult RGWLibFS::mkdir(RGWFileHandle* parent, const char *name,
struct stat *st, uint32_t mask, uint32_t flags)
{
int rc, rc2;
rgw_file_handle *lfh;
rc = rgw_lookup(get_fs(), parent->get_fh(), name, &lfh,
nullptr /* st */, 0 /* mask */,
RGW_LOOKUP_FLAG_NONE);
if (! rc) {
/* conflict! */
rc = rgw_fh_rele(get_fs(), lfh, RGW_FH_RELE_FLAG_NONE);
// ignore return code
return MkObjResult{nullptr, -EEXIST};
}
MkObjResult mkr{nullptr, -EINVAL};
LookupFHResult fhr;
RGWFileHandle* rgw_fh = nullptr;
buffer::list ux_key, ux_attrs;
fhr = lookup_fh(parent, name,
RGWFileHandle::FLAG_CREATE|
RGWFileHandle::FLAG_DIRECTORY|
RGWFileHandle::FLAG_LOCK);
rgw_fh = get<0>(fhr);
if (rgw_fh) {
rgw_fh->create_stat(st, mask);
rgw_fh->set_times(real_clock::now());
/* save attrs */
rgw_fh->encode_attrs(ux_key, ux_attrs);
if (st)
rgw_fh->stat(st, RGWFileHandle::FLAG_LOCKED);
get<0>(mkr) = rgw_fh;
} else {
get<1>(mkr) = -EIO;
return mkr;
}
if (parent->is_root()) {
/* bucket */
string bname{name};
/* enforce S3 name restrictions */
rc = valid_fs_bucket_name(bname);
if (rc != 0) {
rgw_fh->flags |= RGWFileHandle::FLAG_DELETED;
fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh,
RGWFileHandle::FHCache::FLAG_LOCK);
rgw_fh->mtx.unlock();
unref(rgw_fh);
get<0>(mkr) = nullptr;
get<1>(mkr) = rc;
return mkr;
}
RGWCreateBucketRequest req(get_context(), user->clone(), bname);
/* save attrs */
req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
} else {
/* create an object representing the directory */
buffer::list bl;
string dir_name = parent->format_child_name(name, true);
/* need valid S3 name (characters, length <= 1024, etc) */
rc = valid_fs_object_name(dir_name);
if (rc != 0) {
rgw_fh->flags |= RGWFileHandle::FLAG_DELETED;
fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh,
RGWFileHandle::FHCache::FLAG_LOCK);
rgw_fh->mtx.unlock();
unref(rgw_fh);
get<0>(mkr) = nullptr;
get<1>(mkr) = rc;
return mkr;
}
RGWPutObjRequest req(get_context(), user->clone(), parent->bucket_name(), dir_name, bl);
/* save attrs */
req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
}
if (! ((rc == 0) &&
(rc2 == 0))) {
/* op failed */
rgw_fh->flags |= RGWFileHandle::FLAG_DELETED;
rgw_fh->mtx.unlock(); /* !LOCKED */
unref(rgw_fh);
get<0>(mkr) = nullptr;
/* fixup rc */
if (!rc)
rc = rc2;
} else {
real_time t = real_clock::now();
parent->set_mtime(real_clock::to_timespec(t));
parent->set_ctime(real_clock::to_timespec(t));
rgw_fh->mtx.unlock(); /* !LOCKED */
}
get<1>(mkr) = rc;
return mkr;
} /* RGWLibFS::mkdir */
MkObjResult RGWLibFS::create(RGWFileHandle* parent, const char *name,
struct stat *st, uint32_t mask, uint32_t flags)
{
int rc, rc2;
using std::get;
rgw_file_handle *lfh;
rc = rgw_lookup(get_fs(), parent->get_fh(), name, &lfh,
nullptr /* st */, 0 /* mask */,
RGW_LOOKUP_FLAG_NONE);
if (! rc) {
/* conflict! */
rc = rgw_fh_rele(get_fs(), lfh, RGW_FH_RELE_FLAG_NONE);
// ignore return code
return MkObjResult{nullptr, -EEXIST};
}
/* expand and check name */
std::string obj_name = parent->format_child_name(name, false);
rc = valid_fs_object_name(obj_name);
if (rc != 0) {
return MkObjResult{nullptr, rc};
}
/* create it */
buffer::list bl;
RGWPutObjRequest req(cct, user->clone(), parent->bucket_name(), obj_name, bl);
MkObjResult mkr{nullptr, -EINVAL};
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
if ((rc == 0) &&
(rc2 == 0)) {
/* XXX atomicity */
LookupFHResult fhr = lookup_fh(parent, name, RGWFileHandle::FLAG_CREATE |
RGWFileHandle::FLAG_LOCK);
RGWFileHandle* rgw_fh = get<0>(fhr);
if (rgw_fh) {
if (get<1>(fhr) & RGWFileHandle::FLAG_CREATE) {
/* fill in stat data */
real_time t = real_clock::now();
rgw_fh->create_stat(st, mask);
rgw_fh->set_times(t);
parent->set_mtime(real_clock::to_timespec(t));
parent->set_ctime(real_clock::to_timespec(t));
}
if (st)
(void) rgw_fh->stat(st, RGWFileHandle::FLAG_LOCKED);
rgw_fh->set_etag(*(req.get_attr(RGW_ATTR_ETAG)));
rgw_fh->set_acls(*(req.get_attr(RGW_ATTR_ACL)));
get<0>(mkr) = rgw_fh;
rgw_fh->file_ondisk_version = 0; // inital version
rgw_fh->mtx.unlock();
} else
rc = -EIO;
}
get<1>(mkr) = rc;
/* case like : quota exceed will be considered as fail too*/
if(rc2 < 0)
get<1>(mkr) = rc2;
return mkr;
} /* RGWLibFS::create */
MkObjResult RGWLibFS::symlink(RGWFileHandle* parent, const char *name,
const char* link_path, struct stat *st, uint32_t mask, uint32_t flags)
{
int rc, rc2;
using std::get;
rgw_file_handle *lfh;
rc = rgw_lookup(get_fs(), parent->get_fh(), name, &lfh,
nullptr /* st */, 0 /* mask */,
RGW_LOOKUP_FLAG_NONE);
if (! rc) {
/* conflict! */
rc = rgw_fh_rele(get_fs(), lfh, RGW_FH_RELE_FLAG_NONE);
// ignore return code
return MkObjResult{nullptr, -EEXIST};
}
MkObjResult mkr{nullptr, -EINVAL};
LookupFHResult fhr;
RGWFileHandle* rgw_fh = nullptr;
buffer::list ux_key, ux_attrs;
fhr = lookup_fh(parent, name,
RGWFileHandle::FLAG_CREATE|
RGWFileHandle::FLAG_SYMBOLIC_LINK|
RGWFileHandle::FLAG_LOCK);
rgw_fh = get<0>(fhr);
if (rgw_fh) {
rgw_fh->create_stat(st, mask);
rgw_fh->set_times(real_clock::now());
/* save attrs */
rgw_fh->encode_attrs(ux_key, ux_attrs);
if (st)
rgw_fh->stat(st);
get<0>(mkr) = rgw_fh;
} else {
get<1>(mkr) = -EIO;
return mkr;
}
/* need valid S3 name (characters, length <= 1024, etc) */
rc = valid_fs_object_name(name);
if (rc != 0) {
rgw_fh->flags |= RGWFileHandle::FLAG_DELETED;
fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh,
RGWFileHandle::FHCache::FLAG_LOCK);
rgw_fh->mtx.unlock();
unref(rgw_fh);
get<0>(mkr) = nullptr;
get<1>(mkr) = rc;
return mkr;
}
string obj_name = std::string(name);
/* create an object representing the directory */
buffer::list bl;
/* XXXX */
#if 0
bl.push_back(
buffer::create_static(len, static_cast<char*>(buffer)));
#else
bl.push_back(
buffer::copy(link_path, strlen(link_path)));
#endif
RGWPutObjRequest req(get_context(), user->clone(), parent->bucket_name(), obj_name, bl);
/* save attrs */
req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
if (! ((rc == 0) &&
(rc2 == 0))) {
/* op failed */
rgw_fh->flags |= RGWFileHandle::FLAG_DELETED;
rgw_fh->mtx.unlock(); /* !LOCKED */
unref(rgw_fh);
get<0>(mkr) = nullptr;
/* fixup rc */
if (!rc)
rc = rc2;
} else {
real_time t = real_clock::now();
parent->set_mtime(real_clock::to_timespec(t));
parent->set_ctime(real_clock::to_timespec(t));
rgw_fh->mtx.unlock(); /* !LOCKED */
}
get<1>(mkr) = rc;
return mkr;
} /* RGWLibFS::symlink */
int RGWLibFS::getattr(RGWFileHandle* rgw_fh, struct stat* st)
{
switch(rgw_fh->fh.fh_type) {
case RGW_FS_TYPE_FILE:
{
if (rgw_fh->deleted())
return -ESTALE;
}
break;
default:
break;
};
/* if rgw_fh is a directory, mtime will be advanced */
return rgw_fh->stat(st);
} /* RGWLibFS::getattr */
int RGWLibFS::setattr(RGWFileHandle* rgw_fh, struct stat* st, uint32_t mask,
uint32_t flags)
{
int rc, rc2;
buffer::list ux_key, ux_attrs;
buffer::list etag = rgw_fh->get_etag();
buffer::list acls = rgw_fh->get_acls();
lock_guard guard(rgw_fh->mtx);
switch(rgw_fh->fh.fh_type) {
case RGW_FS_TYPE_FILE:
{
if (rgw_fh->deleted())
return -ESTALE;
}
break;
default:
break;
};
string obj_name{rgw_fh->relative_object_name()};
if (rgw_fh->is_dir() &&
(likely(! rgw_fh->is_bucket()))) {
obj_name += "/";
}
RGWSetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name);
rgw_fh->create_stat(st, mask);
rgw_fh->encode_attrs(ux_key, ux_attrs);
/* save attrs */
req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
req.emplace_attr(RGW_ATTR_ETAG, std::move(etag));
req.emplace_attr(RGW_ATTR_ACL, std::move(acls));
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
if (rc == -ENOENT) {
/* special case: materialize placeholder dir */
buffer::list bl;
RGWPutObjRequest req(get_context(), user->clone(), rgw_fh->bucket_name(), obj_name, bl);
rgw_fh->encode_attrs(ux_key, ux_attrs); /* because std::moved */
/* save attrs */
req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
}
if ((rc != 0) || (rc2 != 0)) {
return -EIO;
}
rgw_fh->set_ctime(real_clock::to_timespec(real_clock::now()));
return 0;
} /* RGWLibFS::setattr */
static inline std::string prefix_xattr_keystr(const rgw_xattrstr& key) {
std::string keystr;
keystr.reserve(sizeof(RGW_ATTR_META_PREFIX) + key.len);
keystr += string{RGW_ATTR_META_PREFIX};
keystr += string{key.val, key.len};
return keystr;
}
static inline std::string_view unprefix_xattr_keystr(const std::string& key)
{
std::string_view svk{key};
auto pos = svk.find(RGW_ATTR_META_PREFIX);
if (pos == std::string_view::npos) {
return std::string_view{""};
} else if (pos == 0) {
svk.remove_prefix(sizeof(RGW_ATTR_META_PREFIX)-1);
}
return svk;
}
int RGWLibFS::getxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist *attrs,
rgw_getxattr_cb cb, void *cb_arg,
uint32_t flags)
{
/* cannot store on fs_root, should not on buckets? */
if ((rgw_fh->is_bucket()) ||
(rgw_fh->is_root())) {
return -EINVAL;
}
int rc, rc2, rc3;
string obj_name{rgw_fh->relative_object_name2()};
RGWGetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name);
for (uint32_t ix = 0; ix < attrs->xattr_cnt; ++ix) {
auto& xattr = attrs->xattrs[ix];
/* pass exposed attr keys as given, else prefix */
std::string k = is_exposed_attr(xattr.key)
? std::string{xattr.key.val, xattr.key.len}
: prefix_xattr_keystr(xattr.key);
req.emplace_key(std::move(k));
}
if (ldlog_p1(get_context(), ceph_subsys_rgw, 15)) {
lsubdout(get_context(), rgw, 15)
<< __func__
<< " get keys for: "
<< rgw_fh->object_name()
<< " keys:"
<< dendl;
for (const auto& attr: req.get_attrs()) {
lsubdout(get_context(), rgw, 15)
<< "\tkey: " << attr.first << dendl;
}
}
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
rc3 = ((rc == 0) && (rc2 == 0)) ? 0 : -EIO;
/* call back w/xattr data */
if (rc3 == 0) {
const auto& attrs = req.get_attrs();
for (const auto& attr : attrs) {
if (!attr.second.has_value())
continue;
const auto& k = attr.first;
const auto& v = attr.second.value();
/* return exposed attr keys as given, else unprefix --
* yes, we could have memoized the exposed check, but
* to be efficient it would need to be saved with
* RGWGetAttrs::attrs, I think */
std::string_view svk =
is_exposed_attr(rgw_xattrstr{const_cast<char*>(k.c_str()),
uint32_t(k.length())})
? k
: unprefix_xattr_keystr(k);
/* skip entries not matching prefix */
if (svk.empty())
continue;
rgw_xattrstr xattr_k = { const_cast<char*>(svk.data()),
uint32_t(svk.length())};
rgw_xattrstr xattr_v =
{const_cast<char*>(const_cast<buffer::list&>(v).c_str()),
uint32_t(v.length())};
rgw_xattr xattr = { xattr_k, xattr_v };
rgw_xattrlist xattrlist = { &xattr, 1 };
cb(&xattrlist, cb_arg, RGW_GETXATTR_FLAG_NONE);
}
}
return rc3;
} /* RGWLibFS::getxattrs */
int RGWLibFS::lsxattrs(
RGWFileHandle* rgw_fh, rgw_xattrstr *filter_prefix, rgw_getxattr_cb cb,
void *cb_arg, uint32_t flags)
{
/* cannot store on fs_root, should not on buckets? */
if ((rgw_fh->is_bucket()) ||
(rgw_fh->is_root())) {
return -EINVAL;
}
int rc, rc2, rc3;
string obj_name{rgw_fh->relative_object_name2()};
RGWGetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name);
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
rc3 = ((rc == 0) && (rc2 == 0)) ? 0 : -EIO;
/* call back w/xattr data--check for eof */
if (rc3 == 0) {
const auto& keys = req.get_attrs();
for (const auto& k : keys) {
/* return exposed attr keys as given, else unprefix */
std::string_view svk =
is_exposed_attr(rgw_xattrstr{const_cast<char*>(k.first.c_str()),
uint32_t(k.first.length())})
? k.first
: unprefix_xattr_keystr(k.first);
/* skip entries not matching prefix */
if (svk.empty())
continue;
rgw_xattrstr xattr_k = { const_cast<char*>(svk.data()),
uint32_t(svk.length())};
rgw_xattrstr xattr_v = { nullptr, 0 };
rgw_xattr xattr = { xattr_k, xattr_v };
rgw_xattrlist xattrlist = { &xattr, 1 };
auto cbr = cb(&xattrlist, cb_arg, RGW_LSXATTR_FLAG_NONE);
if (cbr & RGW_LSXATTR_FLAG_STOP)
break;
}
}
return rc3;
} /* RGWLibFS::lsxattrs */
int RGWLibFS::setxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist *attrs,
uint32_t flags)
{
/* cannot store on fs_root, should not on buckets? */
if ((rgw_fh->is_bucket()) ||
(rgw_fh->is_root())) {
return -EINVAL;
}
int rc, rc2;
string obj_name{rgw_fh->relative_object_name2()};
RGWSetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name);
for (uint32_t ix = 0; ix < attrs->xattr_cnt; ++ix) {
auto& xattr = attrs->xattrs[ix];
buffer::list attr_bl;
/* don't allow storing at RGW_ATTR_META_PREFIX */
if (! (xattr.key.len > 0))
continue;
/* reject lexical match with any exposed attr */
if (is_exposed_attr(xattr.key))
continue;
string k = prefix_xattr_keystr(xattr.key);
attr_bl.append(xattr.val.val, xattr.val.len);
req.emplace_attr(k.c_str(), std::move(attr_bl));
}
/* don't send null requests */
if (! (req.get_attrs().size() > 0)) {
return -EINVAL;
}
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
return (((rc == 0) && (rc2 == 0)) ? 0 : -EIO);
} /* RGWLibFS::setxattrs */
int RGWLibFS::rmxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs,
uint32_t flags)
{
/* cannot store on fs_root, should not on buckets? */
if ((rgw_fh->is_bucket()) ||
(rgw_fh->is_root())) {
return -EINVAL;
}
int rc, rc2;
string obj_name{rgw_fh->relative_object_name2()};
RGWRMAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name);
for (uint32_t ix = 0; ix < attrs->xattr_cnt; ++ix) {
auto& xattr = attrs->xattrs[ix];
/* don't allow storing at RGW_ATTR_META_PREFIX */
if (! (xattr.key.len > 0)) {
continue;
}
string k = prefix_xattr_keystr(xattr.key);
req.emplace_key(std::move(k));
}
/* don't send null requests */
if (! (req.get_attrs().size() > 0)) {
return -EINVAL;
}
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
return (((rc == 0) && (rc2 == 0)) ? 0 : -EIO);
} /* RGWLibFS::rmxattrs */
/* called with rgw_fh->mtx held */
void RGWLibFS::update_fh(RGWFileHandle *rgw_fh)
{
int rc, rc2;
string obj_name{rgw_fh->relative_object_name()};
buffer::list ux_key, ux_attrs;
if (rgw_fh->is_dir() &&
(likely(! rgw_fh->is_bucket()))) {
obj_name += "/";
}
lsubdout(get_context(), rgw, 17)
<< __func__
<< " update old versioned fh : " << obj_name
<< dendl;
RGWSetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name);
rgw_fh->encode_attrs(ux_key, ux_attrs, false);
req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
rc = g_rgwlib->get_fe()->execute_req(&req);
rc2 = req.get_ret();
if ((rc != 0) || (rc2 != 0)) {
lsubdout(get_context(), rgw, 17)
<< __func__
<< " update fh failed : " << obj_name
<< dendl;
}
} /* RGWLibFS::update_fh */
void RGWLibFS::close()
{
state.flags |= FLAG_CLOSED;
class ObjUnref
{
RGWLibFS* fs;
public:
explicit ObjUnref(RGWLibFS* _fs) : fs(_fs) {}
void operator()(RGWFileHandle* fh) const {
lsubdout(fs->get_context(), rgw, 5)
<< __PRETTY_FUNCTION__
<< fh->name
<< " before ObjUnref refs=" << fh->get_refcnt()
<< dendl;
fs->unref(fh);
}
};
/* force cache drain, forces objects to evict */
fh_cache.drain(ObjUnref(this),
RGWFileHandle::FHCache::FLAG_LOCK);
g_rgwlib->get_fe()->get_process()->unregister_fs(this);
rele();
} /* RGWLibFS::close */
inline std::ostream& operator<<(std::ostream &os, fh_key const &fhk) {
os << "<fh_key: bucket=";
os << fhk.fh_hk.bucket;
os << "; object=";
os << fhk.fh_hk.object;
os << ">";
return os;
}
inline std::ostream& operator<<(std::ostream &os, struct timespec const &ts) {
os << "<timespec: tv_sec=";
os << ts.tv_sec;
os << "; tv_nsec=";
os << ts.tv_nsec;
os << ">";
return os;
}
std::ostream& operator<<(std::ostream &os, RGWLibFS::event const &ev) {
os << "<event:";
switch (ev.t) {
case RGWLibFS::event::type::READDIR:
os << "type=READDIR;";
break;
default:
os << "type=UNKNOWN;";
break;
};
os << "fid=" << ev.fhk.fh_hk.bucket << ":" << ev.fhk.fh_hk.object
<< ";ts=" << ev.ts << ">";
return os;
}
void RGWLibFS::gc()
{
using std::get;
using directory = RGWFileHandle::directory;
/* dirent invalidate timeout--basically, the upper-bound on
* inconsistency with the S3 namespace */
auto expire_s
= get_context()->_conf->rgw_nfs_namespace_expire_secs;
/* max events to gc in one cycle */
uint32_t max_ev = get_context()->_conf->rgw_nfs_max_gc;
struct timespec now, expire_ts;
event_vector ve;
bool stop = false;
std::deque<event> &events = state.events;
do {
(void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
lsubdout(get_context(), rgw, 15)
<< "GC: top of expire loop"
<< " now=" << now
<< " expire_s=" << expire_s
<< dendl;
{
lock_guard guard(state.mtx); /* LOCKED */
lsubdout(get_context(), rgw, 15)
<< "GC: processing"
<< " count=" << events.size()
<< " events"
<< dendl;
/* just return if no events */
if (events.empty()) {
return;
}
uint32_t _max_ev =
(events.size() < 500) ? max_ev : (events.size() / 4);
for (uint32_t ix = 0; (ix < _max_ev) && (events.size() > 0); ++ix) {
event& ev = events.front();
expire_ts = ev.ts;
expire_ts.tv_sec += expire_s;
if (expire_ts > now) {
stop = true;
break;
}
ve.push_back(ev);
events.pop_front();
}
} /* anon */
/* !LOCKED */
for (auto& ev : ve) {
lsubdout(get_context(), rgw, 15)
<< "try-expire ev: " << ev << dendl;
if (likely(ev.t == event::type::READDIR)) {
RGWFileHandle* rgw_fh = lookup_handle(ev.fhk.fh_hk);
lsubdout(get_context(), rgw, 15)
<< "ev rgw_fh: " << rgw_fh << dendl;
if (rgw_fh) {
RGWFileHandle::directory* d;
if (unlikely(! rgw_fh->is_dir())) {
lsubdout(get_context(), rgw, 0)
<< __func__
<< " BUG non-directory found with READDIR event "
<< "(" << rgw_fh->bucket_name() << ","
<< rgw_fh->object_name() << ")"
<< dendl;
goto rele;
}
/* maybe clear state */
d = get<directory>(&rgw_fh->variant_type);
if (d) {
struct timespec ev_ts = ev.ts;
lock_guard guard(rgw_fh->mtx);
struct timespec d_last_readdir = d->last_readdir;
if (unlikely(ev_ts < d_last_readdir)) {
/* readdir cycle in progress, don't invalidate */
lsubdout(get_context(), rgw, 15)
<< "GC: delay expiration for "
<< rgw_fh->object_name()
<< " ev.ts=" << ev_ts
<< " last_readdir=" << d_last_readdir
<< dendl;
continue;
} else {
lsubdout(get_context(), rgw, 15)
<< "GC: expiring "
<< rgw_fh->object_name()
<< dendl;
rgw_fh->clear_state();
rgw_fh->invalidate();
}
}
rele:
unref(rgw_fh);
} /* rgw_fh */
} /* event::type::READDIR */
} /* ev */
ve.clear();
} while (! (stop || shutdown));
} /* RGWLibFS::gc */
std::ostream& operator<<(std::ostream &os,
RGWFileHandle const &rgw_fh)
{
const auto& fhk = rgw_fh.get_key();
const auto& fh = const_cast<RGWFileHandle&>(rgw_fh).get_fh();
os << "<RGWFileHandle:";
os << "addr=" << &rgw_fh << ";";
switch (fh->fh_type) {
case RGW_FS_TYPE_DIRECTORY:
os << "type=DIRECTORY;";
break;
case RGW_FS_TYPE_FILE:
os << "type=FILE;";
break;
default:
os << "type=UNKNOWN;";
break;
};
os << "fid=" << fhk.fh_hk.bucket << ":" << fhk.fh_hk.object << ";";
os << "name=" << rgw_fh.object_name() << ";";
os << "refcnt=" << rgw_fh.get_refcnt() << ";";
os << ">";
return os;
}
RGWFileHandle::~RGWFileHandle() {
/* !recycle case, handle may STILL be in handle table, BUT
* the partition lock is not held in this path */
if (fh_hook.is_linked()) {
fs->fh_cache.remove(fh.fh_hk.object, this, FHCache::FLAG_LOCK);
}
/* cond-unref parent */
if (parent && (! parent->is_mount())) {
/* safe because if parent->unref causes its deletion,
* there are a) by refcnt, no other objects/paths pointing
* to it and b) by the semantics of valid iteration of
* fh_lru (observed, e.g., by cohort_lru<T,...>::drain())
* no unsafe iterators reaching it either--n.b., this constraint
* is binding oncode which may in future attempt to e.g.,
* cause the eviction of objects in LRU order */
(void) get_fs()->unref(parent);
}
}
fh_key RGWFileHandle::make_fhk(const std::string& name)
{
std::string tenant = get_fs()->get_user()->user_id.to_str();
if (depth == 0) {
/* S3 bucket -- assert mount-at-bucket case reaches here */
return fh_key(name, name, tenant);
} else {
std::string key_name = make_key_name(name.c_str());
return fh_key(fhk.fh_hk.bucket, key_name.c_str(), tenant);
}
}
void RGWFileHandle::encode_attrs(ceph::buffer::list& ux_key1,
ceph::buffer::list& ux_attrs1,
bool inc_ov)
{
using ceph::encode;
fh_key fhk(this->fh.fh_hk);
encode(fhk, ux_key1);
bool need_ondisk_version =
(fh.fh_type == RGW_FS_TYPE_FILE ||
fh.fh_type == RGW_FS_TYPE_SYMBOLIC_LINK);
if (need_ondisk_version &&
file_ondisk_version < 0) {
file_ondisk_version = 0;
}
encode(*this, ux_attrs1);
if (need_ondisk_version && inc_ov) {
file_ondisk_version++;
}
} /* RGWFileHandle::encode_attrs */
DecodeAttrsResult RGWFileHandle::decode_attrs(const ceph::buffer::list* ux_key1,
const ceph::buffer::list* ux_attrs1)
{
using ceph::decode;
DecodeAttrsResult dar { false, false };
fh_key fhk;
auto bl_iter_key1 = ux_key1->cbegin();
decode(fhk, bl_iter_key1);
get<0>(dar) = true;
// decode to a temporary file handle which may not be
// copied to the current file handle if its file_ondisk_version
// is not newer
RGWFileHandle tmp_fh(fs);
tmp_fh.fh.fh_type = fh.fh_type;
auto bl_iter_unix1 = ux_attrs1->cbegin();
decode(tmp_fh, bl_iter_unix1);
fh.fh_type = tmp_fh.fh.fh_type;
// for file handles that represent files and whose file_ondisk_version
// is newer, no updates are need, otherwise, go updating the current
// file handle
if (!((fh.fh_type == RGW_FS_TYPE_FILE ||
fh.fh_type == RGW_FS_TYPE_SYMBOLIC_LINK) &&
file_ondisk_version >= tmp_fh.file_ondisk_version)) {
// make sure the following "encode" always encode a greater version
file_ondisk_version = tmp_fh.file_ondisk_version + 1;
state.dev = tmp_fh.state.dev;
state.size = tmp_fh.state.size;
state.nlink = tmp_fh.state.nlink;
state.owner_uid = tmp_fh.state.owner_uid;
state.owner_gid = tmp_fh.state.owner_gid;
state.unix_mode = tmp_fh.state.unix_mode;
state.ctime = tmp_fh.state.ctime;
state.mtime = tmp_fh.state.mtime;
state.atime = tmp_fh.state.atime;
state.version = tmp_fh.state.version;
}
if (this->state.version < 2) {
get<1>(dar) = true;
}
return dar;
} /* RGWFileHandle::decode_attrs */
bool RGWFileHandle::reclaim(const cohort::lru::ObjectFactory* newobj_fac) {
lsubdout(fs->get_context(), rgw, 17)
<< __func__ << " " << *this
<< dendl;
auto factory = dynamic_cast<const RGWFileHandle::Factory*>(newobj_fac);
if (factory == nullptr) {
return false;
}
/* make sure the reclaiming object is the same partiton with newobject factory,
* then we can recycle the object, and replace with newobject */
if (!fs->fh_cache.is_same_partition(factory->fhk.fh_hk.object, fh.fh_hk.object)) {
return false;
}
/* in the non-delete case, handle may still be in handle table */
if (fh_hook.is_linked()) {
/* in this case, we are being called from a context which holds
* the partition lock */
fs->fh_cache.remove(fh.fh_hk.object, this, FHCache::FLAG_NONE);
}
return true;
} /* RGWFileHandle::reclaim */
bool RGWFileHandle::has_children() const
{
if (unlikely(! is_dir()))
return false;
RGWRMdirCheck req(fs->get_context(),
g_rgwlib->get_driver()->get_user(fs->get_user()->user_id),
this);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if (! rc) {
return req.valid && req.has_children;
}
return false;
}
std::ostream& operator<<(std::ostream &os,
RGWFileHandle::readdir_offset const &offset)
{
using boost::get;
if (unlikely(!! get<uint64_t*>(&offset))) {
uint64_t* ioff = get<uint64_t*>(offset);
os << *ioff;
}
else
os << get<const char*>(offset);
return os;
}
int RGWFileHandle::readdir(rgw_readdir_cb rcb, void *cb_arg,
readdir_offset offset,
bool *eof, uint32_t flags)
{
using event = RGWLibFS::event;
using boost::get;
int rc = 0;
struct timespec now;
CephContext* cct = fs->get_context();
lsubdout(cct, rgw, 10)
<< __func__ << " readdir called on "
<< object_name()
<< dendl;
directory* d = get<directory>(&variant_type);
if (d) {
(void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); /* !LOCKED */
lock_guard guard(mtx);
d->last_readdir = now;
}
bool initial_off;
char* mk{nullptr};
if (likely(!! get<const char*>(&offset))) {
mk = const_cast<char*>(get<const char*>(offset));
initial_off = !mk;
} else {
initial_off = (*get<uint64_t*>(offset) == 0);
}
if (is_root()) {
RGWListBucketsRequest req(cct, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id),
this, rcb, cb_arg, offset);
rc = g_rgwlib->get_fe()->execute_req(&req);
if (! rc) {
(void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); /* !LOCKED */
lock_guard guard(mtx);
state.atime = now;
if (initial_off)
set_nlink(2);
inc_nlink(req.d_count);
*eof = req.eof();
}
} else {
RGWReaddirRequest req(cct, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id),
this, rcb, cb_arg, offset);
rc = g_rgwlib->get_fe()->execute_req(&req);
if (! rc) {
(void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); /* !LOCKED */
lock_guard guard(mtx);
state.atime = now;
if (initial_off)
set_nlink(2);
inc_nlink(req.d_count);
*eof = req.eof();
}
}
event ev(event::type::READDIR, get_key(), state.atime);
lock_guard sguard(fs->state.mtx);
fs->state.push_event(ev);
lsubdout(fs->get_context(), rgw, 15)
<< __func__
<< " final link count=" << state.nlink
<< dendl;
return rc;
} /* RGWFileHandle::readdir */
int RGWFileHandle::write(uint64_t off, size_t len, size_t *bytes_written,
void *buffer)
{
using std::get;
using WriteCompletion = RGWLibFS::WriteCompletion;
lock_guard guard(mtx);
int rc = 0;
file* f = get<file>(&variant_type);
if (! f)
return -EISDIR;
if (deleted()) {
lsubdout(fs->get_context(), rgw, 5)
<< __func__
<< " write attempted on deleted object "
<< this->object_name()
<< dendl;
/* zap write transaction, if any */
if (f->write_req) {
delete f->write_req;
f->write_req = nullptr;
}
return -ESTALE;
}
if (! f->write_req) {
/* guard--we do not support (e.g., COW-backed) partial writes */
if (off != 0) {
lsubdout(fs->get_context(), rgw, 5)
<< __func__
<< " " << object_name()
<< " non-0 initial write position " << off
<< " (mounting with -o sync required)"
<< dendl;
return -EIO;
}
const RGWProcessEnv& penv = g_rgwlib->get_fe()->get_process()->get_env();
/* start */
std::string object_name = relative_object_name();
f->write_req =
new RGWWriteRequest(g_rgwlib->get_driver(), penv,
g_rgwlib->get_driver()->get_user(fs->get_user()->user_id),
this, bucket_name(), object_name);
rc = g_rgwlib->get_fe()->start_req(f->write_req);
if (rc < 0) {
lsubdout(fs->get_context(), rgw, 5)
<< __func__
<< this->object_name()
<< " write start failed " << off
<< " (" << rc << ")"
<< dendl;
/* zap failed write transaction */
delete f->write_req;
f->write_req = nullptr;
return -EIO;
} else {
if (stateless_open()) {
/* start write timer */
f->write_req->timer_id =
RGWLibFS::write_timer.add_event(
std::chrono::seconds(RGWLibFS::write_completion_interval_s),
WriteCompletion(*this));
}
}
}
int overlap = 0;
if ((static_cast<off_t>(off) < f->write_req->real_ofs) &&
((f->write_req->real_ofs - off) <= len)) {
overlap = f->write_req->real_ofs - off;
off = f->write_req->real_ofs;
buffer = static_cast<char*>(buffer) + overlap;
len -= overlap;
}
buffer::list bl;
/* XXXX */
#if 0
bl.push_back(
buffer::create_static(len, static_cast<char*>(buffer)));
#else
bl.push_back(
buffer::copy(static_cast<char*>(buffer), len));
#endif
f->write_req->put_data(off, bl);
rc = f->write_req->exec_continue();
if (rc == 0) {
size_t min_size = off + len;
if (min_size > get_size())
set_size(min_size);
if (stateless_open()) {
/* bump write timer */
RGWLibFS::write_timer.adjust_event(
f->write_req->timer_id, std::chrono::seconds(10));
}
} else {
/* continuation failed (e.g., non-contiguous write position) */
lsubdout(fs->get_context(), rgw, 5)
<< __func__
<< object_name()
<< " failed write at position " << off
<< " (fails write transaction) "
<< dendl;
/* zap failed write transaction */
delete f->write_req;
f->write_req = nullptr;
rc = -EIO;
}
*bytes_written = (rc == 0) ? (len + overlap) : 0;
return rc;
} /* RGWFileHandle::write */
int RGWFileHandle::write_finish(uint32_t flags)
{
unique_lock guard{mtx, std::defer_lock};
int rc = 0;
if (! (flags & FLAG_LOCKED)) {
guard.lock();
}
file* f = get<file>(&variant_type);
if (f && (f->write_req)) {
lsubdout(fs->get_context(), rgw, 10)
<< __func__
<< " finishing write trans on " << object_name()
<< dendl;
rc = g_rgwlib->get_fe()->finish_req(f->write_req);
if (! rc) {
rc = f->write_req->get_ret();
}
delete f->write_req;
f->write_req = nullptr;
}
return rc;
} /* RGWFileHandle::write_finish */
int RGWFileHandle::close()
{
lock_guard guard(mtx);
int rc = write_finish(FLAG_LOCKED);
flags &= ~FLAG_OPEN;
flags &= ~FLAG_STATELESS_OPEN;
return rc;
} /* RGWFileHandle::close */
RGWFileHandle::file::~file()
{
delete write_req;
}
void RGWFileHandle::clear_state()
{
directory* d = get<directory>(&variant_type);
if (d) {
state.nlink = 2;
d->last_marker = rgw_obj_key{};
}
}
void RGWFileHandle::advance_mtime(uint32_t flags) {
/* intended for use on directories, fast-forward mtime so as to
* ensure a new, higher value for the change attribute */
unique_lock uniq(mtx, std::defer_lock);
if (likely(! (flags & RGWFileHandle::FLAG_LOCKED))) {
uniq.lock();
}
/* advance mtime only if stored mtime is older than the
* configured namespace expiration */
auto now = real_clock::now();
auto cmptime = state.mtime;
cmptime.tv_sec +=
fs->get_context()->_conf->rgw_nfs_namespace_expire_secs;
if (cmptime < real_clock::to_timespec(now)) {
/* sets ctime as well as mtime, to avoid masking updates should
* ctime inexplicably hold a higher value */
set_times(now);
}
}
void RGWFileHandle::invalidate() {
RGWLibFS *fs = get_fs();
if (fs->invalidate_cb) {
fs->invalidate_cb(fs->invalidate_arg, get_key().fh_hk);
}
}
int RGWWriteRequest::exec_start() {
req_state* state = get_state();
/* Object needs a bucket from this point */
state->object->set_bucket(state->bucket.get());
auto compression_type =
get_driver()->get_compression_type(state->bucket->get_placement_rule());
/* not obviously supportable */
ceph_assert(! dlo_manifest);
ceph_assert(! slo_info);
perfcounter->inc(l_rgw_put);
op_ret = -EINVAL;
if (state->object->empty()) {
ldout(state->cct, 0) << __func__ << " called on empty object" << dendl;
goto done;
}
op_ret = get_params(null_yield);
if (op_ret < 0)
goto done;
op_ret = get_system_versioning_params(state, &olh_epoch, &version_id);
if (op_ret < 0) {
goto done;
}
/* user-supplied MD5 check skipped (not supplied) */
/* early quota check skipped--we don't have size yet */
/* skipping user-supplied etag--we might have one in future, but
* like data it and other attrs would arrive after open */
aio.emplace(state->cct->_conf->rgw_put_obj_min_window_size);
if (state->bucket->versioning_enabled()) {
if (!version_id.empty()) {
state->object->set_instance(version_id);
} else {
state->object->gen_rand_obj_instance_name();
version_id = state->object->get_instance();
}
}
processor = get_driver()->get_atomic_writer(this, state->yield, state->object.get(),
state->bucket_owner.get_id(),
&state->dest_placement, 0, state->req_id);
op_ret = processor->prepare(state->yield);
if (op_ret < 0) {
ldout(state->cct, 20) << "processor->prepare() returned ret=" << op_ret
<< dendl;
goto done;
}
filter = &*processor;
if (compression_type != "none") {
plugin = Compressor::create(state->cct, compression_type);
if (! plugin) {
ldout(state->cct, 1) << "Cannot load plugin for rgw_compression_type "
<< compression_type << dendl;
} else {
compressor.emplace(state->cct, plugin, filter);
filter = &*compressor;
}
}
done:
return op_ret;
} /* exec_start */
int RGWWriteRequest::exec_continue()
{
req_state* state = get_state();
op_ret = 0;
/* check guards (e.g., contig write) */
if (eio) {
ldout(state->cct, 5)
<< " chunks arrived in wrong order"
<< " (mounting with -o sync required)"
<< dendl;
return -EIO;
}
op_ret = state->bucket->check_quota(this, quota, real_ofs, null_yield, true);
/* max_size exceed */
if (op_ret < 0)
return -EIO;
size_t len = data.length();
if (! len)
return 0;
hash.Update((const unsigned char *)data.c_str(), data.length());
op_ret = filter->process(std::move(data), ofs);
if (op_ret < 0) {
goto done;
}
bytes_written += len;
done:
return op_ret;
} /* exec_continue */
int RGWWriteRequest::exec_finish()
{
buffer::list bl, aclbl, ux_key, ux_attrs;
map<string, string>::iterator iter;
char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
unsigned char m[CEPH_CRYPTO_MD5_DIGESTSIZE];
req_state* state = get_state();
size_t osize = rgw_fh->get_size();
struct timespec octime = rgw_fh->get_ctime();
struct timespec omtime = rgw_fh->get_mtime();
real_time appx_t = real_clock::now();
state->obj_size = bytes_written;
perfcounter->inc(l_rgw_put_b, state->obj_size);
// flush data in filters
op_ret = filter->process({}, state->obj_size);
if (op_ret < 0) {
goto done;
}
op_ret = state->bucket->check_quota(this, quota, state->obj_size, null_yield, true);
/* max_size exceed */
if (op_ret < 0) {
goto done;
}
hash.Final(m);
if (compressor && compressor->is_compressed()) {
bufferlist tmp;
RGWCompressionInfo cs_info;
cs_info.compression_type = plugin->get_type_name();
cs_info.orig_size = state->obj_size;
cs_info.blocks = std::move(compressor->get_compression_blocks());
encode(cs_info, tmp);
attrs[RGW_ATTR_COMPRESSION] = tmp;
ldpp_dout(this, 20) << "storing " << RGW_ATTR_COMPRESSION
<< " with type=" << cs_info.compression_type
<< ", orig_size=" << cs_info.orig_size
<< ", blocks=" << cs_info.blocks.size() << dendl;
}
buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);
etag = calc_md5;
bl.append(etag.c_str(), etag.size() + 1);
emplace_attr(RGW_ATTR_ETAG, std::move(bl));
policy.encode(aclbl);
emplace_attr(RGW_ATTR_ACL, std::move(aclbl));
/* unix attrs */
rgw_fh->set_mtime(real_clock::to_timespec(appx_t));
rgw_fh->set_ctime(real_clock::to_timespec(appx_t));
rgw_fh->set_size(bytes_written);
rgw_fh->encode_attrs(ux_key, ux_attrs);
emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs));
for (iter = state->generic_attrs.begin(); iter != state->generic_attrs.end();
++iter) {
buffer::list& attrbl = attrs[iter->first];
const string& val = iter->second;
attrbl.append(val.c_str(), val.size() + 1);
}
op_ret = rgw_get_request_metadata(this, state->cct, state->info, attrs);
if (op_ret < 0) {
goto done;
}
encode_delete_at_attr(delete_at, attrs);
/* Add a custom metadata to expose the information whether an object
* is an SLO or not. Appending the attribute must be performed AFTER
* processing any input from user in order to prohibit overwriting. */
if (unlikely(!! slo_info)) {
buffer::list slo_userindicator_bl;
using ceph::encode;
encode("True", slo_userindicator_bl);
emplace_attr(RGW_ATTR_SLO_UINDICATOR, std::move(slo_userindicator_bl));
}
op_ret = processor->complete(state->obj_size, etag, &mtime, real_time(), attrs,
(delete_at ? *delete_at : real_time()),
if_match, if_nomatch, nullptr, nullptr, nullptr,
state->yield);
if (op_ret != 0) {
/* revert attr updates */
rgw_fh->set_mtime(omtime);
rgw_fh->set_ctime(octime);
rgw_fh->set_size(osize);
}
done:
perfcounter->tinc(l_rgw_put_lat, state->time_elapsed());
return op_ret;
} /* exec_finish */
} /* namespace rgw */
/* librgw */
extern "C" {
void rgwfile_version(int *major, int *minor, int *extra)
{
if (major)
*major = LIBRGW_FILE_VER_MAJOR;
if (minor)
*minor = LIBRGW_FILE_VER_MINOR;
if (extra)
*extra = LIBRGW_FILE_VER_EXTRA;
}
/*
attach rgw namespace
*/
int rgw_mount(librgw_t rgw, const char *uid, const char *acc_key,
const char *sec_key, struct rgw_fs **rgw_fs,
uint32_t flags)
{
int rc = 0;
/* stash access data for "mount" */
RGWLibFS* new_fs = new RGWLibFS(static_cast<CephContext*>(rgw), uid, acc_key,
sec_key, "/");
ceph_assert(new_fs);
const DoutPrefix dp(g_rgwlib->get_driver()->ctx(), dout_subsys, "rgw mount: ");
rc = new_fs->authorize(&dp, g_rgwlib->get_driver());
if (rc != 0) {
delete new_fs;
return -EINVAL;
}
/* register fs for shared gc */
g_rgwlib->get_fe()->get_process()->register_fs(new_fs);
struct rgw_fs *fs = new_fs->get_fs();
fs->rgw = rgw;
/* XXX we no longer assume "/" is unique, but we aren't tracking the
* roots atm */
*rgw_fs = fs;
return 0;
}
int rgw_mount2(librgw_t rgw, const char *uid, const char *acc_key,
const char *sec_key, const char *root, struct rgw_fs **rgw_fs,
uint32_t flags)
{
int rc = 0;
/* if the config has no value for path/root, choose "/" */
RGWLibFS* new_fs{nullptr};
if(root &&
(!strcmp(root, ""))) {
/* stash access data for "mount" */
new_fs = new RGWLibFS(
static_cast<CephContext*>(rgw), uid, acc_key, sec_key, "/");
}
else {
/* stash access data for "mount" */
new_fs = new RGWLibFS(
static_cast<CephContext*>(rgw), uid, acc_key, sec_key, root);
}
ceph_assert(new_fs); /* should we be using ceph_assert? */
const DoutPrefix dp(g_rgwlib->get_driver()->ctx(), dout_subsys, "rgw mount2: ");
rc = new_fs->authorize(&dp, g_rgwlib->get_driver());
if (rc != 0) {
delete new_fs;
return -EINVAL;
}
/* register fs for shared gc */
g_rgwlib->get_fe()->get_process()->register_fs(new_fs);
struct rgw_fs *fs = new_fs->get_fs();
fs->rgw = rgw;
/* XXX we no longer assume "/" is unique, but we aren't tracking the
* roots atm */
*rgw_fs = fs;
return 0;
}
/*
register invalidate callbacks
*/
int rgw_register_invalidate(struct rgw_fs *rgw_fs, rgw_fh_callback_t cb,
void *arg, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
return fs->register_invalidate(cb, arg, flags);
}
/*
detach rgw namespace
*/
int rgw_umount(struct rgw_fs *rgw_fs, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
fs->close();
return 0;
}
/*
get filesystem attributes
*/
int rgw_statfs(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh,
struct rgw_statvfs *vfs_st, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
struct rados_cluster_stat_t stats;
RGWGetClusterStatReq req(fs->get_context(),
g_rgwlib->get_driver()->get_user(fs->get_user()->user_id),
stats);
int rc = g_rgwlib->get_fe()->execute_req(&req);
if (rc < 0) {
lderr(fs->get_context()) << "ERROR: getting total cluster usage"
<< cpp_strerror(-rc) << dendl;
return rc;
}
//Set block size to 1M.
constexpr uint32_t CEPH_BLOCK_SHIFT = 20;
vfs_st->f_bsize = 1 << CEPH_BLOCK_SHIFT;
vfs_st->f_frsize = 1 << CEPH_BLOCK_SHIFT;
vfs_st->f_blocks = stats.kb >> (CEPH_BLOCK_SHIFT - 10);
vfs_st->f_bfree = stats.kb_avail >> (CEPH_BLOCK_SHIFT - 10);
vfs_st->f_bavail = stats.kb_avail >> (CEPH_BLOCK_SHIFT - 10);
vfs_st->f_files = stats.num_objects;
vfs_st->f_ffree = -1;
vfs_st->f_fsid[0] = fs->get_fsid();
vfs_st->f_fsid[1] = fs->get_fsid();
vfs_st->f_flag = 0;
vfs_st->f_namemax = 4096;
return 0;
}
/*
generic create -- create an empty regular file
*/
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)
{
using std::get;
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* parent = get_rgwfh(parent_fh);
if ((! parent) ||
(parent->is_root()) ||
(parent->is_file())) {
/* bad parent */
return -EINVAL;
}
MkObjResult fhr = fs->create(parent, name, st, mask, flags);
RGWFileHandle *nfh = get<0>(fhr); // nullptr if !success
if (nfh)
*fh = nfh->get_fh();
return get<1>(fhr);
} /* rgw_create */
/*
create a symbolic link
*/
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)
{
using std::get;
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* parent = get_rgwfh(parent_fh);
if ((! parent) ||
(parent->is_root()) ||
(parent->is_file())) {
/* bad parent */
return -EINVAL;
}
MkObjResult fhr = fs->symlink(parent, name, link_path, st, mask, flags);
RGWFileHandle *nfh = get<0>(fhr); // nullptr if !success
if (nfh)
*fh = nfh->get_fh();
return get<1>(fhr);
} /* rgw_symlink */
/*
create a new directory
*/
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)
{
using std::get;
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* parent = get_rgwfh(parent_fh);
if (! parent) {
/* bad parent */
return -EINVAL;
}
MkObjResult fhr = fs->mkdir(parent, name, st, mask, flags);
RGWFileHandle *nfh = get<0>(fhr); // nullptr if !success
if (nfh)
*fh = nfh->get_fh();
return get<1>(fhr);
} /* rgw_mkdir */
/*
rename object
*/
int rgw_rename(struct rgw_fs *rgw_fs,
struct rgw_file_handle *src, const char* src_name,
struct rgw_file_handle *dst, const char* dst_name,
uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* src_fh = get_rgwfh(src);
RGWFileHandle* dst_fh = get_rgwfh(dst);
return fs->rename(src_fh, dst_fh, src_name, dst_name);
}
/*
remove file or directory
*/
int rgw_unlink(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh,
const char *name, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* parent = get_rgwfh(parent_fh);
return fs->unlink(parent, name);
}
/*
lookup object by name (POSIX style)
*/
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)
{
//CephContext* cct = static_cast<CephContext*>(rgw_fs->rgw);
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* parent = get_rgwfh(parent_fh);
if ((! parent) ||
(! parent->is_dir())) {
/* bad parent */
return -EINVAL;
}
RGWFileHandle* rgw_fh;
LookupFHResult fhr;
if (parent->is_root()) {
/* special: parent lookup--note lack of ref()! */
if (unlikely((strcmp(path, "..") == 0) ||
(strcmp(path, "/") == 0))) {
rgw_fh = parent;
} else {
RGWLibFS::BucketStats bstat;
fhr = fs->stat_bucket(parent, path, bstat, RGWFileHandle::FLAG_NONE);
rgw_fh = get<0>(fhr);
if (! rgw_fh)
return -ENOENT;
}
} else {
/* special: after readdir--note extra ref()! */
if (unlikely((strcmp(path, "..") == 0))) {
rgw_fh = parent;
lsubdout(fs->get_context(), rgw, 17)
<< __func__ << " BANG"<< *rgw_fh
<< dendl;
fs->ref(rgw_fh);
} else {
enum rgw_fh_type fh_type = fh_type_of(flags);
uint32_t sl_flags = (flags & RGW_LOOKUP_FLAG_RCB)
? RGWFileHandle::FLAG_IN_CB
: RGWFileHandle::FLAG_EXACT_MATCH;
bool fast_attrs= fs->get_context()->_conf->rgw_nfs_s3_fast_attrs;
if ((flags & RGW_LOOKUP_FLAG_RCB) && fast_attrs) {
/* FAKE STAT--this should mean, interpolate special
* owner, group, and perms masks */
fhr = fs->fake_leaf(parent, path, fh_type, st, mask, sl_flags);
} else {
if ((fh_type == RGW_FS_TYPE_DIRECTORY) && fast_attrs) {
/* trust cached dir, if present */
fhr = fs->lookup_fh(parent, path, RGWFileHandle::FLAG_DIRECTORY);
if (get<0>(fhr)) {
rgw_fh = get<0>(fhr);
goto done;
}
}
fhr = fs->stat_leaf(parent, path, fh_type, sl_flags);
}
if (! get<0>(fhr)) {
if (! (flags & RGW_LOOKUP_FLAG_CREATE))
return -ENOENT;
else
fhr = fs->lookup_fh(parent, path, RGWFileHandle::FLAG_CREATE);
}
rgw_fh = get<0>(fhr);
}
} /* !root */
done:
struct rgw_file_handle *rfh = rgw_fh->get_fh();
*fh = rfh;
return 0;
} /* rgw_lookup */
/*
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)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = fs->lookup_handle(*fh_hk);
if (! rgw_fh) {
/* not found */
return -ENOENT;
}
struct rgw_file_handle *rfh = rgw_fh->get_fh();
*fh = rfh;
return 0;
}
/*
* release file handle
*/
int rgw_fh_rele(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
lsubdout(fs->get_context(), rgw, 17)
<< __func__ << " " << *rgw_fh
<< dendl;
fs->unref(rgw_fh);
return 0;
}
/*
get unix attributes for object
*/
int rgw_getattr(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, struct stat *st, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->getattr(rgw_fh, st);
}
/*
set unix attributes for object
*/
int rgw_setattr(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, struct stat *st,
uint32_t mask, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->setattr(rgw_fh, st, mask, flags);
}
/*
truncate file
*/
int rgw_truncate(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint64_t size, uint32_t flags)
{
return 0;
}
/*
open file
*/
int rgw_open(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint32_t posix_flags, uint32_t flags)
{
RGWFileHandle* rgw_fh = get_rgwfh(fh);
/* XXX
* need to track specific opens--at least read opens and
* a write open; we need to know when a write open is returned,
* that closes a write transaction
*
* for now, we will support single-open only, it's preferable to
* anything we can otherwise do without access to the NFS state
*/
if (! rgw_fh->is_file())
return -EISDIR;
return rgw_fh->open(flags);
}
/*
close file
*/
int rgw_close(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
int rc = rgw_fh->close(/* XXX */);
if (flags & RGW_CLOSE_FLAG_RELE)
fs->unref(rgw_fh);
return rc;
}
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)
{
RGWFileHandle* parent = get_rgwfh(parent_fh);
if (! parent) {
/* bad parent */
return -EINVAL;
}
lsubdout(parent->get_fs()->get_context(), rgw, 15)
<< __func__
<< " offset=" << *offset
<< dendl;
if ((*offset == 0) &&
(flags & RGW_READDIR_FLAG_DOTDOT)) {
/* send '.' and '..' with their NFS-defined offsets */
rcb(".", cb_arg, 1, nullptr, 0, RGW_LOOKUP_FLAG_DIR);
rcb("..", cb_arg, 2, nullptr, 0, RGW_LOOKUP_FLAG_DIR);
}
int rc = parent->readdir(rcb, cb_arg, offset, eof, flags);
return rc;
} /* rgw_readdir */
/* 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)
{
RGWFileHandle* parent = get_rgwfh(parent_fh);
if (! parent) {
/* bad parent */
return -EINVAL;
}
lsubdout(parent->get_fs()->get_context(), rgw, 15)
<< __func__
<< " offset=" << ((name) ? name : "(nil)")
<< dendl;
if ((! name) &&
(flags & RGW_READDIR_FLAG_DOTDOT)) {
/* send '.' and '..' with their NFS-defined offsets */
rcb(".", cb_arg, 1, nullptr, 0, RGW_LOOKUP_FLAG_DIR);
rcb("..", cb_arg, 2, nullptr, 0, RGW_LOOKUP_FLAG_DIR);
}
int rc = parent->readdir(rcb, cb_arg, name, eof, flags);
return rc;
} /* rgw_readdir2 */
/* project offset of dirent name */
int rgw_dirent_offset(struct rgw_fs *rgw_fs,
struct rgw_file_handle *parent_fh,
const char *name, int64_t *offset,
uint32_t flags)
{
RGWFileHandle* parent = get_rgwfh(parent_fh);
if ((! parent)) {
/* bad parent */
return -EINVAL;
}
std::string sname{name};
int rc = parent->offset_of(sname, offset, flags);
return rc;
}
/*
read data from file
*/
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)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->read(rgw_fh, offset, length, bytes_read, buffer, flags);
}
/*
read symbolic link
*/
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)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->readlink(rgw_fh, offset, length, bytes_read, buffer, flags);
}
/*
write data to file
*/
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)
{
RGWFileHandle* rgw_fh = get_rgwfh(fh);
int rc;
*bytes_written = 0;
if (! rgw_fh->is_file())
return -EISDIR;
if (! rgw_fh->is_open()) {
if (flags & RGW_OPEN_FLAG_V3) {
rc = rgw_fh->open(flags);
if (!! rc)
return rc;
} else
return -EPERM;
}
rc = rgw_fh->write(offset, length, bytes_written, buffer);
return rc;
}
/*
read data from file (vector)
*/
class RGWReadV
{
buffer::list bl;
struct rgw_vio* vio;
public:
RGWReadV(buffer::list& _bl, rgw_vio* _vio) : vio(_vio) {
bl = std::move(_bl);
}
struct rgw_vio* get_vio() { return vio; }
const auto& buffers() { return bl.buffers(); }
unsigned /* XXX */ length() { return bl.length(); }
};
void rgw_readv_rele(struct rgw_uio *uio, uint32_t flags)
{
RGWReadV* rdv = static_cast<RGWReadV*>(uio->uio_p1);
rdv->~RGWReadV();
::operator delete(rdv);
}
int rgw_readv(struct rgw_fs *rgw_fs,
struct rgw_file_handle *fh, rgw_uio *uio, uint32_t flags)
{
#if 0 /* XXX */
CephContext* cct = static_cast<CephContext*>(rgw_fs->rgw);
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
if (! rgw_fh->is_file())
return -EINVAL;
int rc = 0;
buffer::list bl;
RGWGetObjRequest req(cct, fs->get_user(), rgw_fh->bucket_name(),
rgw_fh->object_name(), uio->uio_offset, uio->uio_resid,
bl);
req.do_hexdump = false;
rc = g_rgwlib->get_fe()->execute_req(&req);
if (! rc) {
RGWReadV* rdv = static_cast<RGWReadV*>(
::operator new(sizeof(RGWReadV) +
(bl.buffers().size() * sizeof(struct rgw_vio))));
(void) new (rdv)
RGWReadV(bl, reinterpret_cast<rgw_vio*>(rdv+sizeof(RGWReadV)));
uio->uio_p1 = rdv;
uio->uio_cnt = rdv->buffers().size();
uio->uio_resid = rdv->length();
uio->uio_vio = rdv->get_vio();
uio->uio_rele = rgw_readv_rele;
int ix = 0;
auto& buffers = rdv->buffers();
for (auto& bp : buffers) {
rgw_vio *vio = &(uio->uio_vio[ix]);
vio->vio_base = const_cast<char*>(bp.c_str());
vio->vio_len = bp.length();
vio->vio_u1 = nullptr;
vio->vio_p1 = nullptr;
++ix;
}
}
return rc;
#else
return 0;
#endif
}
/*
write data to file (vector)
*/
int rgw_writev(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_uio *uio, uint32_t flags)
{
// not supported - rest of function is ignored
return -ENOTSUP;
CephContext* cct = static_cast<CephContext*>(rgw_fs->rgw);
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
if (! rgw_fh->is_file())
return -EINVAL;
buffer::list bl;
for (unsigned int ix = 0; ix < uio->uio_cnt; ++ix) {
rgw_vio *vio = &(uio->uio_vio[ix]);
bl.push_back(
buffer::create_static(vio->vio_len,
static_cast<char*>(vio->vio_base)));
}
std::string oname = rgw_fh->relative_object_name();
RGWPutObjRequest req(cct, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id),
rgw_fh->bucket_name(), oname, bl);
int rc = g_rgwlib->get_fe()->execute_req(&req);
/* XXX update size (in request) */
return rc;
}
/*
sync written data
*/
int rgw_fsync(struct rgw_fs *rgw_fs, struct rgw_file_handle *handle,
uint32_t flags)
{
return 0;
}
int rgw_commit(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
uint64_t offset, uint64_t length, uint32_t flags)
{
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return rgw_fh->commit(offset, length, RGWFileHandle::FLAG_NONE);
}
/*
extended attributes
*/
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)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->getxattrs(rgw_fh, attrs, cb, cb_arg, flags);
}
int rgw_lsxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrstr *filter_prefix /* ignored */,
rgw_getxattr_cb cb, void *cb_arg, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->lsxattrs(rgw_fh, filter_prefix, cb, cb_arg, flags);
}
int rgw_setxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrlist *attrs, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->setxattrs(rgw_fh, attrs, flags);
}
int rgw_rmxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh,
rgw_xattrlist *attrs, uint32_t flags)
{
RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private);
RGWFileHandle* rgw_fh = get_rgwfh(fh);
return fs->rmxattrs(rgw_fh, attrs, flags);
}
} /* extern "C" */
| 75,443 | 26.060258 | 95 |
cc
|
null |
ceph-main/src/rgw/rgw_file.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "include/rados/rgw_file.h"
/* internal header */
#include <string.h>
#include <string_view>
#include <sys/stat.h>
#include <stdint.h>
#include <atomic>
#include <chrono>
#include <thread>
#include <mutex>
#include <vector>
#include <deque>
#include <algorithm>
#include <functional>
#include <boost/intrusive_ptr.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/variant.hpp>
#include <boost/optional.hpp>
#include "xxhash.h"
#include "include/buffer.h"
#include "common/cohort_lru.h"
#include "common/ceph_timer.h"
#include "rgw_common.h"
#include "rgw_user.h"
#include "rgw_lib.h"
#include "rgw_ldap.h"
#include "rgw_token.h"
#include "rgw_putobj_processor.h"
#include "rgw_aio_throttle.h"
#include "rgw_compression.h"
/* XXX
* ASSERT_H somehow not defined after all the above (which bring
* in common/debug.h [e.g., dout])
*/
#include "include/ceph_assert.h"
#define RGW_RWXMODE (S_IRWXU | S_IRWXG | S_IRWXO)
#define RGW_RWMODE (RGW_RWXMODE & \
~(S_IXUSR | S_IXGRP | S_IXOTH))
namespace rgw {
template <typename T>
static inline void ignore(T &&) {}
namespace bi = boost::intrusive;
class RGWLibFS;
class RGWFileHandle;
class RGWWriteRequest;
inline bool operator <(const struct timespec& lhs,
const struct timespec& rhs) {
if (lhs.tv_sec == rhs.tv_sec)
return lhs.tv_nsec < rhs.tv_nsec;
else
return lhs.tv_sec < rhs.tv_sec;
}
inline bool operator ==(const struct timespec& lhs,
const struct timespec& rhs) {
return ((lhs.tv_sec == rhs.tv_sec) &&
(lhs.tv_nsec == rhs.tv_nsec));
}
/*
* XXX
* The current 64-bit, non-cryptographic hash used here is intended
* for prototyping only.
*
* However, the invariant being prototyped is that objects be
* identifiable by their hash components alone. We believe this can
* be legitimately implemented using 128-hash values for bucket and
* object components, together with a cluster-resident cryptographic
* key. Since an MD5 or SHA-1 key is 128 bits and the (fast),
* non-cryptographic CityHash128 hash algorithm takes a 128-bit seed,
* speculatively we could use that for the final hash computations.
*/
struct fh_key
{
rgw_fh_hk fh_hk {};
uint32_t version;
static constexpr uint64_t seed = 8675309;
fh_key() : version(0) {}
fh_key(const rgw_fh_hk& _hk)
: fh_hk(_hk), version(0) {
// nothing
}
fh_key(const uint64_t bk, const uint64_t ok)
: version(0) {
fh_hk.bucket = bk;
fh_hk.object = ok;
}
fh_key(const uint64_t bk, const char *_o, const std::string& _t)
: version(0) {
fh_hk.bucket = bk;
std::string to = _t + ":" + _o;
fh_hk.object = XXH64(to.c_str(), to.length(), seed);
}
fh_key(const std::string& _b, const std::string& _o,
const std::string& _t /* tenant */)
: version(0) {
std::string tb = _t + ":" + _b;
std::string to = _t + ":" + _o;
fh_hk.bucket = XXH64(tb.c_str(), tb.length(), seed);
fh_hk.object = XXH64(to.c_str(), to.length(), seed);
}
void encode(buffer::list& bl) const {
ENCODE_START(2, 1, bl);
encode(fh_hk.bucket, bl);
encode(fh_hk.object, bl);
encode((uint32_t)2, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(fh_hk.bucket, bl);
decode(fh_hk.object, bl);
if (struct_v >= 2) {
decode(version, bl);
}
DECODE_FINISH(bl);
}
friend std::ostream& operator<<(std::ostream &os, fh_key const &fhk);
}; /* fh_key */
WRITE_CLASS_ENCODER(fh_key);
inline bool operator<(const fh_key& lhs, const fh_key& rhs)
{
return ((lhs.fh_hk.bucket < rhs.fh_hk.bucket) ||
((lhs.fh_hk.bucket == rhs.fh_hk.bucket) &&
(lhs.fh_hk.object < rhs.fh_hk.object)));
}
inline bool operator>(const fh_key& lhs, const fh_key& rhs)
{
return (rhs < lhs);
}
inline bool operator==(const fh_key& lhs, const fh_key& rhs)
{
return ((lhs.fh_hk.bucket == rhs.fh_hk.bucket) &&
(lhs.fh_hk.object == rhs.fh_hk.object));
}
inline bool operator!=(const fh_key& lhs, const fh_key& rhs)
{
return !(lhs == rhs);
}
inline bool operator<=(const fh_key& lhs, const fh_key& rhs)
{
return (lhs < rhs) || (lhs == rhs);
}
using boost::variant;
using boost::container::flat_map;
typedef std::tuple<bool, bool> DecodeAttrsResult;
class RGWFileHandle : public cohort::lru::Object
{
struct rgw_file_handle fh;
std::mutex mtx;
RGWLibFS* fs;
RGWFileHandle* bucket;
RGWFileHandle* parent;
std::atomic_int64_t file_ondisk_version; // version of unix attrs, file only
/* const */ std::string name; /* XXX file or bucket name */
/* const */ fh_key fhk;
using lock_guard = std::lock_guard<std::mutex>;
using unique_lock = std::unique_lock<std::mutex>;
/* TODO: keeping just the last marker is sufficient for
* nfs-ganesha 2.4.5; in the near future, nfs-ganesha will
* be able to hint the name of the next dirent required,
* from which we can directly synthesize a RADOS marker.
* using marker_cache_t = flat_map<uint64_t, rgw_obj_key>;
*/
struct State {
uint64_t dev;
uint64_t size;
uint64_t nlink;
uint32_t owner_uid; /* XXX need Unix attr */
uint32_t owner_gid; /* XXX need Unix attr */
mode_t unix_mode;
struct timespec ctime;
struct timespec mtime;
struct timespec atime;
uint32_t version;
State() : dev(0), size(0), nlink(1), owner_uid(0), owner_gid(0), unix_mode(0),
ctime{0,0}, mtime{0,0}, atime{0,0}, version(0) {}
} state;
struct file {
RGWWriteRequest* write_req;
file() : write_req(nullptr) {}
~file();
};
struct directory {
static constexpr uint32_t FLAG_NONE = 0x0000;
uint32_t flags;
rgw_obj_key last_marker;
struct timespec last_readdir;
directory() : flags(FLAG_NONE), last_readdir{0,0} {}
};
void clear_state();
void advance_mtime(uint32_t flags = FLAG_NONE);
boost::variant<file, directory> variant_type;
uint16_t depth;
uint32_t flags;
ceph::buffer::list etag;
ceph::buffer::list acls;
public:
const static std::string root_name;
static constexpr uint16_t MAX_DEPTH = 256;
static constexpr uint32_t FLAG_NONE = 0x0000;
static constexpr uint32_t FLAG_OPEN = 0x0001;
static constexpr uint32_t FLAG_ROOT = 0x0002;
static constexpr uint32_t FLAG_CREATE = 0x0004;
static constexpr uint32_t FLAG_CREATING = 0x0008;
static constexpr uint32_t FLAG_SYMBOLIC_LINK = 0x0009;
static constexpr uint32_t FLAG_DIRECTORY = 0x0010;
static constexpr uint32_t FLAG_BUCKET = 0x0020;
static constexpr uint32_t FLAG_LOCK = 0x0040;
static constexpr uint32_t FLAG_DELETED = 0x0080;
static constexpr uint32_t FLAG_UNLINK_THIS = 0x0100;
static constexpr uint32_t FLAG_LOCKED = 0x0200;
static constexpr uint32_t FLAG_STATELESS_OPEN = 0x0400;
static constexpr uint32_t FLAG_EXACT_MATCH = 0x0800;
static constexpr uint32_t FLAG_MOUNT = 0x1000;
static constexpr uint32_t FLAG_IN_CB = 0x2000;
#define CREATE_FLAGS(x) \
((x) & ~(RGWFileHandle::FLAG_CREATE|RGWFileHandle::FLAG_LOCK))
static constexpr uint32_t RCB_MASK = \
RGW_SETATTR_MTIME|RGW_SETATTR_CTIME|RGW_SETATTR_ATIME|RGW_SETATTR_SIZE;
friend class RGWLibFS;
private:
explicit RGWFileHandle(RGWLibFS* _fs)
: fs(_fs), bucket(nullptr), parent(nullptr), file_ondisk_version(-1),
variant_type{directory()}, depth(0), flags(FLAG_NONE)
{
fh.fh_hk.bucket = 0;
fh.fh_hk.object = 0;
/* root */
fh.fh_type = RGW_FS_TYPE_DIRECTORY;
variant_type = directory();
/* stat */
state.unix_mode = RGW_RWXMODE|S_IFDIR;
/* pointer to self */
fh.fh_private = this;
}
uint64_t init_fsid(std::string& uid) {
return XXH64(uid.c_str(), uid.length(), fh_key::seed);
}
void init_rootfs(std::string& fsid, const std::string& object_name,
bool is_bucket) {
/* fh_key */
fh.fh_hk.bucket = XXH64(fsid.c_str(), fsid.length(), fh_key::seed);
fh.fh_hk.object = XXH64(object_name.c_str(), object_name.length(),
fh_key::seed);
fhk = fh.fh_hk;
name = object_name;
state.dev = init_fsid(fsid);
if (is_bucket) {
flags |= RGWFileHandle::FLAG_BUCKET | RGWFileHandle::FLAG_MOUNT;
bucket = this;
depth = 1;
} else {
flags |= RGWFileHandle::FLAG_ROOT | RGWFileHandle::FLAG_MOUNT;
}
}
void encode(buffer::list& bl) const {
ENCODE_START(3, 1, bl);
encode(uint32_t(fh.fh_type), bl);
encode(state.dev, bl);
encode(state.size, bl);
encode(state.nlink, bl);
encode(state.owner_uid, bl);
encode(state.owner_gid, bl);
encode(state.unix_mode, bl);
for (const auto& t : { state.ctime, state.mtime, state.atime }) {
encode(real_clock::from_timespec(t), bl);
}
encode((uint32_t)2, bl);
encode(file_ondisk_version.load(), bl);
ENCODE_FINISH(bl);
}
//XXX: RGWFileHandle::decode method can only be called from
// RGWFileHandle::decode_attrs, otherwise the file_ondisk_version
// fied would be contaminated
void decode(bufferlist::const_iterator& bl) {
DECODE_START(3, bl);
uint32_t fh_type;
decode(fh_type, bl);
if ((fh.fh_type != fh_type) &&
(fh_type == RGW_FS_TYPE_SYMBOLIC_LINK))
fh.fh_type = RGW_FS_TYPE_SYMBOLIC_LINK;
decode(state.dev, bl);
decode(state.size, bl);
decode(state.nlink, bl);
decode(state.owner_uid, bl);
decode(state.owner_gid, bl);
decode(state.unix_mode, bl);
ceph::real_time enc_time;
for (auto t : { &(state.ctime), &(state.mtime), &(state.atime) }) {
decode(enc_time, bl);
*t = real_clock::to_timespec(enc_time);
}
if (struct_v >= 2) {
decode(state.version, bl);
}
if (struct_v >= 3) {
int64_t fov;
decode(fov, bl);
file_ondisk_version = fov;
}
DECODE_FINISH(bl);
}
friend void encode(const RGWFileHandle& c, ::ceph::buffer::list &bl, uint64_t features);
friend void decode(RGWFileHandle &c, ::ceph::bufferlist::const_iterator &p);
public:
RGWFileHandle(RGWLibFS* _fs, RGWFileHandle* _parent,
const fh_key& _fhk, std::string& _name, uint32_t _flags)
: fs(_fs), bucket(nullptr), parent(_parent), file_ondisk_version(-1),
name(std::move(_name)), fhk(_fhk), flags(_flags) {
if (parent->is_root()) {
fh.fh_type = RGW_FS_TYPE_DIRECTORY;
variant_type = directory();
flags |= FLAG_BUCKET;
} else {
bucket = parent->is_bucket() ? parent
: parent->bucket;
if (flags & FLAG_DIRECTORY) {
fh.fh_type = RGW_FS_TYPE_DIRECTORY;
variant_type = directory();
} else if(flags & FLAG_SYMBOLIC_LINK) {
fh.fh_type = RGW_FS_TYPE_SYMBOLIC_LINK;
variant_type = file();
} else {
fh.fh_type = RGW_FS_TYPE_FILE;
variant_type = file();
}
}
depth = parent->depth + 1;
/* save constant fhk */
fh.fh_hk = fhk.fh_hk; /* XXX redundant in fh_hk */
/* inherits parent's fsid */
state.dev = parent->state.dev;
switch (fh.fh_type) {
case RGW_FS_TYPE_DIRECTORY:
state.unix_mode = RGW_RWXMODE|S_IFDIR;
/* virtual directories are always invalid */
advance_mtime();
break;
case RGW_FS_TYPE_FILE:
state.unix_mode = RGW_RWMODE|S_IFREG;
break;
case RGW_FS_TYPE_SYMBOLIC_LINK:
state.unix_mode = RGW_RWMODE|S_IFLNK;
break;
default:
break;
}
/* pointer to self */
fh.fh_private = this;
}
const std::string& get_name() const {
return name;
}
const fh_key& get_key() const {
return fhk;
}
directory* get_directory() {
return boost::get<directory>(&variant_type);
}
size_t get_size() const { return state.size; }
const char* stype() {
return is_dir() ? "DIR" : "FILE";
}
uint16_t get_depth() const { return depth; }
struct rgw_file_handle* get_fh() { return &fh; }
RGWLibFS* get_fs() { return fs; }
RGWFileHandle* get_parent() { return parent; }
uint32_t get_owner_uid() const { return state.owner_uid; }
uint32_t get_owner_gid() const { return state.owner_gid; }
struct timespec get_ctime() const { return state.ctime; }
struct timespec get_mtime() const { return state.mtime; }
const ceph::buffer::list& get_etag() const { return etag; }
const ceph::buffer::list& get_acls() const { return acls; }
void create_stat(struct stat* st, uint32_t mask) {
if (mask & RGW_SETATTR_UID)
state.owner_uid = st->st_uid;
if (mask & RGW_SETATTR_GID)
state.owner_gid = st->st_gid;
if (mask & RGW_SETATTR_MODE) {
switch (fh.fh_type) {
case RGW_FS_TYPE_DIRECTORY:
state.unix_mode = st->st_mode|S_IFDIR;
break;
case RGW_FS_TYPE_FILE:
state.unix_mode = st->st_mode|S_IFREG;
break;
case RGW_FS_TYPE_SYMBOLIC_LINK:
state.unix_mode = st->st_mode|S_IFLNK;
break;
default:
break;
}
}
if (mask & RGW_SETATTR_ATIME)
state.atime = st->st_atim;
if (mask & RGW_SETATTR_MTIME) {
if (fh.fh_type != RGW_FS_TYPE_DIRECTORY)
state.mtime = st->st_mtim;
}
if (mask & RGW_SETATTR_CTIME)
state.ctime = st->st_ctim;
}
int stat(struct stat* st, uint32_t flags = FLAG_NONE) {
/* partial Unix attrs */
/* FIPS zeroization audit 20191115: this memset is not security
* related. */
memset(st, 0, sizeof(struct stat));
st->st_dev = state.dev;
st->st_ino = fh.fh_hk.object; // XXX
st->st_uid = state.owner_uid;
st->st_gid = state.owner_gid;
st->st_mode = state.unix_mode;
switch (fh.fh_type) {
case RGW_FS_TYPE_DIRECTORY:
/* virtual directories are always invalid */
advance_mtime(flags);
st->st_nlink = state.nlink;
break;
case RGW_FS_TYPE_FILE:
st->st_nlink = 1;
st->st_blksize = 4096;
st->st_size = state.size;
st->st_blocks = (state.size) / 512;
break;
case RGW_FS_TYPE_SYMBOLIC_LINK:
st->st_nlink = 1;
st->st_blksize = 4096;
st->st_size = state.size;
st->st_blocks = (state.size) / 512;
break;
default:
break;
}
#ifdef HAVE_STAT_ST_MTIMESPEC_TV_NSEC
st->st_atimespec = state.atime;
st->st_mtimespec = state.mtime;
st->st_ctimespec = state.ctime;
#else
st->st_atim = state.atime;
st->st_mtim = state.mtime;
st->st_ctim = state.ctime;
#endif
return 0;
}
const std::string& bucket_name() const {
if (is_root())
return root_name;
if (is_bucket())
return name;
return bucket->object_name();
}
const std::string& object_name() const { return name; }
std::string full_object_name(bool omit_bucket = false) const {
std::string path;
std::vector<const std::string*> segments;
int reserve = 0;
const RGWFileHandle* tfh = this;
while (tfh && !tfh->is_root() && !(tfh->is_bucket() && omit_bucket)) {
segments.push_back(&tfh->object_name());
reserve += (1 + tfh->object_name().length());
tfh = tfh->parent;
}
int pos = 1;
path.reserve(reserve);
for (auto& s : boost::adaptors::reverse(segments)) {
if (pos > 1) {
path += "/";
} else {
if (!omit_bucket &&
((path.length() == 0) || (path.front() != '/')))
path += "/";
}
path += *s;
++pos;
}
return path;
}
inline std::string relative_object_name() const {
return full_object_name(true /* omit_bucket */);
}
inline std::string relative_object_name2() {
std::string rname = full_object_name(true /* omit_bucket */);
if (is_dir()) {
rname += "/";
}
return rname;
}
inline std::string format_child_name(const std::string& cbasename,
bool is_dir) const {
std::string child_name{relative_object_name()};
if ((child_name.size() > 0) &&
(child_name.back() != '/'))
child_name += "/";
child_name += cbasename;
if (is_dir)
child_name += "/";
return child_name;
}
inline std::string make_key_name(const char *name) const {
std::string key_name{full_object_name()};
if (key_name.length() > 0)
key_name += "/";
key_name += name;
return key_name;
}
fh_key make_fhk(const std::string& name);
void add_marker(uint64_t off, const rgw_obj_key& marker,
uint8_t obj_type) {
using std::get;
directory* d = get<directory>(&variant_type);
if (d) {
unique_lock guard(mtx);
d->last_marker = marker;
}
}
const rgw_obj_key* find_marker(uint64_t off) const {
using std::get;
if (off > 0) {
const directory* d = get<directory>(&variant_type);
if (d ) {
return &d->last_marker;
}
}
return nullptr;
}
int offset_of(const std::string& name, int64_t *offset, uint32_t flags) {
if (unlikely(! is_dir())) {
return -EINVAL;
}
*offset = XXH64(name.c_str(), name.length(), fh_key::seed);
return 0;
}
bool is_open() const { return flags & FLAG_OPEN; }
bool is_root() const { return flags & FLAG_ROOT; }
bool is_mount() const { return flags & FLAG_MOUNT; }
bool is_bucket() const { return flags & FLAG_BUCKET; }
bool is_object() const { return !is_bucket(); }
bool is_file() const { return (fh.fh_type == RGW_FS_TYPE_FILE); }
bool is_dir() const { return (fh.fh_type == RGW_FS_TYPE_DIRECTORY); }
bool is_link() const { return (fh.fh_type == RGW_FS_TYPE_SYMBOLIC_LINK); }
bool creating() const { return flags & FLAG_CREATING; }
bool deleted() const { return flags & FLAG_DELETED; }
bool stateless_open() const { return flags & FLAG_STATELESS_OPEN; }
bool has_children() const;
int open(uint32_t gsh_flags) {
lock_guard guard(mtx);
if (! is_open()) {
if (gsh_flags & RGW_OPEN_FLAG_V3) {
flags |= FLAG_STATELESS_OPEN;
}
flags |= FLAG_OPEN;
return 0;
}
return -EPERM;
}
typedef boost::variant<uint64_t*, const char*> readdir_offset;
int readdir(rgw_readdir_cb rcb, void *cb_arg, readdir_offset offset,
bool *eof, uint32_t flags);
int write(uint64_t off, size_t len, size_t *nbytes, void *buffer);
int commit(uint64_t offset, uint64_t length, uint32_t flags) {
/* NFS3 and NFSv4 COMMIT implementation
* the current atomic update strategy doesn't actually permit
* clients to read-stable until either CLOSE (NFSv4+) or the
* expiration of the active write timer (NFS3). In the
* interim, the client may send an arbitrary number of COMMIT
* operations which must return a success result */
return 0;
}
int write_finish(uint32_t flags = FLAG_NONE);
int close();
void open_for_create() {
lock_guard guard(mtx);
flags |= FLAG_CREATING;
}
void clear_creating() {
lock_guard guard(mtx);
flags &= ~FLAG_CREATING;
}
void inc_nlink(const uint64_t n) {
state.nlink += n;
}
void set_nlink(const uint64_t n) {
state.nlink = n;
}
void set_size(const size_t size) {
state.size = size;
}
void set_times(const struct timespec &ts) {
state.ctime = ts;
state.mtime = state.ctime;
state.atime = state.ctime;
}
void set_times(real_time t) {
set_times(real_clock::to_timespec(t));
}
void set_ctime(const struct timespec &ts) {
state.ctime = ts;
}
void set_mtime(const struct timespec &ts) {
state.mtime = ts;
}
void set_atime(const struct timespec &ts) {
state.atime = ts;
}
void set_etag(const ceph::buffer::list& _etag ) {
etag = _etag;
}
void set_acls(const ceph::buffer::list& _acls ) {
acls = _acls;
}
void encode_attrs(ceph::buffer::list& ux_key1,
ceph::buffer::list& ux_attrs1,
bool inc_ov = true);
DecodeAttrsResult decode_attrs(const ceph::buffer::list* ux_key1,
const ceph::buffer::list* ux_attrs1);
void invalidate();
bool reclaim(const cohort::lru::ObjectFactory* newobj_fac) override;
typedef cohort::lru::LRU<std::mutex> FhLRU;
struct FhLT
{
// for internal ordering
bool operator()(const RGWFileHandle& lhs, const RGWFileHandle& rhs) const
{ return (lhs.get_key() < rhs.get_key()); }
// for external search by fh_key
bool operator()(const fh_key& k, const RGWFileHandle& fh) const
{ return k < fh.get_key(); }
bool operator()(const RGWFileHandle& fh, const fh_key& k) const
{ return fh.get_key() < k; }
};
struct FhEQ
{
bool operator()(const RGWFileHandle& lhs, const RGWFileHandle& rhs) const
{ return (lhs.get_key() == rhs.get_key()); }
bool operator()(const fh_key& k, const RGWFileHandle& fh) const
{ return k == fh.get_key(); }
bool operator()(const RGWFileHandle& fh, const fh_key& k) const
{ return fh.get_key() == k; }
};
typedef bi::link_mode<bi::safe_link> link_mode; /* XXX normal */
#if defined(FHCACHE_AVL)
typedef bi::avl_set_member_hook<link_mode> tree_hook_type;
#else
/* RBT */
typedef bi::set_member_hook<link_mode> tree_hook_type;
#endif
tree_hook_type fh_hook;
typedef bi::member_hook<
RGWFileHandle, tree_hook_type, &RGWFileHandle::fh_hook> FhHook;
#if defined(FHCACHE_AVL)
typedef bi::avltree<RGWFileHandle, bi::compare<FhLT>, FhHook> FHTree;
#else
typedef bi::rbtree<RGWFileHandle, bi::compare<FhLT>, FhHook> FhTree;
#endif
typedef cohort::lru::TreeX<RGWFileHandle, FhTree, FhLT, FhEQ, fh_key,
std::mutex> FHCache;
~RGWFileHandle() override;
friend std::ostream& operator<<(std::ostream &os,
RGWFileHandle const &rgw_fh);
class Factory : public cohort::lru::ObjectFactory
{
public:
RGWLibFS* fs;
RGWFileHandle* parent;
const fh_key& fhk;
std::string& name;
uint32_t flags;
Factory() = delete;
Factory(RGWLibFS* _fs, RGWFileHandle* _parent,
const fh_key& _fhk, std::string& _name, uint32_t _flags)
: fs(_fs), parent(_parent), fhk(_fhk), name(_name),
flags(_flags) {}
void recycle (cohort::lru::Object* o) override {
/* re-use an existing object */
o->~Object(); // call lru::Object virtual dtor
// placement new!
new (o) RGWFileHandle(fs, parent, fhk, name, flags);
}
cohort::lru::Object* alloc() override {
return new RGWFileHandle(fs, parent, fhk, name, flags);
}
}; /* Factory */
}; /* RGWFileHandle */
WRITE_CLASS_ENCODER(RGWFileHandle);
inline RGWFileHandle* get_rgwfh(struct rgw_file_handle* fh) {
return static_cast<RGWFileHandle*>(fh->fh_private);
}
inline enum rgw_fh_type fh_type_of(uint32_t flags) {
enum rgw_fh_type fh_type;
switch(flags & RGW_LOOKUP_TYPE_FLAGS)
{
case RGW_LOOKUP_FLAG_DIR:
fh_type = RGW_FS_TYPE_DIRECTORY;
break;
case RGW_LOOKUP_FLAG_FILE:
fh_type = RGW_FS_TYPE_FILE;
break;
default:
fh_type = RGW_FS_TYPE_NIL;
};
return fh_type;
}
typedef std::tuple<RGWFileHandle*, uint32_t> LookupFHResult;
typedef std::tuple<RGWFileHandle*, int> MkObjResult;
class RGWLibFS
{
CephContext* cct;
struct rgw_fs fs{};
RGWFileHandle root_fh;
rgw_fh_callback_t invalidate_cb;
void *invalidate_arg;
bool shutdown;
mutable std::atomic<uint64_t> refcnt;
RGWFileHandle::FHCache fh_cache;
RGWFileHandle::FhLRU fh_lru;
std::string uid; // should match user.user_id, iiuc
std::unique_ptr<rgw::sal::User> user;
RGWAccessKey key; // XXXX acc_key
static std::atomic<uint32_t> fs_inst_counter;
static uint32_t write_completion_interval_s;
using lock_guard = std::lock_guard<std::mutex>;
using unique_lock = std::unique_lock<std::mutex>;
struct event
{
enum class type : uint8_t { READDIR } ;
type t;
const fh_key fhk;
struct timespec ts;
event(type t, const fh_key& k, const struct timespec& ts)
: t(t), fhk(k), ts(ts) {}
};
friend std::ostream& operator<<(std::ostream &os,
RGWLibFS::event const &ev);
using event_vector = /* boost::small_vector<event, 16> */
std::vector<event>;
struct WriteCompletion
{
RGWFileHandle& rgw_fh;
explicit WriteCompletion(RGWFileHandle& _fh) : rgw_fh(_fh) {
rgw_fh.get_fs()->ref(&rgw_fh);
}
void operator()() {
rgw_fh.close(); /* will finish in-progress write */
rgw_fh.get_fs()->unref(&rgw_fh);
}
};
static ceph::timer<ceph::mono_clock> write_timer;
struct State {
std::mutex mtx;
std::atomic<uint32_t> flags;
std::deque<event> events;
State() : flags(0) {}
void push_event(const event& ev) {
events.push_back(ev);
}
} state;
uint32_t new_inst() {
return ++fs_inst_counter;
}
friend class RGWFileHandle;
friend class RGWLibProcess;
public:
static constexpr uint32_t FLAG_NONE = 0x0000;
static constexpr uint32_t FLAG_CLOSED = 0x0001;
struct BucketStats {
size_t size;
size_t size_rounded;
real_time creation_time;
uint64_t num_entries;
};
RGWLibFS(CephContext* _cct, const char *_uid, const char *_user_id,
const char* _key, const char *root)
: cct(_cct), root_fh(this), invalidate_cb(nullptr),
invalidate_arg(nullptr), shutdown(false), refcnt(1),
fh_cache(cct->_conf->rgw_nfs_fhcache_partitions,
cct->_conf->rgw_nfs_fhcache_size),
fh_lru(cct->_conf->rgw_nfs_lru_lanes,
cct->_conf->rgw_nfs_lru_lane_hiwat),
uid(_uid), key(_user_id, _key) {
if (!root || !strcmp(root, "/")) {
root_fh.init_rootfs(uid, RGWFileHandle::root_name, false);
} else {
root_fh.init_rootfs(uid, root, true);
}
/* pointer to self */
fs.fs_private = this;
/* expose public root fh */
fs.root_fh = root_fh.get_fh();
new_inst();
}
friend void intrusive_ptr_add_ref(const RGWLibFS* fs) {
fs->refcnt.fetch_add(1, std::memory_order_relaxed);
}
friend void intrusive_ptr_release(const RGWLibFS* fs) {
if (fs->refcnt.fetch_sub(1, std::memory_order_release) == 0) {
std::atomic_thread_fence(std::memory_order_acquire);
delete fs;
}
}
RGWLibFS* ref() {
intrusive_ptr_add_ref(this);
return this;
}
inline void rele() {
intrusive_ptr_release(this);
}
void stop() { shutdown = true; }
void release_evict(RGWFileHandle* fh) {
/* remove from cache, releases sentinel ref */
fh_cache.remove(fh->fh.fh_hk.object, fh,
RGWFileHandle::FHCache::FLAG_LOCK);
/* release call-path ref */
(void) fh_lru.unref(fh, cohort::lru::FLAG_NONE);
}
int authorize(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver) {
int ret = driver->get_user_by_access_key(dpp, key.id, null_yield, &user);
if (ret == 0) {
RGWAccessKey* k = user->get_info().get_key(key.id);
if (!k || (k->key != key.key))
return -EINVAL;
if (user->get_info().suspended)
return -ERR_USER_SUSPENDED;
} else {
/* try external authenticators (ldap for now) */
rgw::LDAPHelper* ldh = g_rgwlib->get_ldh(); /* !nullptr */
RGWToken token;
/* boost filters and/or string_ref may throw on invalid input */
try {
token = rgw::from_base64(key.id);
} catch(...) {
token = std::string("");
}
if (token.valid() && (ldh->auth(token.id, token.key) == 0)) {
/* try to driver user if it doesn't already exist */
if (user->load_user(dpp, null_yield) < 0) {
int ret = user->store_user(dpp, null_yield, true);
if (ret < 0) {
lsubdout(get_context(), rgw, 10)
<< "NOTICE: failed to driver new user's info: ret=" << ret
<< dendl;
}
}
} /* auth success */
}
return ret;
} /* authorize */
int register_invalidate(rgw_fh_callback_t cb, void *arg, uint32_t flags) {
invalidate_cb = cb;
invalidate_arg = arg;
return 0;
}
/* find RGWFileHandle by id */
LookupFHResult lookup_fh(const fh_key& fhk,
const uint32_t flags = RGWFileHandle::FLAG_NONE) {
using std::get;
// cast int32_t(RGWFileHandle::FLAG_NONE) due to strictness of Clang
// the cast transfers a lvalue into a rvalue in the ctor
// check the commit message for the full details
LookupFHResult fhr { nullptr, uint32_t(RGWFileHandle::FLAG_NONE) };
RGWFileHandle::FHCache::Latch lat;
bool fh_locked = flags & RGWFileHandle::FLAG_LOCKED;
retry:
RGWFileHandle* fh =
fh_cache.find_latch(fhk.fh_hk.object /* partition selector*/,
fhk /* key */, lat /* serializer */,
RGWFileHandle::FHCache::FLAG_LOCK);
/* LATCHED */
if (fh) {
if (likely(! fh_locked))
fh->mtx.lock(); // XXX !RAII because may-return-LOCKED
/* need initial ref from LRU (fast path) */
if (! fh_lru.ref(fh, cohort::lru::FLAG_INITIAL)) {
lat.lock->unlock();
if (likely(! fh_locked))
fh->mtx.unlock();
goto retry; /* !LATCHED */
}
/* LATCHED, LOCKED */
if (! (flags & RGWFileHandle::FLAG_LOCK))
fh->mtx.unlock(); /* ! LOCKED */
}
lat.lock->unlock(); /* !LATCHED */
get<0>(fhr) = fh;
if (fh) {
lsubdout(get_context(), rgw, 17)
<< __func__ << " 1 " << *fh
<< dendl;
}
return fhr;
} /* lookup_fh(const fh_key&) */
/* find or create an RGWFileHandle */
LookupFHResult lookup_fh(RGWFileHandle* parent, const char *name,
const uint32_t flags = RGWFileHandle::FLAG_NONE) {
using std::get;
// cast int32_t(RGWFileHandle::FLAG_NONE) due to strictness of Clang
// the cast transfers a lvalue into a rvalue in the ctor
// check the commit message for the full details
LookupFHResult fhr { nullptr, uint32_t(RGWFileHandle::FLAG_NONE) };
/* mount is stale? */
if (state.flags & FLAG_CLOSED)
return fhr;
RGWFileHandle::FHCache::Latch lat;
bool fh_locked = flags & RGWFileHandle::FLAG_LOCKED;
std::string obj_name{name};
std::string key_name{parent->make_key_name(name)};
fh_key fhk = parent->make_fhk(obj_name);
lsubdout(get_context(), rgw, 10)
<< __func__ << " called on "
<< parent->object_name() << " for " << key_name
<< " (" << obj_name << ")"
<< " -> " << fhk
<< dendl;
retry:
RGWFileHandle* fh =
fh_cache.find_latch(fhk.fh_hk.object /* partition selector*/,
fhk /* key */, lat /* serializer */,
RGWFileHandle::FHCache::FLAG_LOCK);
/* LATCHED */
if (fh) {
if (likely(! fh_locked))
fh->mtx.lock(); // XXX !RAII because may-return-LOCKED
if (fh->flags & RGWFileHandle::FLAG_DELETED) {
/* for now, delay briefly and retry */
lat.lock->unlock();
if (likely(! fh_locked))
fh->mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
goto retry; /* !LATCHED */
}
/* need initial ref from LRU (fast path) */
if (! fh_lru.ref(fh, cohort::lru::FLAG_INITIAL)) {
lat.lock->unlock();
if (likely(! fh_locked))
fh->mtx.unlock();
goto retry; /* !LATCHED */
}
/* LATCHED, LOCKED */
if (! (flags & RGWFileHandle::FLAG_LOCK))
if (likely(! fh_locked))
fh->mtx.unlock(); /* ! LOCKED */
} else {
/* make or re-use handle */
RGWFileHandle::Factory prototype(this, parent, fhk,
obj_name, CREATE_FLAGS(flags));
uint32_t iflags{cohort::lru::FLAG_INITIAL};
fh = static_cast<RGWFileHandle*>(
fh_lru.insert(&prototype,
cohort::lru::Edge::MRU,
iflags));
if (fh) {
/* lock fh (LATCHED) */
if (flags & RGWFileHandle::FLAG_LOCK)
fh->mtx.lock();
if (likely(! (iflags & cohort::lru::FLAG_RECYCLE))) {
/* inserts at cached insert iterator, releasing latch */
fh_cache.insert_latched(
fh, lat, RGWFileHandle::FHCache::FLAG_UNLOCK);
} else {
/* recycle step invalidates Latch */
fh_cache.insert(
fhk.fh_hk.object, fh, RGWFileHandle::FHCache::FLAG_NONE);
lat.lock->unlock(); /* !LATCHED */
}
get<1>(fhr) |= RGWFileHandle::FLAG_CREATE;
/* ref parent (non-initial ref cannot fail on valid object) */
if (! parent->is_mount()) {
(void) fh_lru.ref(parent, cohort::lru::FLAG_NONE);
}
goto out; /* !LATCHED */
} else {
lat.lock->unlock();
goto retry; /* !LATCHED */
}
}
lat.lock->unlock(); /* !LATCHED */
out:
get<0>(fhr) = fh;
if (fh) {
lsubdout(get_context(), rgw, 17)
<< __func__ << " 2 " << *fh
<< dendl;
}
return fhr;
} /* lookup_fh(RGWFileHandle*, const char *, const uint32_t) */
inline void unref(RGWFileHandle* fh) {
if (likely(! fh->is_mount())) {
(void) fh_lru.unref(fh, cohort::lru::FLAG_NONE);
}
}
inline RGWFileHandle* ref(RGWFileHandle* fh) {
if (likely(! fh->is_mount())) {
fh_lru.ref(fh, cohort::lru::FLAG_NONE);
}
return fh;
}
int getattr(RGWFileHandle* rgw_fh, struct stat* st);
int setattr(RGWFileHandle* rgw_fh, struct stat* st, uint32_t mask,
uint32_t flags);
int getxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs,
rgw_getxattr_cb cb, void *cb_arg, uint32_t flags);
int lsxattrs(RGWFileHandle* rgw_fh, rgw_xattrstr *filter_prefix,
rgw_getxattr_cb cb, void *cb_arg, uint32_t flags);
int setxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs, uint32_t flags);
int rmxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs, uint32_t flags);
void update_fh(RGWFileHandle *rgw_fh);
LookupFHResult stat_bucket(RGWFileHandle* parent, const char *path,
RGWLibFS::BucketStats& bs,
uint32_t flags);
LookupFHResult fake_leaf(RGWFileHandle* parent, const char *path,
enum rgw_fh_type type = RGW_FS_TYPE_NIL,
struct stat *st = nullptr, uint32_t mask = 0,
uint32_t flags = RGWFileHandle::FLAG_NONE);
LookupFHResult stat_leaf(RGWFileHandle* parent, const char *path,
enum rgw_fh_type type = RGW_FS_TYPE_NIL,
uint32_t flags = RGWFileHandle::FLAG_NONE);
int read(RGWFileHandle* rgw_fh, uint64_t offset, size_t length,
size_t* bytes_read, void* buffer, uint32_t flags);
int readlink(RGWFileHandle* rgw_fh, uint64_t offset, size_t length,
size_t* bytes_read, void* buffer, uint32_t flags);
int rename(RGWFileHandle* old_fh, RGWFileHandle* new_fh,
const char *old_name, const char *new_name);
MkObjResult create(RGWFileHandle* parent, const char *name, struct stat *st,
uint32_t mask, uint32_t flags);
MkObjResult symlink(RGWFileHandle* parent, const char *name,
const char *link_path, struct stat *st, uint32_t mask, uint32_t flags);
MkObjResult mkdir(RGWFileHandle* parent, const char *name, struct stat *st,
uint32_t mask, uint32_t flags);
int unlink(RGWFileHandle* rgw_fh, const char *name,
uint32_t flags = FLAG_NONE);
/* find existing RGWFileHandle */
RGWFileHandle* lookup_handle(struct rgw_fh_hk fh_hk) {
if (state.flags & FLAG_CLOSED)
return nullptr;
RGWFileHandle::FHCache::Latch lat;
fh_key fhk(fh_hk);
retry:
RGWFileHandle* fh =
fh_cache.find_latch(fhk.fh_hk.object /* partition selector*/,
fhk /* key */, lat /* serializer */,
RGWFileHandle::FHCache::FLAG_LOCK);
/* LATCHED */
if (! fh) {
if (unlikely(fhk == root_fh.fh.fh_hk)) {
/* lookup for root of this fs */
fh = &root_fh;
goto out;
}
lsubdout(get_context(), rgw, 0)
<< __func__ << " handle lookup failed " << fhk
<< dendl;
goto out;
}
fh->mtx.lock();
if (fh->flags & RGWFileHandle::FLAG_DELETED) {
/* for now, delay briefly and retry */
lat.lock->unlock();
fh->mtx.unlock(); /* !LOCKED */
std::this_thread::sleep_for(std::chrono::milliseconds(20));
goto retry; /* !LATCHED */
}
if (! fh_lru.ref(fh, cohort::lru::FLAG_INITIAL)) {
lat.lock->unlock();
fh->mtx.unlock();
goto retry; /* !LATCHED */
}
/* LATCHED */
fh->mtx.unlock(); /* !LOCKED */
out:
lat.lock->unlock(); /* !LATCHED */
/* special case: lookup root_fh */
if (! fh) {
if (unlikely(fh_hk == root_fh.fh.fh_hk)) {
fh = &root_fh;
}
}
return fh;
}
CephContext* get_context() {
return cct;
}
struct rgw_fs* get_fs() { return &fs; }
RGWFileHandle& get_fh() { return root_fh; }
uint64_t get_fsid() { return root_fh.state.dev; }
RGWUserInfo* get_user() { return &user->get_info(); }
void update_user(const DoutPrefixProvider *dpp) {
(void) g_rgwlib->get_driver()->get_user_by_access_key(dpp, key.id, null_yield, &user);
}
void close();
void gc();
}; /* RGWLibFS */
static inline std::string make_uri(const std::string& bucket_name,
const std::string& object_name) {
std::string uri("/");
uri.reserve(bucket_name.length() + object_name.length() + 2);
uri += bucket_name;
uri += "/";
uri += object_name;
return uri;
}
/*
read directory content (buckets)
*/
class RGWListBucketsRequest : public RGWLibRequest,
public RGWListBuckets /* RGWOp */
{
public:
RGWFileHandle* rgw_fh;
RGWFileHandle::readdir_offset offset;
void* cb_arg;
rgw_readdir_cb rcb;
uint64_t* ioff;
size_t ix;
uint32_t d_count;
bool rcb_eof; // caller forced early stop in readdir cycle
RGWListBucketsRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
RGWFileHandle* _rgw_fh, rgw_readdir_cb _rcb,
void* _cb_arg, RGWFileHandle::readdir_offset& _offset)
: RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), offset(_offset),
cb_arg(_cb_arg), rcb(_rcb), ioff(nullptr), ix(0), d_count(0),
rcb_eof(false) {
using boost::get;
if (unlikely(!! get<uint64_t*>(&offset))) {
ioff = get<uint64_t*>(offset);
const auto& mk = rgw_fh->find_marker(*ioff);
if (mk) {
marker = mk->name;
}
} else {
const char* mk = get<const char*>(offset);
if (mk) {
marker = mk;
}
}
op = this;
}
bool only_bucket() override { return false; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
/* XXX derp derp derp */
state->relative_uri = "/";
state->info.request_uri = "/"; // XXX
state->info.effective_uri = "/";
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
int get_params(optional_yield) override {
limit = -1; /* no limit */
return 0;
}
void send_response_begin(bool has_buckets) override {
sent_data = true;
}
void send_response_data(rgw::sal::BucketList& buckets) override {
if (!sent_data)
return;
auto& m = buckets.get_buckets();
for (const auto& iter : m) {
std::string_view marker{iter.first};
auto& ent = iter.second;
if (! this->operator()(ent->get_name(), marker)) {
/* caller cannot accept more */
lsubdout(cct, rgw, 5) << "ListBuckets rcb failed"
<< " dirent=" << ent->get_name()
<< " call count=" << ix
<< dendl;
rcb_eof = true;
return;
}
++ix;
}
} /* send_response_data */
void send_response_end() override {
// do nothing
}
int operator()(const std::string_view& name,
const std::string_view& marker) {
uint64_t off = XXH64(name.data(), name.length(), fh_key::seed);
if (!! ioff) {
*ioff = off;
}
/* update traversal cache */
rgw_fh->add_marker(off, rgw_obj_key{marker.data(), ""},
RGW_FS_TYPE_DIRECTORY);
++d_count;
return rcb(name.data(), cb_arg, off, nullptr, 0, RGW_LOOKUP_FLAG_DIR);
}
bool eof() {
using boost::get;
if (unlikely(cct->_conf->subsys.should_gather(ceph_subsys_rgw, 15))) {
bool is_offset =
unlikely(! get<const char*>(&offset)) ||
!! get<const char*>(offset);
lsubdout(cct, rgw, 15) << "READDIR offset: " <<
((is_offset) ? offset : "(nil)")
<< " is_truncated: " << is_truncated
<< dendl;
}
return !is_truncated && !rcb_eof;
}
}; /* RGWListBucketsRequest */
/*
read directory content (bucket objects)
*/
class RGWReaddirRequest : public RGWLibRequest,
public RGWListBucket /* RGWOp */
{
public:
RGWFileHandle* rgw_fh;
RGWFileHandle::readdir_offset offset;
void* cb_arg;
rgw_readdir_cb rcb;
uint64_t* ioff;
size_t ix;
uint32_t d_count;
bool rcb_eof; // caller forced early stop in readdir cycle
RGWReaddirRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
RGWFileHandle* _rgw_fh, rgw_readdir_cb _rcb,
void* _cb_arg, RGWFileHandle::readdir_offset& _offset)
: RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), offset(_offset),
cb_arg(_cb_arg), rcb(_rcb), ioff(nullptr), ix(0), d_count(0),
rcb_eof(false) {
using boost::get;
if (unlikely(!! get<uint64_t*>(&offset))) {
ioff = get<uint64_t*>(offset);
const auto& mk = rgw_fh->find_marker(*ioff);
if (mk) {
marker = *mk;
}
} else {
const char* mk = get<const char*>(offset);
if (mk) {
std::string tmark{rgw_fh->relative_object_name()};
if (tmark.length() > 0)
tmark += "/";
tmark += mk;
marker = rgw_obj_key{std::move(tmark), "", ""};
}
}
default_max = 1000; // XXX was being omitted
op = this;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
/* XXX derp derp derp */
std::string uri = "/" + rgw_fh->bucket_name() + "/";
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
prefix = rgw_fh->relative_object_name();
if (prefix.length() > 0)
prefix += "/";
delimiter = '/';
return 0;
}
int operator()(const std::string_view name, const rgw_obj_key& marker,
const ceph::real_time& t, const uint64_t fsz, uint8_t type) {
assert(name.length() > 0); // all cases handled in callers
/* hash offset of name in parent (short name) for NFS readdir cookie */
uint64_t off = XXH64(name.data(), name.length(), fh_key::seed);
if (unlikely(!! ioff)) {
*ioff = off;
}
/* update traversal cache */
rgw_fh->add_marker(off, marker, type);
++d_count;
/* set c/mtime and size from bucket index entry */
struct stat st = {};
#ifdef HAVE_STAT_ST_MTIMESPEC_TV_NSEC
st.st_atimespec = ceph::real_clock::to_timespec(t);
st.st_mtimespec = st.st_atimespec;
st.st_ctimespec = st.st_atimespec;
#else
st.st_atim = ceph::real_clock::to_timespec(t);
st.st_mtim = st.st_atim;
st.st_ctim = st.st_atim;
#endif
st.st_size = fsz;
return rcb(name.data(), cb_arg, off, &st, RGWFileHandle::RCB_MASK,
(type == RGW_FS_TYPE_DIRECTORY) ?
RGW_LOOKUP_FLAG_DIR :
RGW_LOOKUP_FLAG_FILE);
}
int get_params(optional_yield) override {
max = default_max;
return 0;
}
void send_response() override {
req_state* state = get_state();
auto cnow = real_clock::now();
/* enumerate objs and common_prefixes in parallel,
* avoiding increment on and end iterator, which is
* undefined */
class DirIterator
{
std::vector<rgw_bucket_dir_entry>& objs;
std::vector<rgw_bucket_dir_entry>::iterator obj_iter;
std::map<std::string, bool>& common_prefixes;
std::map<string, bool>::iterator cp_iter;
boost::optional<std::string_view> obj_sref;
boost::optional<std::string_view> cp_sref;
bool _skip_cp;
public:
DirIterator(std::vector<rgw_bucket_dir_entry>& objs,
std::map<string, bool>& common_prefixes)
: objs(objs), common_prefixes(common_prefixes), _skip_cp(false)
{
obj_iter = objs.begin();
parse_obj();
cp_iter = common_prefixes.begin();
parse_cp();
}
bool is_obj() {
return (obj_iter != objs.end());
}
bool is_cp(){
return (cp_iter != common_prefixes.end());
}
bool eof() {
return ((!is_obj()) && (!is_cp()));
}
void parse_obj() {
if (is_obj()) {
std::string_view sref{obj_iter->key.name};
size_t last_del = sref.find_last_of('/');
if (last_del != string::npos)
sref.remove_prefix(last_del+1);
obj_sref = sref;
}
} /* parse_obj */
void next_obj() {
++obj_iter;
parse_obj();
}
void parse_cp() {
if (is_cp()) {
/* leading-/ skip case */
if (cp_iter->first == "/") {
_skip_cp = true;
return;
} else
_skip_cp = false;
/* it's safest to modify the element in place--a suffix-modifying
* string_ref operation is problematic since ULP rgw_file callers
* will ultimately need a c-string */
if (cp_iter->first.back() == '/')
const_cast<std::string&>(cp_iter->first).pop_back();
std::string_view sref{cp_iter->first};
size_t last_del = sref.find_last_of('/');
if (last_del != string::npos)
sref.remove_prefix(last_del+1);
cp_sref = sref;
} /* is_cp */
} /* parse_cp */
void next_cp() {
++cp_iter;
parse_cp();
}
bool skip_cp() {
return _skip_cp;
}
bool entry_is_obj() {
return (is_obj() &&
((! is_cp()) ||
(obj_sref.get() < cp_sref.get())));
}
std::string_view get_obj_sref() {
return obj_sref.get();
}
std::string_view get_cp_sref() {
return cp_sref.get();
}
std::vector<rgw_bucket_dir_entry>::iterator& get_obj_iter() {
return obj_iter;
}
std::map<string, bool>::iterator& get_cp_iter() {
return cp_iter;
}
}; /* DirIterator */
DirIterator di{objs, common_prefixes};
for (;;) {
if (di.eof()) {
break; // done
}
/* assert: one of is_obj() || is_cp() holds */
if (di.entry_is_obj()) {
auto sref = di.get_obj_sref();
if (sref.empty()) {
/* recursive list of a leaf dir (iirc), do nothing */
} else {
/* send a file entry */
auto obj_entry = *(di.get_obj_iter());
lsubdout(cct, rgw, 15) << "RGWReaddirRequest "
<< __func__ << " "
<< "list uri=" << state->relative_uri << " "
<< " prefix=" << prefix << " "
<< " obj path=" << obj_entry.key.name
<< " (" << sref << ")" << ""
<< " mtime="
<< real_clock::to_time_t(obj_entry.meta.mtime)
<< " size=" << obj_entry.meta.accounted_size
<< dendl;
if (! this->operator()(sref, next_marker, obj_entry.meta.mtime,
obj_entry.meta.accounted_size,
RGW_FS_TYPE_FILE)) {
/* caller cannot accept more */
lsubdout(cct, rgw, 5) << "readdir rcb caller signalled stop"
<< " dirent=" << sref.data()
<< " call count=" << ix
<< dendl;
rcb_eof = true;
return;
}
}
di.next_obj(); // and advance object
} else {
/* send a dir entry */
if (! di.skip_cp()) {
auto sref = di.get_cp_sref();
lsubdout(cct, rgw, 15) << "RGWReaddirRequest "
<< __func__ << " "
<< "list uri=" << state->relative_uri << " "
<< " prefix=" << prefix << " "
<< " cpref=" << sref
<< dendl;
if (sref.empty()) {
/* null path segment--could be created in S3 but has no NFS
* interpretation */
} else {
if (! this->operator()(sref, next_marker, cnow, 0,
RGW_FS_TYPE_DIRECTORY)) {
/* caller cannot accept more */
lsubdout(cct, rgw, 5) << "readdir rcb caller signalled stop"
<< " dirent=" << sref.data()
<< " call count=" << ix
<< dendl;
rcb_eof = true;
return;
}
}
}
di.next_cp(); // and advance common_prefixes
} /* ! di.entry_is_obj() */
} /* for (;;) */
}
virtual void send_versioned_response() {
send_response();
}
bool eof() {
using boost::get;
if (unlikely(cct->_conf->subsys.should_gather(ceph_subsys_rgw, 15))) {
bool is_offset =
unlikely(! get<const char*>(&offset)) ||
!! get<const char*>(offset);
lsubdout(cct, rgw, 15) << "READDIR offset: " <<
((is_offset) ? offset : "(nil)")
<< " next marker: " << next_marker
<< " is_truncated: " << is_truncated
<< dendl;
}
return !is_truncated && !rcb_eof;
}
}; /* RGWReaddirRequest */
/*
dir has-children predicate (bucket objects)
*/
class RGWRMdirCheck : public RGWLibRequest,
public RGWListBucket /* RGWOp */
{
public:
const RGWFileHandle* rgw_fh;
bool valid;
bool has_children;
RGWRMdirCheck (CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
const RGWFileHandle* _rgw_fh)
: RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), valid(false),
has_children(false) {
default_max = 2;
op = this;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
std::string uri = "/" + rgw_fh->bucket_name() + "/";
state->relative_uri = uri;
state->info.request_uri = uri;
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
prefix = rgw_fh->relative_object_name();
if (prefix.length() > 0)
prefix += "/";
delimiter = '/';
return 0;
}
int get_params(optional_yield) override {
max = default_max;
return 0;
}
void send_response() override {
valid = true;
if ((objs.size() > 1) ||
(! objs.empty() &&
(objs.front().key.name != prefix))) {
has_children = true;
return;
}
for (auto& iter : common_prefixes) {
/* readdir never produces a name for this case */
if (iter.first == "/")
continue;
has_children = true;
break;
}
}
virtual void send_versioned_response() {
send_response();
}
}; /* RGWRMdirCheck */
/*
create bucket
*/
class RGWCreateBucketRequest : public RGWLibRequest,
public RGWCreateBucket /* RGWOp */
{
public:
const std::string& bucket_name;
RGWCreateBucketRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
std::string& _bname)
: RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname) {
op = this;
}
bool only_bucket() override { return false; }
int read_permissions(RGWOp* op_obj, optional_yield) override {
/* we ARE a 'create bucket' request (cf. rgw_rest.cc, ll. 1305-6) */
return 0;
}
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "PUT";
state->op = OP_PUT;
string uri = "/" + bucket_name;
/* XXX derp derp derp */
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
int get_params(optional_yield) override {
req_state* state = get_state();
RGWAccessControlPolicy_S3 s3policy(state->cct);
/* we don't have (any) headers, so just create canned ACLs */
int ret = s3policy.create_canned(state->owner, state->bucket_owner, state->canned_acl);
policy = s3policy;
return ret;
}
void send_response() override {
/* TODO: something (maybe) */
}
}; /* RGWCreateBucketRequest */
/*
delete bucket
*/
class RGWDeleteBucketRequest : public RGWLibRequest,
public RGWDeleteBucket /* RGWOp */
{
public:
const std::string& bucket_name;
RGWDeleteBucketRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
std::string& _bname)
: RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname) {
op = this;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "DELETE";
state->op = OP_DELETE;
string uri = "/" + bucket_name;
/* XXX derp derp derp */
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
void send_response() override {}
}; /* RGWDeleteBucketRequest */
/*
put object
*/
class RGWPutObjRequest : public RGWLibRequest,
public RGWPutObj /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
buffer::list& bl; /* XXX */
size_t bytes_written;
RGWPutObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
const std::string& _bname, const std::string& _oname,
buffer::list& _bl)
: RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname),
bl(_bl), bytes_written(0) {
op = this;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
int rc = valid_s3_object_name(obj_name);
if (rc != 0)
return rc;
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "PUT";
state->op = OP_PUT;
/* XXX derp derp derp */
std::string uri = make_uri(bucket_name, obj_name);
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
/* XXX required in RGWOp::execute() */
state->content_length = bl.length();
return 0;
}
int get_params(optional_yield) override {
req_state* state = get_state();
RGWAccessControlPolicy_S3 s3policy(state->cct);
/* we don't have (any) headers, so just create canned ACLs */
int ret = s3policy.create_canned(state->owner, state->bucket_owner, state->canned_acl);
policy = s3policy;
return ret;
}
int get_data(buffer::list& _bl) override {
/* XXX for now, use sharing semantics */
_bl = std::move(bl);
uint32_t len = _bl.length();
bytes_written += len;
return len;
}
void send_response() override {}
int verify_params() override {
if (bl.length() > cct->_conf->rgw_max_put_size)
return -ERR_TOO_LARGE;
return 0;
}
buffer::list* get_attr(const std::string& k) {
auto iter = attrs.find(k);
return (iter != attrs.end()) ? &(iter->second) : nullptr;
}
}; /* RGWPutObjRequest */
/*
get object
*/
class RGWReadRequest : public RGWLibRequest,
public RGWGetObj /* RGWOp */
{
public:
RGWFileHandle* rgw_fh;
void *ulp_buffer;
size_t nread;
size_t read_resid; /* initialize to len, <= sizeof(ulp_buffer) */
bool do_hexdump = false;
RGWReadRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
RGWFileHandle* _rgw_fh, uint64_t off, uint64_t len,
void *_ulp_buffer)
: RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), ulp_buffer(_ulp_buffer),
nread(0), read_resid(len) {
op = this;
/* fixup RGWGetObj (already know range parameters) */
RGWGetObj::range_parsed = true;
RGWGetObj::get_data = true; // XXX
RGWGetObj::partial_content = true;
RGWGetObj::ofs = off;
RGWGetObj::end = off + len;
}
bool only_bucket() override { return false; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
/* XXX derp derp derp */
state->relative_uri = make_uri(rgw_fh->bucket_name(),
rgw_fh->relative_object_name());
state->info.request_uri = state->relative_uri; // XXX
state->info.effective_uri = state->relative_uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
int get_params(optional_yield) override {
return 0;
}
int send_response_data(ceph::buffer::list& bl, off_t bl_off,
off_t bl_len) override {
size_t bytes;
for (auto& bp : bl.buffers()) {
/* if for some reason bl_off indicates the start-of-data is not at
* the current buffer::ptr, skip it and account */
if (bl_off > bp.length()) {
bl_off -= bp.length();
continue;
}
/* read no more than read_resid */
bytes = std::min(read_resid, size_t(bp.length()-bl_off));
memcpy(static_cast<char*>(ulp_buffer)+nread, bp.c_str()+bl_off, bytes);
read_resid -= bytes; /* reduce read_resid by bytes read */
nread += bytes;
bl_off = 0;
/* stop if we have no residual ulp_buffer */
if (! read_resid)
break;
}
return 0;
}
int send_response_data_error(optional_yield) override {
/* S3 implementation just sends nothing--there is no side effect
* to simulate here */
return 0;
}
bool prefetch_data() override { return false; }
}; /* RGWReadRequest */
/*
delete object
*/
class RGWDeleteObjRequest : public RGWLibRequest,
public RGWDeleteObj /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
RGWDeleteObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
const std::string& _bname, const std::string& _oname)
: RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname) {
op = this;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "DELETE";
state->op = OP_DELETE;
/* XXX derp derp derp */
std::string uri = make_uri(bucket_name, obj_name);
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
void send_response() override {}
}; /* RGWDeleteObjRequest */
class RGWStatObjRequest : public RGWLibRequest,
public RGWGetObj /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
uint64_t _size;
uint32_t flags;
static constexpr uint32_t FLAG_NONE = 0x000;
RGWStatObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
const std::string& _bname, const std::string& _oname,
uint32_t _flags)
: RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname),
_size(0), flags(_flags) {
op = this;
/* fixup RGWGetObj (already know range parameters) */
RGWGetObj::range_parsed = true;
RGWGetObj::get_data = false; // XXX
RGWGetObj::partial_content = true;
RGWGetObj::ofs = 0;
RGWGetObj::end = UINT64_MAX;
}
const char* name() const override { return "stat_obj"; }
RGWOpType get_type() override { return RGW_OP_STAT_OBJ; }
real_time get_mtime() const {
return lastmod;
}
/* attributes */
uint64_t get_size() { return _size; }
real_time ctime() { return mod_time; } // XXX
real_time mtime() { return mod_time; }
std::map<string, bufferlist>& get_attrs() { return attrs; }
buffer::list* get_attr(const std::string& k) {
auto iter = attrs.find(k);
return (iter != attrs.end()) ? &(iter->second) : nullptr;
}
bool only_bucket() override { return false; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
/* XXX derp derp derp */
state->relative_uri = make_uri(bucket_name, obj_name);
state->info.request_uri = state->relative_uri; // XXX
state->info.effective_uri = state->relative_uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
int get_params(optional_yield) override {
return 0;
}
int send_response_data(ceph::buffer::list& _bl, off_t s_off,
off_t e_off) override {
/* NOP */
/* XXX save attrs? */
return 0;
}
int send_response_data_error(optional_yield) override {
/* NOP */
return 0;
}
void execute(optional_yield y) override {
RGWGetObj::execute(y);
_size = get_state()->obj_size;
}
}; /* RGWStatObjRequest */
class RGWStatBucketRequest : public RGWLibRequest,
public RGWStatBucket /* RGWOp */
{
public:
std::string uri;
std::map<std::string, buffer::list> attrs;
RGWLibFS::BucketStats& bs;
RGWStatBucketRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
const std::string& _path,
RGWLibFS::BucketStats& _stats)
: RGWLibRequest(_cct, std::move(_user)), bs(_stats) {
uri = "/" + _path;
op = this;
}
buffer::list* get_attr(const std::string& k) {
auto iter = attrs.find(k);
return (iter != attrs.end()) ? &(iter->second) : nullptr;
}
real_time get_ctime() const {
return bucket->get_creation_time();
}
bool only_bucket() override { return false; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
/* XXX derp derp derp */
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
virtual int get_params() {
return 0;
}
void send_response() override {
bucket->get_creation_time() = get_state()->bucket->get_info().creation_time;
bs.size = bucket->get_size();
bs.size_rounded = bucket->get_size_rounded();
bs.creation_time = bucket->get_creation_time();
bs.num_entries = bucket->get_count();
std::swap(attrs, get_state()->bucket_attrs);
}
bool matched() {
return (bucket->get_name().length() > 0);
}
}; /* RGWStatBucketRequest */
class RGWStatLeafRequest : public RGWLibRequest,
public RGWListBucket /* RGWOp */
{
public:
RGWFileHandle* rgw_fh;
std::string path;
bool matched;
bool is_dir;
bool exact_matched;
RGWStatLeafRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
RGWFileHandle* _rgw_fh, const std::string& _path)
: RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), path(_path),
matched(false), is_dir(false), exact_matched(false) {
default_max = 1000; // logical max {"foo", "foo/"}
op = this;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
/* XXX derp derp derp */
std::string uri = "/" + rgw_fh->bucket_name() + "/";
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
prefix = rgw_fh->relative_object_name();
if (prefix.length() > 0)
prefix += "/";
prefix += path;
delimiter = '/';
return 0;
}
int get_params(optional_yield) override {
max = default_max;
return 0;
}
void send_response() override {
req_state* state = get_state();
// try objects
for (const auto& iter : objs) {
auto& name = iter.key.name;
lsubdout(cct, rgw, 15) << "RGWStatLeafRequest "
<< __func__ << " "
<< "list uri=" << state->relative_uri << " "
<< " prefix=" << prefix << " "
<< " obj path=" << name << ""
<< " target = " << path << ""
<< dendl;
/* XXX is there a missing match-dir case (trailing '/')? */
matched = true;
if (name == path) {
exact_matched = true;
return;
}
}
// try prefixes
for (auto& iter : common_prefixes) {
auto& name = iter.first;
lsubdout(cct, rgw, 15) << "RGWStatLeafRequest "
<< __func__ << " "
<< "list uri=" << state->relative_uri << " "
<< " prefix=" << prefix << " "
<< " pref path=" << name << " (not chomped)"
<< " target = " << path << ""
<< dendl;
matched = true;
/* match-dir case (trailing '/') */
if (name == prefix + "/") {
exact_matched = true;
is_dir = true;
return;
}
}
}
virtual void send_versioned_response() {
send_response();
}
}; /* RGWStatLeafRequest */
/*
put object
*/
class RGWWriteRequest : public RGWLibContinuedReq,
public RGWPutObj /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
RGWFileHandle* rgw_fh;
std::optional<rgw::BlockingAioThrottle> aio;
std::unique_ptr<rgw::sal::Writer> processor;
rgw::sal::DataProcessor* filter;
boost::optional<RGWPutObj_Compress> compressor;
CompressorRef plugin;
buffer::list data;
uint64_t timer_id;
MD5 hash;
off_t real_ofs;
size_t bytes_written;
bool eio;
RGWWriteRequest(rgw::sal::Driver* driver, const RGWProcessEnv& penv,
std::unique_ptr<rgw::sal::User> _user,
RGWFileHandle* _fh, const std::string& _bname,
const std::string& _oname)
: RGWLibContinuedReq(driver->ctx(), penv, std::move(_user)),
bucket_name(_bname), obj_name(_oname),
rgw_fh(_fh), filter(nullptr), timer_id(0), real_ofs(0),
bytes_written(0), eio(false) {
// in ctr this is not a virtual call
// invoking this classes's header_init()
(void) RGWWriteRequest::header_init();
op = this;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "PUT";
state->op = OP_PUT;
/* XXX derp derp derp */
std::string uri = make_uri(bucket_name, obj_name);
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
int get_params(optional_yield) override {
req_state* state = get_state();
RGWAccessControlPolicy_S3 s3policy(state->cct);
/* we don't have (any) headers, so just create canned ACLs */
int ret = s3policy.create_canned(state->owner, state->bucket_owner, state->canned_acl);
policy = s3policy;
return ret;
}
int get_data(buffer::list& _bl) override {
/* XXX for now, use sharing semantics */
uint32_t len = data.length();
_bl = std::move(data);
bytes_written += len;
return len;
}
void put_data(off_t off, buffer::list& _bl) {
if (off != real_ofs) {
eio = true;
}
data = std::move(_bl);
real_ofs += data.length();
ofs = off; /* consumed in exec_continue() */
}
int exec_start() override;
int exec_continue() override;
int exec_finish() override;
void send_response() override {}
int verify_params() override {
return 0;
}
}; /* RGWWriteRequest */
/*
copy object
*/
class RGWCopyObjRequest : public RGWLibRequest,
public RGWCopyObj /* RGWOp */
{
public:
RGWFileHandle* src_parent;
RGWFileHandle* dst_parent;
const std::string& src_name;
const std::string& dst_name;
RGWCopyObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
RGWFileHandle* _src_parent, RGWFileHandle* _dst_parent,
const std::string& _src_name, const std::string& _dst_name)
: RGWLibRequest(_cct, std::move(_user)), src_parent(_src_parent),
dst_parent(_dst_parent), src_name(_src_name), dst_name(_dst_name) {
/* all requests have this */
op = this;
/* allow this request to replace selected attrs */
attrs_mod = rgw::sal::ATTRSMOD_MERGE;
}
bool only_bucket() override { return true; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "PUT"; // XXX check
state->op = OP_PUT;
state->src_bucket_name = src_parent->bucket_name();
state->bucket_name = dst_parent->bucket_name();
std::string dest_obj_name = dst_parent->format_child_name(dst_name, false);
int rc = valid_s3_object_name(dest_obj_name);
if (rc != 0)
return rc;
state->object = RGWHandler::driver->get_object(rgw_obj_key(dest_obj_name));
/* XXX and fixup key attr (could optimize w/string ref and
* dest_obj_name) */
buffer::list ux_key;
fh_key fhk = dst_parent->make_fhk(dst_name);
rgw::encode(fhk, ux_key);
emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key));
#if 0 /* XXX needed? */
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
#endif
return 0;
}
int get_params(optional_yield) override {
req_state* s = get_state();
RGWAccessControlPolicy_S3 s3policy(s->cct);
/* we don't have (any) headers, so just create canned ACLs */
int ret = s3policy.create_canned(s->owner, s->bucket_owner, s->canned_acl);
dest_policy = s3policy;
/* src_object required before RGWCopyObj::verify_permissions() */
rgw_obj_key k = rgw_obj_key(src_name);
s->src_object = s->bucket->get_object(k);
s->object = s->src_object->clone(); // needed to avoid trap at rgw_op.cc:5150
return ret;
}
void send_response() override {}
void send_partial_response(off_t ofs) override {}
}; /* RGWCopyObjRequest */
class RGWGetAttrsRequest : public RGWLibRequest,
public RGWGetAttrs /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
RGWGetAttrsRequest(CephContext* _cct,
std::unique_ptr<rgw::sal::User> _user,
const std::string& _bname, const std::string& _oname)
: RGWLibRequest(_cct, std::move(_user)), RGWGetAttrs(),
bucket_name(_bname), obj_name(_oname) {
op = this;
}
const flat_map<std::string, std::optional<buffer::list>>& get_attrs() {
return attrs;
}
virtual bool only_bucket() { return false; }
virtual int op_init() {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
virtual int header_init() {
req_state* s = get_state();
s->info.method = "GET";
s->op = OP_GET;
std::string uri = make_uri(bucket_name, obj_name);
s->relative_uri = uri;
s->info.request_uri = uri;
s->info.effective_uri = uri;
s->info.request_params = "";
s->info.domain = ""; /* XXX ? */
return 0;
}
virtual int get_params() {
return 0;
}
virtual void send_response() {}
}; /* RGWGetAttrsRequest */
class RGWSetAttrsRequest : public RGWLibRequest,
public RGWSetAttrs /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
RGWSetAttrsRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
const std::string& _bname, const std::string& _oname)
: RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname) {
op = this;
}
const std::map<std::string, buffer::list>& get_attrs() {
return attrs;
}
bool only_bucket() override { return false; }
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "PUT";
state->op = OP_PUT;
/* XXX derp derp derp */
std::string uri = make_uri(bucket_name, obj_name);
state->relative_uri = uri;
state->info.request_uri = uri; // XXX
state->info.effective_uri = uri;
state->info.request_params = "";
state->info.domain = ""; /* XXX ? */
return 0;
}
int get_params(optional_yield) override {
return 0;
}
void send_response() override {}
}; /* RGWSetAttrsRequest */
class RGWRMAttrsRequest : public RGWLibRequest,
public RGWRMAttrs /* RGWOp */
{
public:
const std::string& bucket_name;
const std::string& obj_name;
RGWRMAttrsRequest(CephContext* _cct,
std::unique_ptr<rgw::sal::User> _user,
const std::string& _bname, const std::string& _oname)
: RGWLibRequest(_cct, std::move(_user)), RGWRMAttrs(),
bucket_name(_bname), obj_name(_oname) {
op = this;
}
const rgw::sal::Attrs& get_attrs() {
return attrs;
}
virtual bool only_bucket() { return false; }
virtual int op_init() {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
virtual int header_init() {
req_state* s = get_state();
s->info.method = "DELETE";
s->op = OP_PUT;
std::string uri = make_uri(bucket_name, obj_name);
s->relative_uri = uri;
s->info.request_uri = uri;
s->info.effective_uri = uri;
s->info.request_params = "";
s->info.domain = ""; /* XXX ? */
return 0;
}
virtual int get_params() {
return 0;
}
virtual void send_response() {}
}; /* RGWRMAttrsRequest */
/*
* Send request to get the rados cluster stats
*/
class RGWGetClusterStatReq : public RGWLibRequest,
public RGWGetClusterStat {
public:
struct rados_cluster_stat_t& stats_req;
RGWGetClusterStatReq(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user,
rados_cluster_stat_t& _stats):
RGWLibRequest(_cct, std::move(_user)), stats_req(_stats){
op = this;
}
int op_init() override {
// assign driver, s, and dialect_handler
// framework promises to call op_init after parent init
RGWOp::init(RGWHandler::driver, get_state(), this);
op = this; // assign self as op: REQUIRED
return 0;
}
int header_init() override {
req_state* state = get_state();
state->info.method = "GET";
state->op = OP_GET;
return 0;
}
int get_params(optional_yield) override { return 0; }
bool only_bucket() override { return false; }
void send_response() override {
stats_req.kb = stats_op.kb;
stats_req.kb_avail = stats_op.kb_avail;
stats_req.kb_used = stats_op.kb_used;
stats_req.num_objects = stats_op.num_objects;
}
}; /* RGWGetClusterStatReq */
} /* namespace rgw */
| 77,679 | 26.179846 | 92 |
h
|
null |
ceph-main/src/rgw/rgw_flight.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright 2023 IBM
*
* See file COPYING for licensing information.
*/
#include <iostream>
#include <fstream>
#include <mutex>
#include <map>
#include <algorithm>
#include "arrow/type.h"
#include "arrow/buffer.h"
#include "arrow/util/string_view.h"
#include "arrow/io/interfaces.h"
#include "arrow/ipc/reader.h"
#include "arrow/table.h"
#include "arrow/flight/server.h"
#include "parquet/arrow/reader.h"
#include "common/dout.h"
#include "rgw_op.h"
#include "rgw_flight.h"
#include "rgw_flight_frontend.h"
namespace rgw::flight {
// Ticket and FlightKey
std::atomic<FlightKey> next_flight_key = null_flight_key;
flt::Ticket FlightKeyToTicket(const FlightKey& key) {
flt::Ticket result;
result.ticket = std::to_string(key);
return result;
}
arw::Result<FlightKey> TicketToFlightKey(const flt::Ticket& t) {
try {
return (FlightKey) std::stoul(t.ticket);
} catch (std::invalid_argument const& ex) {
return arw::Status::Invalid(
"could not convert Ticket containing \"%s\" into a Flight Key",
t.ticket);
} catch (const std::out_of_range& ex) {
return arw::Status::Invalid(
"could not convert Ticket containing \"%s\" into a Flight Key due to range",
t.ticket);
}
}
// FlightData
FlightData::FlightData(const std::string& _uri,
const std::string& _tenant_name,
const std::string& _bucket_name,
const rgw_obj_key& _object_key,
uint64_t _num_records,
uint64_t _obj_size,
std::shared_ptr<arw::Schema>& _schema,
std::shared_ptr<const arw::KeyValueMetadata>& _kv_metadata,
rgw_user _user_id) :
key(++next_flight_key),
/* expires(coarse_real_clock::now() + lifespan), */
uri(_uri),
tenant_name(_tenant_name),
bucket_name(_bucket_name),
object_key(_object_key),
num_records(_num_records),
obj_size(_obj_size),
schema(_schema),
kv_metadata(_kv_metadata),
user_id(_user_id)
{ }
/**** FlightStore ****/
FlightStore::FlightStore(const DoutPrefix& _dp) :
dp(_dp)
{ }
FlightStore::~FlightStore() { }
/**** MemoryFlightStore ****/
MemoryFlightStore::MemoryFlightStore(const DoutPrefix& _dp) :
FlightStore(_dp)
{ }
MemoryFlightStore::~MemoryFlightStore() { }
FlightKey MemoryFlightStore::add_flight(FlightData&& flight) {
std::pair<decltype(map)::iterator,bool> result;
{
const std::lock_guard lock(mtx);
result = map.insert( {flight.key, std::move(flight)} );
}
ceph_assertf(result.second,
"unable to add FlightData to MemoryFlightStore"); // temporary until error handling
return result.first->second.key;
}
arw::Result<FlightData> MemoryFlightStore::get_flight(const FlightKey& key) const {
const std::lock_guard lock(mtx);
auto i = map.find(key);
if (i == map.cend()) {
return arw::Status::KeyError("could not find Flight with Key %" PRIu32,
key);
} else {
return i->second;
}
}
// returns either the next FilghtData or, if at end, empty optional
std::optional<FlightData> MemoryFlightStore::after_key(const FlightKey& key) const {
std::optional<FlightData> result;
{
const std::lock_guard lock(mtx);
auto i = map.upper_bound(key);
if (i != map.end()) {
result = i->second;
}
}
return result;
}
int MemoryFlightStore::remove_flight(const FlightKey& key) {
return 0;
}
int MemoryFlightStore::expire_flights() {
return 0;
}
/**** FlightServer ****/
FlightServer::FlightServer(RGWProcessEnv& _env,
FlightStore* _flight_store,
const DoutPrefix& _dp) :
env(_env),
driver(env.driver),
dp(_dp),
flight_store(_flight_store)
{ }
FlightServer::~FlightServer()
{ }
arw::Status FlightServer::ListFlights(const flt::ServerCallContext& context,
const flt::Criteria* criteria,
std::unique_ptr<flt::FlightListing>* listings) {
// function local class to implement FlightListing interface
class RGWFlightListing : public flt::FlightListing {
FlightStore* flight_store;
FlightKey previous_key;
public:
RGWFlightListing(FlightStore* flight_store) :
flight_store(flight_store),
previous_key(null_flight_key)
{ }
arw::Status Next(std::unique_ptr<flt::FlightInfo>* info) {
std::optional<FlightData> fd = flight_store->after_key(previous_key);
if (fd) {
previous_key = fd->key;
auto descriptor =
flt::FlightDescriptor::Path(
{ fd->tenant_name, fd->bucket_name, fd->object_key.name, fd->object_key.instance, fd->object_key.ns });
flt::FlightEndpoint endpoint;
endpoint.ticket = FlightKeyToTicket(fd->key);
std::vector<flt::FlightEndpoint> endpoints { endpoint };
ARROW_ASSIGN_OR_RAISE(flt::FlightInfo info_obj,
flt::FlightInfo::Make(*fd->schema, descriptor, endpoints, fd->num_records, fd->obj_size));
*info = std::make_unique<flt::FlightInfo>(std::move(info_obj));
return arw::Status::OK();
} else {
*info = nullptr;
return arw::Status::OK();
}
}
}; // class RGWFlightListing
*listings = std::make_unique<RGWFlightListing>(flight_store);
return arw::Status::OK();
} // FlightServer::ListFlights
arw::Status FlightServer::GetFlightInfo(const flt::ServerCallContext &context,
const flt::FlightDescriptor &request,
std::unique_ptr<flt::FlightInfo> *info) {
return arw::Status::OK();
} // FlightServer::GetFlightInfo
arw::Status FlightServer::GetSchema(const flt::ServerCallContext &context,
const flt::FlightDescriptor &request,
std::unique_ptr<flt::SchemaResult> *schema) {
return arw::Status::OK();
} // FlightServer::GetSchema
// A Buffer that owns its memory and frees it when the Buffer is
// destructed
class OwnedBuffer : public arw::Buffer {
uint8_t* buffer;
protected:
OwnedBuffer(uint8_t* _buffer, int64_t _size) :
Buffer(_buffer, _size),
buffer(_buffer)
{ }
public:
~OwnedBuffer() override {
delete[] buffer;
}
static arw::Result<std::shared_ptr<OwnedBuffer>> make(int64_t size) {
uint8_t* buffer = new (std::nothrow) uint8_t[size];
if (!buffer) {
return arw::Status::OutOfMemory("could not allocated buffer of size %" PRId64, size);
}
OwnedBuffer* ptr = new OwnedBuffer(buffer, size);
std::shared_ptr<OwnedBuffer> result;
result.reset(ptr);
return result;
}
// if what's read in is less than capacity
void set_size(int64_t size) {
size_ = size;
}
// pointer that can be used to write into buffer
uint8_t* writeable_data() {
return buffer;
}
}; // class OwnedBuffer
#if 0 // remove classes used for testing and incrementally building
// make local to DoGet eventually
class LocalInputStream : public arw::io::InputStream {
std::iostream::pos_type position;
std::fstream file;
std::shared_ptr<const arw::KeyValueMetadata> kv_metadata;
const DoutPrefix dp;
public:
LocalInputStream(std::shared_ptr<const arw::KeyValueMetadata> _kv_metadata,
const DoutPrefix _dp) :
kv_metadata(_kv_metadata),
dp(_dp)
{}
arw::Status Open() {
file.open("/tmp/green_tripdata_2022-04.parquet", std::ios::in);
if (!file.good()) {
return arw::Status::IOError("unable to open file");
}
INFO << "file opened successfully" << dendl;
position = file.tellg();
return arw::Status::OK();
}
arw::Status Close() override {
file.close();
INFO << "file closed" << dendl;
return arw::Status::OK();
}
arw::Result<int64_t> Tell() const override {
if (position < 0) {
return arw::Status::IOError(
"could not query file implementaiton with tellg");
} else {
return int64_t(position);
}
}
bool closed() const override {
return file.is_open();
}
arw::Result<int64_t> Read(int64_t nbytes, void* out) override {
INFO << "entered: asking for " << nbytes << " bytes" << dendl;
if (file.read(reinterpret_cast<char*>(out),
reinterpret_cast<std::streamsize>(nbytes))) {
const std::streamsize bytes_read = file.gcount();
INFO << "Point A: read bytes " << bytes_read << dendl;
position = file.tellg();
return bytes_read;
} else {
ERROR << "unable to read from file" << dendl;
return arw::Status::IOError("unable to read from offset %" PRId64,
int64_t(position));
}
}
arw::Result<std::shared_ptr<arw::Buffer>> Read(int64_t nbytes) override {
INFO << "entered: " << ": asking for " << nbytes << " bytes" << dendl;
std::shared_ptr<OwnedBuffer> buffer;
ARROW_ASSIGN_OR_RAISE(buffer, OwnedBuffer::make(nbytes));
if (file.read(reinterpret_cast<char*>(buffer->writeable_data()),
reinterpret_cast<std::streamsize>(nbytes))) {
const auto bytes_read = file.gcount();
INFO << "Point B: read bytes " << bytes_read << dendl;
// buffer->set_size(bytes_read);
position = file.tellg();
return buffer;
} else if (file.rdstate() & std::ifstream::failbit &&
file.rdstate() & std::ifstream::eofbit) {
const auto bytes_read = file.gcount();
INFO << "3 read bytes " << bytes_read << " and reached EOF" << dendl;
// buffer->set_size(bytes_read);
position = file.tellg();
return buffer;
} else {
ERROR << "unable to read from file" << dendl;
return arw::Status::IOError("unable to read from offset %ld", position);
}
}
arw::Result<arw::util::string_view> Peek(int64_t nbytes) override {
INFO << "called, not implemented" << dendl;
return arw::Status::NotImplemented("peek not currently allowed");
}
bool supports_zero_copy() const override {
return false;
}
arw::Result<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadata() override {
INFO << "called" << dendl;
return kv_metadata;
}
}; // class LocalInputStream
class LocalRandomAccessFile : public arw::io::RandomAccessFile {
FlightData flight_data;
const DoutPrefix dp;
std::iostream::pos_type position;
std::fstream file;
public:
LocalRandomAccessFile(const FlightData& _flight_data, const DoutPrefix _dp) :
flight_data(_flight_data),
dp(_dp)
{ }
// implement InputStream
arw::Status Open() {
file.open("/tmp/green_tripdata_2022-04.parquet", std::ios::in);
if (!file.good()) {
return arw::Status::IOError("unable to open file");
}
INFO << "file opened successfully" << dendl;
position = file.tellg();
return arw::Status::OK();
}
arw::Status Close() override {
file.close();
INFO << "file closed" << dendl;
return arw::Status::OK();
}
arw::Result<int64_t> Tell() const override {
if (position < 0) {
return arw::Status::IOError(
"could not query file implementaiton with tellg");
} else {
return int64_t(position);
}
}
bool closed() const override {
return file.is_open();
}
arw::Result<int64_t> Read(int64_t nbytes, void* out) override {
INFO << "entered: asking for " << nbytes << " bytes" << dendl;
if (file.read(reinterpret_cast<char*>(out),
reinterpret_cast<std::streamsize>(nbytes))) {
const std::streamsize bytes_read = file.gcount();
INFO << "Point A: read bytes " << bytes_read << dendl;
position = file.tellg();
return bytes_read;
} else {
ERROR << "unable to read from file" << dendl;
return arw::Status::IOError("unable to read from offset %" PRId64,
int64_t(position));
}
}
arw::Result<std::shared_ptr<arw::Buffer>> Read(int64_t nbytes) override {
INFO << "entered: asking for " << nbytes << " bytes" << dendl;
std::shared_ptr<OwnedBuffer> buffer;
ARROW_ASSIGN_OR_RAISE(buffer, OwnedBuffer::make(nbytes));
if (file.read(reinterpret_cast<char*>(buffer->writeable_data()),
reinterpret_cast<std::streamsize>(nbytes))) {
const auto bytes_read = file.gcount();
INFO << "Point B: read bytes " << bytes_read << dendl;
// buffer->set_size(bytes_read);
position = file.tellg();
return buffer;
} else if (file.rdstate() & std::ifstream::failbit &&
file.rdstate() & std::ifstream::eofbit) {
const auto bytes_read = file.gcount();
INFO << "3 read bytes " << bytes_read << " and reached EOF" << dendl;
// buffer->set_size(bytes_read);
position = file.tellg();
return buffer;
} else {
ERROR << "unable to read from file" << dendl;
return arw::Status::IOError("unable to read from offset %ld", position);
}
}
bool supports_zero_copy() const override {
return false;
}
// implement Seekable
arw::Result<int64_t> GetSize() override {
return flight_data.obj_size;
}
arw::Result<arw::util::string_view> Peek(int64_t nbytes) override {
std::iostream::pos_type here = file.tellg();
if (here == -1) {
return arw::Status::IOError(
"unable to determine current position ahead of peek");
}
ARROW_ASSIGN_OR_RAISE(OwningStringView result,
OwningStringView::make(nbytes));
// read
ARROW_ASSIGN_OR_RAISE(int64_t bytes_read,
Read(nbytes, (void*) result.writeable_data()));
(void) bytes_read; // silence unused variable warnings
// return offset to original
ARROW_RETURN_NOT_OK(Seek(here));
return result;
}
arw::Result<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadata() {
return flight_data.kv_metadata;
}
arw::Future<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadataAsync(
const arw::io::IOContext& io_context) override {
return arw::Future<std::shared_ptr<const arw::KeyValueMetadata>>::MakeFinished(ReadMetadata());
}
// implement Seekable interface
arw::Status Seek(int64_t position) {
file.seekg(position);
if (file.fail()) {
return arw::Status::IOError(
"error encountered during seek to %" PRId64, position);
} else {
return arw::Status::OK();
}
}
}; // class LocalRandomAccessFile
#endif
class RandomAccessObject : public arw::io::RandomAccessFile {
FlightData flight_data;
const DoutPrefix dp;
int64_t position;
bool is_closed;
std::unique_ptr<rgw::sal::Object::ReadOp> op;
public:
RandomAccessObject(const FlightData& _flight_data,
std::unique_ptr<rgw::sal::Object>& obj,
const DoutPrefix _dp) :
flight_data(_flight_data),
dp(_dp),
position(-1),
is_closed(false)
{
op = obj->get_read_op();
}
arw::Status Open() {
int ret = op->prepare(null_yield, &dp);
if (ret < 0) {
return arw::Status::IOError(
"unable to prepare object with error %d", ret);
}
INFO << "file opened successfully" << dendl;
position = 0;
return arw::Status::OK();
}
// implement InputStream
arw::Status Close() override {
position = -1;
is_closed = true;
(void) op.reset();
INFO << "object closed" << dendl;
return arw::Status::OK();
}
arw::Result<int64_t> Tell() const override {
if (position < 0) {
return arw::Status::IOError("could not determine position");
} else {
return position;
}
}
bool closed() const override {
return is_closed;
}
arw::Result<int64_t> Read(int64_t nbytes, void* out) override {
INFO << "entered: asking for " << nbytes << " bytes" << dendl;
if (position < 0) {
ERROR << "error, position indicated error" << dendl;
return arw::Status::IOError("object read op is in bad state");
}
// note: read function reads through end_position inclusive
int64_t end_position = position + nbytes - 1;
bufferlist bl;
const int64_t bytes_read =
op->read(position, end_position, bl, null_yield, &dp);
if (bytes_read < 0) {
const int64_t former_position = position;
position = -1;
ERROR << "read operation returned " << bytes_read << dendl;
return arw::Status::IOError(
"unable to read object at position %" PRId64 ", error code: %" PRId64,
former_position,
bytes_read);
}
// TODO: see if there's a way to get rid of this copy, perhaps
// updating rgw::sal::read_op
bl.cbegin().copy(bytes_read, reinterpret_cast<char*>(out));
position += bytes_read;
if (nbytes != bytes_read) {
INFO << "partial read: nbytes=" << nbytes <<
", bytes_read=" << bytes_read << dendl;
}
INFO << bytes_read << " bytes read" << dendl;
return bytes_read;
}
arw::Result<std::shared_ptr<arw::Buffer>> Read(int64_t nbytes) override {
INFO << "entered: asking for " << nbytes << " bytes" << dendl;
std::shared_ptr<OwnedBuffer> buffer;
ARROW_ASSIGN_OR_RAISE(buffer, OwnedBuffer::make(nbytes));
ARROW_ASSIGN_OR_RAISE(const int64_t bytes_read,
Read(nbytes, buffer->writeable_data()));
buffer->set_size(bytes_read);
return buffer;
}
bool supports_zero_copy() const override {
return false;
}
// implement Seekable
arw::Result<int64_t> GetSize() override {
INFO << "entered: " << flight_data.obj_size << " returned" << dendl;
return flight_data.obj_size;
}
arw::Result<arw::util::string_view> Peek(int64_t nbytes) override {
INFO << "entered: " << nbytes << " bytes" << dendl;
int64_t saved_position = position;
ARROW_ASSIGN_OR_RAISE(OwningStringView buffer,
OwningStringView::make(nbytes));
ARROW_ASSIGN_OR_RAISE(const int64_t bytes_read,
Read(nbytes, (void*) buffer.writeable_data()));
// restore position for a peek
position = saved_position;
if (bytes_read < nbytes) {
// create new OwningStringView with moved buffer
return OwningStringView::shrink(std::move(buffer), bytes_read);
} else {
return buffer;
}
}
arw::Result<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadata() {
return flight_data.kv_metadata;
}
arw::Future<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadataAsync(
const arw::io::IOContext& io_context) override {
return arw::Future<std::shared_ptr<const arw::KeyValueMetadata>>::MakeFinished(ReadMetadata());
}
// implement Seekable interface
arw::Status Seek(int64_t new_position) {
INFO << "entered: position: " << new_position << dendl;
if (position < 0) {
ERROR << "error, position indicated error" << dendl;
return arw::Status::IOError("object read op is in bad state");
} else {
position = new_position;
return arw::Status::OK();
}
}
}; // class RandomAccessObject
arw::Status FlightServer::DoGet(const flt::ServerCallContext &context,
const flt::Ticket &request,
std::unique_ptr<flt::FlightDataStream> *stream) {
int ret;
ARROW_ASSIGN_OR_RAISE(FlightKey key, TicketToFlightKey(request));
ARROW_ASSIGN_OR_RAISE(FlightData fd, get_flight_store()->get_flight(key));
std::unique_ptr<rgw::sal::User> user = driver->get_user(fd.user_id);
if (user->empty()) {
INFO << "user is empty" << dendl;
} else {
// TODO: test what happens if user is not loaded
ret = user->load_user(&dp, null_yield);
if (ret < 0) {
ERROR << "load_user returned " << ret << dendl;
// TODO return something
}
INFO << "user is " << user->get_display_name() << dendl;
}
std::unique_ptr<rgw::sal::Bucket> bucket;
ret = driver->get_bucket(&dp, &(*user), fd.tenant_name, fd.bucket_name,
&bucket, null_yield);
if (ret < 0) {
ERROR << "get_bucket returned " << ret << dendl;
// TODO return something
}
std::unique_ptr<rgw::sal::Object> object = bucket->get_object(fd.object_key);
auto input = std::make_shared<RandomAccessObject>(fd, object, dp);
ARROW_RETURN_NOT_OK(input->Open());
std::unique_ptr<parquet::arrow::FileReader> reader;
ARROW_RETURN_NOT_OK(parquet::arrow::OpenFile(input,
arw::default_memory_pool(),
&reader));
std::shared_ptr<arrow::Table> table;
ARROW_RETURN_NOT_OK(reader->ReadTable(&table));
std::vector<std::shared_ptr<arw::RecordBatch>> batches;
arw::TableBatchReader batch_reader(*table);
ARROW_RETURN_NOT_OK(batch_reader.ReadAll(&batches));
ARROW_ASSIGN_OR_RAISE(auto owning_reader,
arw::RecordBatchReader::Make(
std::move(batches), table->schema()));
*stream = std::unique_ptr<flt::FlightDataStream>(
new flt::RecordBatchStream(owning_reader));
return arw::Status::OK();
} // flightServer::DoGet
} // namespace rgw::flight
| 20,311 | 27.016552 | 108 |
cc
|
null |
ceph-main/src/rgw/rgw_flight.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright 2023 IBM
*
* See file COPYING for licensing information.
*/
#pragma once
#include <map>
#include <mutex>
#include <atomic>
#include "include/common_fwd.h"
#include "common/ceph_context.h"
#include "common/Thread.h"
#include "common/ceph_time.h"
#include "rgw_frontend.h"
#include "arrow/type.h"
#include "arrow/flight/server.h"
#include "arrow/util/string_view.h"
#include "rgw_flight_frontend.h"
#define INFO_F(dp) ldpp_dout(&dp, 20) << "INFO: " << __func__ << ": "
#define STATUS_F(dp) ldpp_dout(&dp, 10) << "STATUS: " << __func__ << ": "
#define WARN_F(dp) ldpp_dout(&dp, 0) << "WARNING: " << __func__ << ": "
#define ERROR_F(dp) ldpp_dout(&dp, 0) << "ERROR: " << __func__ << ": "
#define INFO INFO_F(dp)
#define STATUS STATUS_F(dp)
#define WARN WARN_F(dp)
#define ERROR ERROR_F(dp)
namespace arw = arrow;
namespace flt = arrow::flight;
struct req_state;
namespace rgw::flight {
static const coarse_real_clock::duration lifespan = std::chrono::hours(1);
struct FlightData {
FlightKey key;
// coarse_real_clock::time_point expires;
std::string uri;
std::string tenant_name;
std::string bucket_name;
rgw_obj_key object_key;
// NB: what about object's namespace and instance?
uint64_t num_records;
uint64_t obj_size;
std::shared_ptr<arw::Schema> schema;
std::shared_ptr<const arw::KeyValueMetadata> kv_metadata;
rgw_user user_id; // TODO: this should be removed when we do
// proper flight authentication
FlightData(const std::string& _uri,
const std::string& _tenant_name,
const std::string& _bucket_name,
const rgw_obj_key& _object_key,
uint64_t _num_records,
uint64_t _obj_size,
std::shared_ptr<arw::Schema>& _schema,
std::shared_ptr<const arw::KeyValueMetadata>& _kv_metadata,
rgw_user _user_id);
};
// stores flights that have been created and helps expire them
class FlightStore {
protected:
const DoutPrefix& dp;
public:
FlightStore(const DoutPrefix& dp);
virtual ~FlightStore();
virtual FlightKey add_flight(FlightData&& flight) = 0;
// TODO consider returning const shared pointers to FlightData in
// the following two functions
virtual arw::Result<FlightData> get_flight(const FlightKey& key) const = 0;
virtual std::optional<FlightData> after_key(const FlightKey& key) const = 0;
virtual int remove_flight(const FlightKey& key) = 0;
virtual int expire_flights() = 0;
};
class MemoryFlightStore : public FlightStore {
std::map<FlightKey, FlightData> map;
mutable std::mutex mtx; // for map
public:
MemoryFlightStore(const DoutPrefix& dp);
virtual ~MemoryFlightStore();
FlightKey add_flight(FlightData&& flight) override;
arw::Result<FlightData> get_flight(const FlightKey& key) const override;
std::optional<FlightData> after_key(const FlightKey& key) const override;
int remove_flight(const FlightKey& key) override;
int expire_flights() override;
};
class FlightServer : public flt::FlightServerBase {
using Data1 = std::vector<std::shared_ptr<arw::RecordBatch>>;
RGWProcessEnv& env;
rgw::sal::Driver* driver;
const DoutPrefix& dp;
FlightStore* flight_store;
std::map<std::string, Data1> data;
public:
static constexpr int default_port = 8077;
FlightServer(RGWProcessEnv& env,
FlightStore* flight_store,
const DoutPrefix& dp);
~FlightServer() override;
FlightStore* get_flight_store() {
return flight_store;
}
arw::Status ListFlights(const flt::ServerCallContext& context,
const flt::Criteria* criteria,
std::unique_ptr<flt::FlightListing>* listings) override;
arw::Status GetFlightInfo(const flt::ServerCallContext &context,
const flt::FlightDescriptor &request,
std::unique_ptr<flt::FlightInfo> *info) override;
arw::Status GetSchema(const flt::ServerCallContext &context,
const flt::FlightDescriptor &request,
std::unique_ptr<flt::SchemaResult> *schema) override;
arw::Status DoGet(const flt::ServerCallContext &context,
const flt::Ticket &request,
std::unique_ptr<flt::FlightDataStream> *stream) override;
}; // class FlightServer
class OwningStringView : public arw::util::string_view {
uint8_t* buffer;
int64_t capacity;
int64_t consumed;
OwningStringView(uint8_t* _buffer, int64_t _size) :
arw::util::string_view((const char*) _buffer, _size),
buffer(_buffer),
capacity(_size),
consumed(_size)
{ }
OwningStringView(OwningStringView&& from, int64_t new_size) :
buffer(nullptr),
capacity(from.capacity),
consumed(new_size)
{
// should be impossible due to static function check
ceph_assertf(consumed <= capacity, "new size cannot exceed capacity");
std::swap(buffer, from.buffer);
from.capacity = 0;
from.consumed = 0;
}
public:
OwningStringView(OwningStringView&&) = default;
OwningStringView& operator=(OwningStringView&&) = default;
uint8_t* writeable_data() {
return buffer;
}
~OwningStringView() {
if (buffer) {
delete[] buffer;
}
}
static arw::Result<OwningStringView> make(int64_t size) {
uint8_t* buffer = new uint8_t[size];
if (!buffer) {
return arw::Status::OutOfMemory("could not allocated buffer of size %" PRId64, size);
}
return OwningStringView(buffer, size);
}
static arw::Result<OwningStringView> shrink(OwningStringView&& from,
int64_t new_size) {
if (new_size > from.capacity) {
return arw::Status::Invalid("new size cannot exceed capacity");
} else {
return OwningStringView(std::move(from), new_size);
}
}
};
// GLOBAL
flt::Ticket FlightKeyToTicket(const FlightKey& key);
arw::Status TicketToFlightKey(const flt::Ticket& t, FlightKey& key);
} // namespace rgw::flight
| 5,924 | 25.689189 | 91 |
h
|
null |
ceph-main/src/rgw/rgw_flight_frontend.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright 2023 IBM
*
* See file COPYING for licensing information.
*/
#include <cstdio>
#include <filesystem>
#include <sstream>
#include "arrow/type.h"
#include "arrow/flight/server.h"
#include "arrow/io/file.h"
#include "parquet/arrow/reader.h"
#include "parquet/arrow/schema.h"
#include "parquet/stream_reader.h"
#include "rgw_flight_frontend.h"
#include "rgw_flight.h"
// logging
constexpr unsigned dout_subsys = ceph_subsys_rgw_flight;
constexpr const char* dout_prefix_str = "rgw arrow_flight: ";
namespace rgw::flight {
const FlightKey null_flight_key = 0;
FlightFrontend::FlightFrontend(RGWProcessEnv& _env,
RGWFrontendConfig* _config,
int _port) :
env(_env),
config(_config),
port(_port),
dp(env.driver->ctx(), dout_subsys, dout_prefix_str)
{
env.flight_store = new MemoryFlightStore(dp);
env.flight_server = new FlightServer(env, env.flight_store, dp);
INFO << "flight server started" << dendl;
}
FlightFrontend::~FlightFrontend() {
delete env.flight_server;
env.flight_server = nullptr;
delete env.flight_store;
env.flight_store = nullptr;
INFO << "flight server shut down" << dendl;
}
int FlightFrontend::init() {
if (port <= 0) {
port = FlightServer::default_port;
}
const std::string url =
std::string("grpc+tcp://localhost:") + std::to_string(port);
flt::Location location;
arw::Status s = flt::Location::Parse(url, &location);
if (!s.ok()) {
ERROR << "couldn't parse url=" << url << ", status=" << s << dendl;
return -EINVAL;
}
flt::FlightServerOptions options(location);
options.verify_client = false;
s = env.flight_server->Init(options);
if (!s.ok()) {
ERROR << "couldn't init flight server; status=" << s << dendl;
return -EINVAL;
}
INFO << "FlightServer inited; will use port " << port << dendl;
return 0;
}
int FlightFrontend::run() {
try {
flight_thread = make_named_thread(server_thread_name,
&FlightServer::Serve,
env.flight_server);
INFO << "FlightServer thread started, id=" <<
flight_thread.get_id() <<
", joinable=" << flight_thread.joinable() << dendl;
return 0;
} catch (std::system_error& e) {
ERROR << "FlightServer thread failed to start" << dendl;
return -e.code().value();
}
}
void FlightFrontend::stop() {
env.flight_server->Shutdown();
env.flight_server->Wait();
INFO << "FlightServer shut down" << dendl;
}
void FlightFrontend::join() {
flight_thread.join();
INFO << "FlightServer thread joined" << dendl;
}
void FlightFrontend::pause_for_new_config() {
// ignore since config changes won't alter flight_server
}
void FlightFrontend::unpause_with_new_config() {
// ignore since config changes won't alter flight_server
}
/* ************************************************************ */
FlightGetObj_Filter::FlightGetObj_Filter(const req_state* request,
RGWGetObj_Filter* next) :
RGWGetObj_Filter(next),
penv(request->penv),
dp(request->cct->get(), dout_subsys, dout_prefix_str),
current_offset(0),
expected_size(request->obj_size),
uri(request->decoded_uri),
tenant_name(request->bucket->get_tenant()),
bucket_name(request->bucket->get_name()),
object_key(request->object->get_key()),
// note: what about object namespace and instance?
schema_status(arrow::StatusCode::Cancelled,
"schema determination incomplete"),
user_id(request->user->get_id())
{
#warning "TODO: fix use of tmpnam"
char name[L_tmpnam];
const char* namep = std::tmpnam(name);
if (!namep) {
//
}
temp_file_name = namep;
temp_file.open(temp_file_name);
}
FlightGetObj_Filter::~FlightGetObj_Filter() {
if (temp_file.is_open()) {
temp_file.close();
}
std::error_code error;
std::filesystem::remove(temp_file_name, error);
if (error) {
ERROR << "FlightGetObj_Filter got error when removing temp file; "
"error=" << error.value() <<
", temp_file_name=" << temp_file_name << dendl;
} else {
INFO << "parquet/arrow schema determination status: " <<
schema_status << dendl;
}
}
int FlightGetObj_Filter::handle_data(bufferlist& bl,
off_t bl_ofs, off_t bl_len) {
INFO << "flight handling data from offset " <<
current_offset << " (" << bl_ofs << ") of size " << bl_len << dendl;
current_offset += bl_len;
if (temp_file.is_open()) {
bl.write_stream(temp_file);
if (current_offset >= expected_size) {
INFO << "data read is completed, current_offset=" <<
current_offset << ", expected_size=" << expected_size << dendl;
temp_file.close();
std::shared_ptr<const arw::KeyValueMetadata> kv_metadata;
std::shared_ptr<arw::Schema> aw_schema;
int64_t num_rows = 0;
auto process_metadata = [&aw_schema, &num_rows, &kv_metadata, this]() -> arrow::Status {
ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::io::ReadableFile> file,
arrow::io::ReadableFile::Open(temp_file_name));
const std::shared_ptr<parquet::FileMetaData> metadata = parquet::ReadMetaData(file);
file->Close();
num_rows = metadata->num_rows();
kv_metadata = metadata->key_value_metadata();
const parquet::SchemaDescriptor* pq_schema = metadata->schema();
ARROW_RETURN_NOT_OK(parquet::arrow::FromParquetSchema(pq_schema, &aw_schema));
return arrow::Status::OK();
};
schema_status = process_metadata();
if (!schema_status.ok()) {
ERROR << "reading metadata to access schema, error=" << schema_status << dendl;
} else {
// INFO << "arrow_schema=" << *aw_schema << dendl;
FlightStore* store = penv.flight_store;
auto key =
store->add_flight(FlightData(uri, tenant_name, bucket_name,
object_key, num_rows,
expected_size, aw_schema,
kv_metadata, user_id));
(void) key; // suppress unused variable warning
}
} // if last block
} // if file opened
// chain to next filter in stream
int ret = RGWGetObj_Filter::handle_data(bl, bl_ofs, bl_len);
return ret;
}
#if 0
void code_snippets() {
INFO << "num_columns:" << md->num_columns() <<
" num_schema_elements:" << md->num_schema_elements() <<
" num_rows:" << md->num_rows() <<
" num_row_groups:" << md->num_row_groups() << dendl;
INFO << "file schema: name=" << schema1->name() << ", ToString:" << schema1->ToString() << ", num_columns=" << schema1->num_columns() << dendl;
for (int c = 0; c < schema1->num_columns(); ++c) {
const parquet::ColumnDescriptor* cd = schema1->Column(c);
// const parquet::ConvertedType::type t = cd->converted_type;
const std::shared_ptr<const parquet::LogicalType> lt = cd->logical_type();
INFO << "column " << c << ": name=" << cd->name() << ", ToString=" << cd->ToString() << ", logical_type=" << lt->ToString() << dendl;
}
INFO << "There are " << md->num_rows() << " rows and " << md->num_row_groups() << " row groups" << dendl;
for (int rg = 0; rg < md->num_row_groups(); ++rg) {
INFO << "Row Group " << rg << dendl;
auto rg_md = md->RowGroup(rg);
auto schema2 = rg_md->schema();
}
}
#endif
} // namespace rgw::flight
| 7,224 | 28.251012 | 145 |
cc
|
null |
ceph-main/src/rgw/rgw_flight_frontend.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright 2023 IBM
*
* See file COPYING for licensing information.
*/
#pragma once
#include "include/common_fwd.h"
#include "common/Thread.h"
#include "rgw_frontend.h"
#include "rgw_op.h"
#include "arrow/status.h"
namespace rgw::flight {
using FlightKey = uint32_t;
extern const FlightKey null_flight_key;
class FlightServer;
class FlightFrontend : public RGWFrontend {
static constexpr std::string_view server_thread_name =
"Arrow Flight Server thread";
RGWProcessEnv& env;
std::thread flight_thread;
RGWFrontendConfig* config;
int port;
const DoutPrefix dp;
public:
// port <= 0 means let server decide; typically 8077
FlightFrontend(RGWProcessEnv& env,
RGWFrontendConfig* config,
int port = -1);
~FlightFrontend() override;
int init() override;
int run() override;
void stop() override;
void join() override;
void pause_for_new_config() override;
void unpause_with_new_config() override;
}; // class FlightFrontend
class FlightGetObj_Filter : public RGWGetObj_Filter {
const RGWProcessEnv& penv;
const DoutPrefix dp;
FlightKey key;
uint64_t current_offset;
uint64_t expected_size;
std::string uri;
std::string tenant_name;
std::string bucket_name;
rgw_obj_key object_key;
std::string temp_file_name;
std::ofstream temp_file;
arrow::Status schema_status;
rgw_user user_id; // TODO: this should be removed when we do
// proper flight authentication
public:
FlightGetObj_Filter(const req_state* request, RGWGetObj_Filter* next);
~FlightGetObj_Filter();
int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override;
#if 0
// this would allow the range to be modified if necessary;
int fixup_range(off_t& ofs, off_t& end) override;
#endif
};
} // namespace rgw::flight
| 1,934 | 21.241379 | 72 |
h
|
null |
ceph-main/src/rgw/rgw_formats.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <boost/format.hpp>
#include "common/escape.h"
#include "common/Formatter.h"
#include "rgw/rgw_common.h"
#include "rgw/rgw_formats.h"
#include "rgw/rgw_rest.h"
#define LARGE_SIZE 8192
#define dout_subsys ceph_subsys_rgw
using namespace std;
RGWFormatter_Plain::RGWFormatter_Plain(const bool ukv)
: use_kv(ukv)
{
}
RGWFormatter_Plain::~RGWFormatter_Plain()
{
free(buf);
}
void RGWFormatter_Plain::flush(ostream& os)
{
if (!buf)
return;
if (len) {
os << buf;
os.flush();
}
reset_buf();
}
void RGWFormatter_Plain::reset_buf()
{
free(buf);
buf = NULL;
len = 0;
max_len = 0;
}
void RGWFormatter_Plain::reset()
{
reset_buf();
stack.clear();
min_stack_level = 0;
}
void RGWFormatter_Plain::open_array_section(std::string_view name)
{
struct plain_stack_entry new_entry;
new_entry.is_array = true;
new_entry.size = 0;
if (use_kv && min_stack_level > 0 && !stack.empty()) {
struct plain_stack_entry& entry = stack.back();
if (!entry.is_array)
dump_format(name, "");
}
stack.push_back(new_entry);
}
void RGWFormatter_Plain::open_array_section_in_ns(std::string_view name, const char *ns)
{
ostringstream oss;
oss << name << " " << ns;
open_array_section(oss.str().c_str());
}
void RGWFormatter_Plain::open_object_section(std::string_view name)
{
struct plain_stack_entry new_entry;
new_entry.is_array = false;
new_entry.size = 0;
if (use_kv && min_stack_level > 0)
dump_format(name, "");
stack.push_back(new_entry);
}
void RGWFormatter_Plain::open_object_section_in_ns(std::string_view name,
const char *ns)
{
ostringstream oss;
oss << name << " " << ns;
open_object_section(oss.str().c_str());
}
void RGWFormatter_Plain::close_section()
{
stack.pop_back();
}
void RGWFormatter_Plain::dump_unsigned(std::string_view name, uint64_t u)
{
dump_value_int(name, "%" PRIu64, u);
}
void RGWFormatter_Plain::dump_int(std::string_view name, int64_t u)
{
dump_value_int(name, "%" PRId64, u);
}
void RGWFormatter_Plain::dump_float(std::string_view name, double d)
{
dump_value_int(name, "%f", d);
}
void RGWFormatter_Plain::dump_string(std::string_view name, std::string_view s)
{
dump_format(name, "%.*s", s.size(), s.data());
}
std::ostream& RGWFormatter_Plain::dump_stream(std::string_view name)
{
// TODO: implement this!
ceph_abort();
}
void RGWFormatter_Plain::dump_format_va(std::string_view name, const char *ns, bool quoted, const char *fmt, va_list ap)
{
char buf[LARGE_SIZE];
struct plain_stack_entry& entry = stack.back();
if (!min_stack_level)
min_stack_level = stack.size();
bool should_print = ((stack.size() == min_stack_level && !entry.size) || use_kv);
entry.size++;
if (!should_print)
return;
vsnprintf(buf, LARGE_SIZE, fmt, ap);
const char *eol;
if (wrote_something) {
if (use_kv && entry.is_array && entry.size > 1)
eol = ", ";
else
eol = "\n";
} else
eol = "";
wrote_something = true;
if (use_kv && !entry.is_array)
write_data("%s%.*s: %s", eol, name.size(), name.data(), buf);
else
write_data("%s%s", eol, buf);
}
int RGWFormatter_Plain::get_len() const
{
// don't include null termination in length
return (len ? len - 1 : 0);
}
void RGWFormatter_Plain::write_raw_data(const char *data)
{
write_data("%s", data);
}
void RGWFormatter_Plain::write_data(const char *fmt, ...)
{
#define LARGE_ENOUGH_LEN 128
int n, size = LARGE_ENOUGH_LEN;
char s[size + 8];
char *p, *np;
bool p_on_stack;
va_list ap;
int pos;
p = s;
p_on_stack = true;
while (1) {
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n > -1 && n < size)
goto done;
/* Else try again with more space. */
if (n > -1) /* glibc 2.1 */
size = n+1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
if (p_on_stack)
np = (char *)malloc(size + 8);
else
np = (char *)realloc(p, size + 8);
if (!np)
goto done_free;
p = np;
p_on_stack = false;
}
done:
#define LARGE_ENOUGH_BUF 4096
if (!buf) {
max_len = std::max(LARGE_ENOUGH_BUF, size);
buf = (char *)malloc(max_len);
if (!buf) {
cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl;
goto done_free;
}
}
if (len + size > max_len) {
max_len = len + size + LARGE_ENOUGH_BUF;
void *_realloc = NULL;
if ((_realloc = realloc(buf, max_len)) == NULL) {
cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl;
goto done_free;
} else {
buf = (char *)_realloc;
}
}
pos = len;
if (len)
pos--; // squash null termination
strcpy(buf + pos, p);
len = pos + strlen(p) + 1;
done_free:
if (!p_on_stack)
free(p);
}
void RGWFormatter_Plain::dump_value_int(std::string_view name, const char *fmt, ...)
{
char buf[LARGE_SIZE];
va_list ap;
if (!min_stack_level)
min_stack_level = stack.size();
struct plain_stack_entry& entry = stack.back();
bool should_print = ((stack.size() == min_stack_level && !entry.size) || use_kv);
entry.size++;
if (!should_print)
return;
va_start(ap, fmt);
vsnprintf(buf, LARGE_SIZE, fmt, ap);
va_end(ap);
const char *eol;
if (wrote_something) {
eol = "\n";
} else
eol = "";
wrote_something = true;
if (use_kv && !entry.is_array)
write_data("%s%.*s: %s", eol, name.size(), name.data(), buf);
else
write_data("%s%s", eol, buf);
}
/* An utility class that serves as a mean to access the protected static
* methods of XMLFormatter. */
class HTMLHelper : public XMLFormatter {
public:
static std::string escape(const std::string& unescaped_str) {
int len = escape_xml_attr_len(unescaped_str.c_str());
std::string escaped(len, 0);
escape_xml_attr(unescaped_str.c_str(), escaped.data());
return escaped;
}
};
void RGWSwiftWebsiteListingFormatter::generate_header(
const std::string& dir_path,
const std::string& css_path)
{
ss << R"(<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 )"
<< R"(Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">)";
ss << "<html><head><title>Listing of " << xml_stream_escaper(dir_path)
<< "</title>";
if (! css_path.empty()) {
ss << boost::format(R"(<link rel="stylesheet" type="text/css" href="%s" />)")
% url_encode(css_path);
} else {
ss << R"(<style type="text/css">)"
<< R"(h1 {font-size: 1em; font-weight: bold;})"
<< R"(th {text-align: left; padding: 0px 1em 0px 1em;})"
<< R"(td {padding: 0px 1em 0px 1em;})"
<< R"(a {text-decoration: none;})"
<< R"(</style>)";
}
ss << "</head><body>";
ss << R"(<h1 id="title">Listing of )" << xml_stream_escaper(dir_path) << "</h1>"
<< R"(<table id="listing">)"
<< R"(<tr id="heading">)"
<< R"(<th class="colname">Name</th>)"
<< R"(<th class="colsize">Size</th>)"
<< R"(<th class="coldate">Date</th>)"
<< R"(</tr>)";
if (! prefix.empty()) {
ss << R"(<tr id="parent" class="item">)"
<< R"(<td class="colname"><a href="../">../</a></td>)"
<< R"(<td class="colsize"> </td>)"
<< R"(<td class="coldate"> </td>)"
<< R"(</tr>)";
}
}
void RGWSwiftWebsiteListingFormatter::generate_footer()
{
ss << R"(</table></body></html>)";
}
std::string RGWSwiftWebsiteListingFormatter::format_name(
const std::string& item_name) const
{
return item_name.substr(prefix.length());
}
void RGWSwiftWebsiteListingFormatter::dump_object(const rgw_bucket_dir_entry& objent)
{
const auto name = format_name(objent.key.name);
ss << boost::format(R"(<tr class="item %s">)")
% "default"
<< boost::format(R"(<td class="colname"><a href="%s">%s</a></td>)")
% url_encode(name)
% HTMLHelper::escape(name)
<< boost::format(R"(<td class="colsize">%lld</td>)") % objent.meta.size
<< boost::format(R"(<td class="coldate">%s</td>)")
% dump_time_to_str(objent.meta.mtime)
<< R"(</tr>)";
}
void RGWSwiftWebsiteListingFormatter::dump_subdir(const std::string& name)
{
const auto fname = format_name(name);
ss << R"(<tr class="item subdir">)"
<< boost::format(R"(<td class="colname"><a href="%s">%s</a></td>)")
% url_encode(fname)
% HTMLHelper::escape(fname)
<< R"(<td class="colsize"> </td>)"
<< R"(<td class="coldate"> </td>)"
<< R"(</tr>)";
}
| 9,132 | 23.225464 | 120 |
cc
|
null |
ceph-main/src/rgw/rgw_formats.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "common/Formatter.h"
#include <list>
#include <stdint.h>
#include <string>
#include <ostream>
struct plain_stack_entry {
int size;
bool is_array;
};
/* FIXME: this class is mis-named.
* FIXME: This was a hack to send certain swift messages.
* There is a much better way to do this.
*/
class RGWFormatter_Plain : public Formatter {
void reset_buf();
public:
explicit RGWFormatter_Plain(bool use_kv = false);
~RGWFormatter_Plain() override;
void set_status(int status, const char* status_name) override {};
void output_header() override {};
void output_footer() override {};
void enable_line_break() override {};
void flush(std::ostream& os) override;
void reset() override;
void open_array_section(std::string_view name) override;
void open_array_section_in_ns(std::string_view name, const char *ns) override;
void open_object_section(std::string_view name) override;
void open_object_section_in_ns(std::string_view name, const char *ns) override;
void close_section() override;
void dump_unsigned(std::string_view name, uint64_t u) override;
void dump_int(std::string_view name, int64_t u) override;
void dump_float(std::string_view name, double d) override;
void dump_string(std::string_view name, std::string_view s) override;
std::ostream& dump_stream(std::string_view name) override;
void dump_format_va(std::string_view name, const char *ns, bool quoted, const char *fmt, va_list ap) override;
int get_len() const override;
void write_raw_data(const char *data) override;
private:
void write_data(const char *fmt, ...);
void dump_value_int(std::string_view name, const char *fmt, ...);
char *buf = nullptr;
int len = 0;
int max_len = 0;
std::list<struct plain_stack_entry> stack;
size_t min_stack_level = 0;
bool use_kv;
bool wrote_something = 0;
};
/* This is a presentation layer. No logic inside, please. */
class RGWSwiftWebsiteListingFormatter {
std::ostream& ss;
const std::string prefix;
protected:
std::string format_name(const std::string& item_name) const;
public:
RGWSwiftWebsiteListingFormatter(std::ostream& ss,
std::string prefix)
: ss(ss),
prefix(std::move(prefix)) {
}
/* The supplied css_path can be empty. In such situation a default,
* embedded style sheet will be generated. */
void generate_header(const std::string& dir_path,
const std::string& css_path);
void generate_footer();
void dump_object(const rgw_bucket_dir_entry& objent);
void dump_subdir(const std::string& name);
};
class RGWFormatterFlusher {
protected:
Formatter *formatter;
bool flushed;
bool started;
virtual void do_flush() = 0;
virtual void do_start(int ret) {}
void set_formatter(Formatter *f) {
formatter = f;
}
public:
explicit RGWFormatterFlusher(Formatter *f) : formatter(f), flushed(false), started(false) {}
virtual ~RGWFormatterFlusher() {}
void flush() {
do_flush();
flushed = true;
}
virtual void start(int client_ret) {
if (!started)
do_start(client_ret);
started = true;
}
Formatter *get_formatter() { return formatter; }
bool did_flush() { return flushed; }
bool did_start() { return started; }
};
class RGWStreamFlusher : public RGWFormatterFlusher {
std::ostream& os;
protected:
void do_flush() override {
formatter->flush(os);
}
public:
RGWStreamFlusher(Formatter *f, std::ostream& _os) : RGWFormatterFlusher(f), os(_os) {}
};
class RGWNullFlusher : public RGWFormatterFlusher {
protected:
void do_flush() override {
}
public:
RGWNullFlusher() : RGWFormatterFlusher(nullptr) {}
};
| 3,776 | 27.186567 | 112 |
h
|
null |
ceph-main/src/rgw/rgw_frontend.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <signal.h>
#include "rgw_frontend.h"
#include "include/str_list.h"
#include "include/ceph_assert.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
int RGWFrontendConfig::parse_config(const string& config,
std::multimap<string, string>& config_map)
{
for (auto& entry : get_str_vec(config, " ")) {
string key;
string val;
if (framework.empty()) {
framework = entry;
dout(0) << "framework: " << framework << dendl;
continue;
}
ssize_t pos = entry.find('=');
if (pos < 0) {
dout(0) << "framework conf key: " << entry << dendl;
config_map.emplace(std::move(entry), "");
continue;
}
int ret = parse_key_value(entry, key, val);
if (ret < 0) {
cerr << "ERROR: can't parse " << entry << std::endl;
return ret;
}
dout(0) << "framework conf key: " << key << ", val: " << val << dendl;
config_map.emplace(std::move(key), std::move(val));
}
return 0;
}
void RGWFrontendConfig::set_default_config(RGWFrontendConfig& def_conf)
{
const auto& def_conf_map = def_conf.get_config_map();
for (auto& entry : def_conf_map) {
if (config_map.find(entry.first) == config_map.end()) {
config_map.emplace(entry.first, entry.second);
}
}
}
std::optional<string> RGWFrontendConfig::get_val(const std::string& key)
{
auto iter = config_map.find(key);
if (iter == config_map.end()) {
return std::nullopt;
}
return iter->second;
}
bool RGWFrontendConfig::get_val(const string& key, const string& def_val,
string *out)
{
auto iter = config_map.find(key);
if (iter == config_map.end()) {
*out = def_val;
return false;
}
*out = iter->second;
return true;
}
bool RGWFrontendConfig::get_val(const string& key, int def_val, int *out)
{
string str;
bool found = get_val(key, "", &str);
if (!found) {
*out = def_val;
return false;
}
string err;
*out = strict_strtol(str.c_str(), 10, &err);
if (!err.empty()) {
cerr << "error parsing int: " << str << ": " << err << std::endl;
return -EINVAL;
}
return 0;
}
void RGWProcessFrontend::stop()
{
pprocess->close_fd();
thread->kill(SIGUSR1);
}
| 2,318 | 20.877358 | 74 |
cc
|
null |
ceph-main/src/rgw/rgw_frontend.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <string>
#include <vector>
#include "common/RWLock.h"
#include "rgw_request.h"
#include "rgw_process.h"
#include "rgw_process_env.h"
#include "rgw_realm_reloader.h"
#include "rgw_auth_registry.h"
#include "rgw_sal_rados.h"
#define dout_context g_ceph_context
namespace rgw::dmclock {
class SyncScheduler;
class ClientConfig;
class SchedulerCtx;
}
class RGWFrontendConfig {
std::string config;
std::multimap<std::string, std::string> config_map;
std::string framework;
int parse_config(const std::string& config,
std::multimap<std::string, std::string>& config_map);
public:
explicit RGWFrontendConfig(const std::string& config)
: config(config) {
}
int init() {
const int ret = parse_config(config, config_map);
return ret < 0 ? ret : 0;
}
void set_default_config(RGWFrontendConfig& def_conf);
std::optional<std::string> get_val(const std::string& key);
bool get_val(const std::string& key,
const std::string& def_val,
std::string* out);
bool get_val(const std::string& key, int def_val, int *out);
std::string get_val(const std::string& key,
const std::string& def_val) {
std::string out;
get_val(key, def_val, &out);
return out;
}
const std::string& get_config() {
return config;
}
std::multimap<std::string, std::string>& get_config_map() {
return config_map;
}
std::string get_framework() const {
return framework;
}
};
class RGWFrontend {
public:
virtual ~RGWFrontend() {}
virtual int init() = 0;
virtual int run() = 0;
virtual void stop() = 0;
virtual void join() = 0;
virtual void pause_for_new_config() = 0;
virtual void unpause_with_new_config() = 0;
};
class RGWProcessFrontend : public RGWFrontend {
protected:
RGWFrontendConfig* conf;
RGWProcess* pprocess;
RGWProcessEnv& env;
RGWProcessControlThread* thread;
public:
RGWProcessFrontend(RGWProcessEnv& pe, RGWFrontendConfig* _conf)
: conf(_conf), pprocess(nullptr), env(pe), thread(nullptr) {
}
~RGWProcessFrontend() override {
delete thread;
delete pprocess;
}
int run() override {
ceph_assert(pprocess); /* should have initialized by init() */
thread = new RGWProcessControlThread(pprocess);
thread->create("rgw_frontend");
return 0;
}
void stop() override;
void join() override {
thread->join();
}
void pause_for_new_config() override {
pprocess->pause();
}
void unpause_with_new_config() override {
pprocess->unpause_with_new_config();
}
}; /* RGWProcessFrontend */
class RGWLoadGenFrontend : public RGWProcessFrontend, public DoutPrefixProvider {
public:
RGWLoadGenFrontend(RGWProcessEnv& pe, RGWFrontendConfig *_conf)
: RGWProcessFrontend(pe, _conf) {}
CephContext *get_cct() const {
return env.driver->ctx();
}
unsigned get_subsys() const
{
return ceph_subsys_rgw;
}
std::ostream& gen_prefix(std::ostream& out) const
{
return out << "rgw loadgen frontend: ";
}
int init() override {
int num_threads;
conf->get_val("num_threads", g_conf()->rgw_thread_pool_size, &num_threads);
std::string uri_prefix;
conf->get_val("prefix", "", &uri_prefix);
RGWLoadGenProcess *pp = new RGWLoadGenProcess(
g_ceph_context, env, num_threads, std::move(uri_prefix), conf);
pprocess = pp;
std::string uid_str;
conf->get_val("uid", "", &uid_str);
if (uid_str.empty()) {
derr << "ERROR: uid param must be specified for loadgen frontend"
<< dendl;
return -EINVAL;
}
rgw_user uid(uid_str);
std::unique_ptr<rgw::sal::User> user = env.driver->get_user(uid);
int ret = user->load_user(this, null_yield);
if (ret < 0) {
derr << "ERROR: failed reading user info: uid=" << uid << " ret="
<< ret << dendl;
return ret;
}
auto aiter = user->get_info().access_keys.begin();
if (aiter == user->get_info().access_keys.end()) {
derr << "ERROR: user has no S3 access keys set" << dendl;
return -EINVAL;
}
pp->set_access_key(aiter->second);
return 0;
}
}; /* RGWLoadGenFrontend */
// FrontendPauser implementation for RGWRealmReloader
class RGWFrontendPauser : public RGWRealmReloader::Pauser {
std::vector<RGWFrontend*> &frontends;
RGWRealmReloader::Pauser* pauser;
public:
RGWFrontendPauser(std::vector<RGWFrontend*> &frontends,
RGWRealmReloader::Pauser* pauser = nullptr)
: frontends(frontends), pauser(pauser) {}
void pause() override {
for (auto frontend : frontends)
frontend->pause_for_new_config();
if (pauser)
pauser->pause();
}
void resume(rgw::sal::Driver* driver) override {
for (auto frontend : frontends)
frontend->unpause_with_new_config();
if (pauser)
pauser->resume(driver);
}
};
| 5,004 | 22.608491 | 81 |
h
|
null |
ceph-main/src/rgw/rgw_gc_log.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "include/rados/librados.hpp"
#include "cls/rgw/cls_rgw_types.h"
// initialize the cls_rgw_gc queue
void gc_log_init2(librados::ObjectWriteOperation& op,
uint64_t max_size, uint64_t max_deferred);
// enqueue a gc entry to omap with cls_rgw
void gc_log_enqueue1(librados::ObjectWriteOperation& op,
uint32_t expiration, cls_rgw_gc_obj_info& info);
// enqueue a gc entry to the cls_rgw_gc queue
void gc_log_enqueue2(librados::ObjectWriteOperation& op,
uint32_t expiration, const cls_rgw_gc_obj_info& info);
// defer a gc entry in omap with cls_rgw
void gc_log_defer1(librados::ObjectWriteOperation& op,
uint32_t expiration, const cls_rgw_gc_obj_info& info);
// defer a gc entry in the cls_rgw_gc queue
void gc_log_defer2(librados::ObjectWriteOperation& op,
uint32_t expiration, const cls_rgw_gc_obj_info& info);
| 1,041 | 34.931034 | 75 |
h
|
null |
ceph-main/src/rgw/rgw_http_client.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "include/compat.h"
#include "common/errno.h"
#include <curl/curl.h>
#include <curl/easy.h>
#include <curl/multi.h>
#include "rgw_common.h"
#include "rgw_http_client.h"
#include "rgw_http_errors.h"
#include "common/async/completion.h"
#include "common/RefCountedObj.h"
#include "rgw_coroutine.h"
#include "rgw_tools.h"
#include <atomic>
#include <string_view>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
RGWHTTPManager *rgw_http_manager;
struct RGWCurlHandle;
static void do_curl_easy_cleanup(RGWCurlHandle *curl_handle);
struct rgw_http_req_data : public RefCountedObject {
RGWCurlHandle *curl_handle{nullptr};
curl_slist *h{nullptr};
uint64_t id;
int ret{0};
std::atomic<bool> done = { false };
RGWHTTPClient *client{nullptr};
rgw_io_id control_io_id;
void *user_info{nullptr};
bool registered{false};
RGWHTTPManager *mgr{nullptr};
char error_buf[CURL_ERROR_SIZE];
bool write_paused{false};
bool read_paused{false};
optional<int> user_ret;
ceph::mutex lock = ceph::make_mutex("rgw_http_req_data::lock");
ceph::condition_variable cond;
using Signature = void(boost::system::error_code);
using Completion = ceph::async::Completion<Signature>;
std::unique_ptr<Completion> completion;
rgw_http_req_data() : id(-1) {
// FIPS zeroization audit 20191115: this memset is not security related.
memset(error_buf, 0, sizeof(error_buf));
}
template <typename ExecutionContext, typename CompletionToken>
auto async_wait(ExecutionContext& ctx, CompletionToken&& token) {
boost::asio::async_completion<CompletionToken, Signature> init(token);
auto& handler = init.completion_handler;
{
std::unique_lock l{lock};
completion = Completion::create(ctx.get_executor(), std::move(handler));
}
return init.result.get();
}
int wait(optional_yield y) {
if (done) {
return ret;
}
if (y) {
auto& context = y.get_io_context();
auto& yield = y.get_yield_context();
boost::system::error_code ec;
async_wait(context, yield[ec]);
return -ec.value();
}
// work on asio threads should be asynchronous, so warn when they block
if (is_asio_thread) {
dout(20) << "WARNING: blocking http request" << dendl;
}
std::unique_lock l{lock};
cond.wait(l, [this]{return done==true;});
return ret;
}
void set_state(int bitmask);
void finish(int r, long http_status = -1) {
std::lock_guard l{lock};
if (http_status != -1) {
if (client) {
client->set_http_status(http_status);
}
}
ret = r;
if (curl_handle)
do_curl_easy_cleanup(curl_handle);
if (h)
curl_slist_free_all(h);
curl_handle = NULL;
h = NULL;
done = true;
if (completion) {
boost::system::error_code ec(-ret, boost::system::system_category());
Completion::post(std::move(completion), ec);
} else {
cond.notify_all();
}
}
bool is_done() {
return done;
}
int get_retcode() {
std::lock_guard l{lock};
return ret;
}
RGWHTTPManager *get_manager() {
std::lock_guard l{lock};
return mgr;
}
CURL *get_easy_handle() const;
};
struct RGWCurlHandle {
int uses;
mono_time lastuse;
CURL* h;
explicit RGWCurlHandle(CURL* h) : uses(0), h(h) {};
CURL* operator*() {
return this->h;
}
};
void rgw_http_req_data::set_state(int bitmask) {
/* no need to lock here, moreover curl_easy_pause() might trigger
* the data receive callback :/
*/
CURLcode rc = curl_easy_pause(**curl_handle, bitmask);
if (rc != CURLE_OK) {
dout(0) << "ERROR: curl_easy_pause() returned rc=" << rc << dendl;
}
}
#define MAXIDLE 5
class RGWCurlHandles : public Thread {
public:
ceph::mutex cleaner_lock = ceph::make_mutex("RGWCurlHandles::cleaner_lock");
std::vector<RGWCurlHandle*> saved_curl;
int cleaner_shutdown;
ceph::condition_variable cleaner_cond;
RGWCurlHandles() :
cleaner_shutdown{0} {
}
RGWCurlHandle* get_curl_handle();
void release_curl_handle_now(RGWCurlHandle* curl);
void release_curl_handle(RGWCurlHandle* curl);
void flush_curl_handles();
void* entry();
void stop();
};
RGWCurlHandle* RGWCurlHandles::get_curl_handle() {
RGWCurlHandle* curl = 0;
CURL* h;
{
std::lock_guard lock{cleaner_lock};
if (!saved_curl.empty()) {
curl = *saved_curl.begin();
saved_curl.erase(saved_curl.begin());
}
}
if (curl) {
} else if ((h = curl_easy_init())) {
curl = new RGWCurlHandle{h};
} else {
// curl = 0;
}
return curl;
}
void RGWCurlHandles::release_curl_handle_now(RGWCurlHandle* curl)
{
curl_easy_cleanup(**curl);
delete curl;
}
void RGWCurlHandles::release_curl_handle(RGWCurlHandle* curl)
{
if (cleaner_shutdown) {
release_curl_handle_now(curl);
} else {
curl_easy_reset(**curl);
std::lock_guard lock{cleaner_lock};
curl->lastuse = mono_clock::now();
saved_curl.insert(saved_curl.begin(), 1, curl);
}
}
void* RGWCurlHandles::entry()
{
RGWCurlHandle* curl;
std::unique_lock lock{cleaner_lock};
for (;;) {
if (cleaner_shutdown) {
if (saved_curl.empty())
break;
} else {
cleaner_cond.wait_for(lock, std::chrono::seconds(MAXIDLE));
}
mono_time now = mono_clock::now();
while (!saved_curl.empty()) {
auto cend = saved_curl.end();
--cend;
curl = *cend;
if (!cleaner_shutdown && now - curl->lastuse < std::chrono::seconds(MAXIDLE))
break;
saved_curl.erase(cend);
release_curl_handle_now(curl);
}
}
return nullptr;
}
void RGWCurlHandles::stop()
{
std::lock_guard lock{cleaner_lock};
cleaner_shutdown = 1;
cleaner_cond.notify_all();
}
void RGWCurlHandles::flush_curl_handles()
{
stop();
join();
if (!saved_curl.empty()) {
dout(0) << "ERROR: " << __func__ << " failed final cleanup" << dendl;
}
saved_curl.shrink_to_fit();
}
CURL *rgw_http_req_data::get_easy_handle() const
{
return **curl_handle;
}
static RGWCurlHandles *handles;
static RGWCurlHandle *do_curl_easy_init()
{
return handles->get_curl_handle();
}
static void do_curl_easy_cleanup(RGWCurlHandle *curl_handle)
{
handles->release_curl_handle(curl_handle);
}
// XXX make this part of the token cache? (but that's swift-only;
// and this especially needs to integrates with s3...)
void rgw_setup_saved_curl_handles()
{
handles = new RGWCurlHandles();
handles->create("rgw_curl");
}
void rgw_release_all_curl_handles()
{
handles->flush_curl_handles();
delete handles;
}
void RGWIOProvider::assign_io(RGWIOIDProvider& io_id_provider, int io_type)
{
if (id == 0) {
id = io_id_provider.get_next();
}
}
RGWHTTPClient::RGWHTTPClient(CephContext *cct,
const string& _method,
const string& _url)
: NoDoutPrefix(cct, dout_subsys),
has_send_len(false),
http_status(HTTP_STATUS_NOSTATUS),
req_data(nullptr),
verify_ssl(cct->_conf->rgw_verify_ssl),
cct(cct),
method(_method),
url(_url) {
init();
}
std::ostream& RGWHTTPClient::gen_prefix(std::ostream& out) const
{
out << "http_client[" << method << "/" << url << "]";
return out;
}
void RGWHTTPClient::init()
{
auto pos = url.find("://");
if (pos == string::npos) {
host = url;
return;
}
protocol = url.substr(0, pos);
pos += 3;
auto host_end_pos = url.find("/", pos);
if (host_end_pos == string::npos) {
host = url.substr(pos);
return;
}
host = url.substr(pos, host_end_pos - pos);
resource_prefix = url.substr(host_end_pos + 1);
if (resource_prefix.size() > 0 && resource_prefix[resource_prefix.size() - 1] != '/') {
resource_prefix.append("/");
}
}
/*
* the following set of callbacks will be called either on RGWHTTPManager::process(),
* or via the RGWHTTPManager async processing.
*/
size_t RGWHTTPClient::receive_http_header(void * const ptr,
const size_t size,
const size_t nmemb,
void * const _info)
{
rgw_http_req_data *req_data = static_cast<rgw_http_req_data *>(_info);
size_t len = size * nmemb;
std::lock_guard l{req_data->lock};
if (!req_data->registered) {
return len;
}
int ret = req_data->client->receive_header(ptr, size * nmemb);
if (ret < 0) {
dout(5) << "WARNING: client->receive_header() returned ret=" << ret << dendl;
req_data->user_ret = ret;
return CURLE_WRITE_ERROR;
}
return len;
}
size_t RGWHTTPClient::receive_http_data(void * const ptr,
const size_t size,
const size_t nmemb,
void * const _info)
{
rgw_http_req_data *req_data = static_cast<rgw_http_req_data *>(_info);
size_t len = size * nmemb;
bool pause = false;
RGWHTTPClient *client;
{
std::lock_guard l{req_data->lock};
if (!req_data->registered) {
return len;
}
client = req_data->client;
}
size_t& skip_bytes = client->receive_pause_skip;
if (skip_bytes >= len) {
skip_bytes -= len;
return len;
}
int ret = client->receive_data((char *)ptr + skip_bytes, len - skip_bytes, &pause);
if (ret < 0) {
dout(5) << "WARNING: client->receive_data() returned ret=" << ret << dendl;
req_data->user_ret = ret;
return CURLE_WRITE_ERROR;
}
if (pause) {
dout(20) << "RGWHTTPClient::receive_http_data(): pause" << dendl;
skip_bytes = len;
std::lock_guard l{req_data->lock};
req_data->read_paused = true;
return CURL_WRITEFUNC_PAUSE;
}
skip_bytes = 0;
return len;
}
size_t RGWHTTPClient::send_http_data(void * const ptr,
const size_t size,
const size_t nmemb,
void * const _info)
{
rgw_http_req_data *req_data = static_cast<rgw_http_req_data *>(_info);
RGWHTTPClient *client;
{
std::lock_guard l{req_data->lock};
if (!req_data->registered) {
return 0;
}
client = req_data->client;
}
bool pause = false;
int ret = client->send_data(ptr, size * nmemb, &pause);
if (ret < 0) {
dout(5) << "WARNING: client->send_data() returned ret=" << ret << dendl;
req_data->user_ret = ret;
return CURLE_READ_ERROR;
}
if (ret == 0 &&
pause) {
std::lock_guard l{req_data->lock};
req_data->write_paused = true;
return CURL_READFUNC_PAUSE;
}
return ret;
}
ceph::mutex& RGWHTTPClient::get_req_lock()
{
return req_data->lock;
}
void RGWHTTPClient::_set_write_paused(bool pause)
{
ceph_assert(ceph_mutex_is_locked(req_data->lock));
RGWHTTPManager *mgr = req_data->mgr;
if (pause == req_data->write_paused) {
return;
}
if (pause) {
mgr->set_request_state(this, SET_WRITE_PAUSED);
} else {
mgr->set_request_state(this, SET_WRITE_RESUME);
}
}
void RGWHTTPClient::_set_read_paused(bool pause)
{
ceph_assert(ceph_mutex_is_locked(req_data->lock));
RGWHTTPManager *mgr = req_data->mgr;
if (pause == req_data->read_paused) {
return;
}
if (pause) {
mgr->set_request_state(this, SET_READ_PAUSED);
} else {
mgr->set_request_state(this, SET_READ_RESUME);
}
}
static curl_slist *headers_to_slist(param_vec_t& headers)
{
curl_slist *h = NULL;
param_vec_t::iterator iter;
for (iter = headers.begin(); iter != headers.end(); ++iter) {
pair<string, string>& p = *iter;
string val = p.first;
if (strncmp(val.c_str(), "HTTP_", 5) == 0) {
val = val.substr(5);
}
/* we need to convert all underscores into dashes as some web servers forbid them
* in the http header field names
*/
for (size_t i = 0; i < val.size(); i++) {
if (val[i] == '_') {
val[i] = '-';
}
}
val = camelcase_dash_http_attr(val);
// curl won't send headers with empty values unless it ends with a ; instead
if (p.second.empty()) {
val.append(1, ';');
} else {
val.append(": ");
val.append(p.second);
}
h = curl_slist_append(h, val.c_str());
}
return h;
}
static bool is_upload_request(const string& method)
{
return method == "POST" || method == "PUT";
}
/*
* process a single simple one off request
*/
int RGWHTTPClient::process(optional_yield y)
{
return RGWHTTP::process(this, y);
}
string RGWHTTPClient::to_str()
{
string method_str = (method.empty() ? "<no-method>" : method);
string url_str = (url.empty() ? "<no-url>" : url);
return method_str + " " + url_str;
}
int RGWHTTPClient::get_req_retcode()
{
if (!req_data) {
return -EINVAL;
}
return req_data->get_retcode();
}
/*
* init request, will be used later with RGWHTTPManager
*/
int RGWHTTPClient::init_request(rgw_http_req_data *_req_data)
{
ceph_assert(!req_data);
_req_data->get();
req_data = _req_data;
req_data->curl_handle = do_curl_easy_init();
CURL *easy_handle = req_data->get_easy_handle();
dout(20) << "sending request to " << url << dendl;
curl_slist *h = headers_to_slist(headers);
req_data->h = h;
curl_easy_setopt(easy_handle, CURLOPT_CUSTOMREQUEST, method.c_str());
curl_easy_setopt(easy_handle, CURLOPT_URL, url.c_str());
curl_easy_setopt(easy_handle, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(easy_handle, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(easy_handle, CURLOPT_HEADERFUNCTION, receive_http_header);
curl_easy_setopt(easy_handle, CURLOPT_WRITEHEADER, (void *)req_data);
curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, receive_http_data);
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, (void *)req_data);
curl_easy_setopt(easy_handle, CURLOPT_ERRORBUFFER, (void *)req_data->error_buf);
curl_easy_setopt(easy_handle, CURLOPT_LOW_SPEED_TIME, cct->_conf->rgw_curl_low_speed_time);
curl_easy_setopt(easy_handle, CURLOPT_LOW_SPEED_LIMIT, cct->_conf->rgw_curl_low_speed_limit);
curl_easy_setopt(easy_handle, CURLOPT_TCP_KEEPALIVE, cct->_conf->rgw_curl_tcp_keepalive);
curl_easy_setopt(easy_handle, CURLOPT_READFUNCTION, send_http_data);
curl_easy_setopt(easy_handle, CURLOPT_READDATA, (void *)req_data);
curl_easy_setopt(easy_handle, CURLOPT_BUFFERSIZE, cct->_conf->rgw_curl_buffersize);
if (send_data_hint || is_upload_request(method)) {
curl_easy_setopt(easy_handle, CURLOPT_UPLOAD, 1L);
}
if (has_send_len) {
// TODO: prevent overflow by using curl_off_t
// and: CURLOPT_INFILESIZE_LARGE, CURLOPT_POSTFIELDSIZE_LARGE
const long size = send_len;
curl_easy_setopt(easy_handle, CURLOPT_INFILESIZE, size);
if (method == "POST") {
curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDSIZE, size);
// TODO: set to size smaller than 1MB should prevent the "Expect" field
// from being sent. So explicit removal is not needed
h = curl_slist_append(h, "Expect:");
}
}
if (method == "HEAD") {
curl_easy_setopt(easy_handle, CURLOPT_NOBODY, 1L);
}
if (h) {
curl_easy_setopt(easy_handle, CURLOPT_HTTPHEADER, (void *)h);
}
if (!verify_ssl) {
curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYHOST, 0L);
dout(20) << "ssl verification is set to off" << dendl;
} else {
if (!ca_path.empty()) {
curl_easy_setopt(easy_handle, CURLOPT_CAINFO, ca_path.c_str());
dout(20) << "using custom ca cert "<< ca_path.c_str() << " for ssl" << dendl;
}
if (!client_cert.empty()) {
if (!client_key.empty()) {
curl_easy_setopt(easy_handle, CURLOPT_SSLCERT, client_cert.c_str());
curl_easy_setopt(easy_handle, CURLOPT_SSLKEY, client_key.c_str());
dout(20) << "using custom client cert " << client_cert.c_str()
<< " and private key " << client_key.c_str() << dendl;
} else {
dout(5) << "private key is missing for client certificate" << dendl;
}
}
}
curl_easy_setopt(easy_handle, CURLOPT_PRIVATE, (void *)req_data);
curl_easy_setopt(easy_handle, CURLOPT_TIMEOUT, req_timeout);
return 0;
}
bool RGWHTTPClient::is_done()
{
return req_data->is_done();
}
/*
* wait for async request to complete
*/
int RGWHTTPClient::wait(optional_yield y)
{
return req_data->wait(y);
}
void RGWHTTPClient::cancel()
{
if (req_data) {
RGWHTTPManager *http_manager = req_data->mgr;
if (http_manager) {
http_manager->remove_request(this);
}
}
}
RGWHTTPClient::~RGWHTTPClient()
{
cancel();
if (req_data) {
req_data->put();
}
}
int RGWHTTPHeadersCollector::receive_header(void * const ptr, const size_t len)
{
const std::string_view header_line(static_cast<const char *>(ptr), len);
/* We're tokening the line that way due to backward compatibility. */
const size_t sep_loc = header_line.find_first_of(" \t:");
if (std::string_view::npos == sep_loc) {
/* Wrongly formatted header? Just skip it. */
return 0;
}
header_name_t name(header_line.substr(0, sep_loc));
if (0 == relevant_headers.count(name)) {
/* Not interested in this particular header. */
return 0;
}
const auto value_part = header_line.substr(sep_loc + 1);
/* Skip spaces and tabs after the separator. */
const size_t val_loc_s = value_part.find_first_not_of(' ');
const size_t val_loc_e = value_part.find_first_of("\r\n");
if (std::string_view::npos == val_loc_s ||
std::string_view::npos == val_loc_e) {
/* Empty value case. */
found_headers.emplace(name, header_value_t());
} else {
found_headers.emplace(name, header_value_t(
value_part.substr(val_loc_s, val_loc_e - val_loc_s)));
}
return 0;
}
int RGWHTTPTransceiver::send_data(void* ptr, size_t len, bool* pause)
{
int length_to_copy = 0;
if (post_data_index < post_data.length()) {
length_to_copy = min(post_data.length() - post_data_index, len);
memcpy(ptr, post_data.data() + post_data_index, length_to_copy);
post_data_index += length_to_copy;
}
return length_to_copy;
}
static int clear_signal(int fd)
{
// since we're in non-blocking mode, we can try to read a lot more than
// one signal from signal_thread() to avoid later wakeups
std::array<char, 256> buf{};
int ret = ::read(fd, (void *)buf.data(), buf.size());
if (ret < 0) {
ret = -errno;
return ret == -EAGAIN ? 0 : ret; // clear EAGAIN
}
return 0;
}
static int do_curl_wait(CephContext *cct, CURLM *handle, int signal_fd)
{
int num_fds;
struct curl_waitfd wait_fd;
wait_fd.fd = signal_fd;
wait_fd.events = CURL_WAIT_POLLIN;
wait_fd.revents = 0;
int ret = curl_multi_wait(handle, &wait_fd, 1, cct->_conf->rgw_curl_wait_timeout_ms, &num_fds);
if (ret) {
ldout(cct, 0) << "ERROR: curl_multi_wait() returned " << ret << dendl;
return -EIO;
}
if (wait_fd.revents > 0) {
ret = clear_signal(signal_fd);
if (ret < 0) {
ldout(cct, 0) << "ERROR: " << __func__ << "(): read() returned " << ret << dendl;
return ret;
}
}
return 0;
}
void *RGWHTTPManager::ReqsThread::entry()
{
manager->reqs_thread_entry();
return NULL;
}
/*
* RGWHTTPManager has two modes of operation: threaded and non-threaded.
*/
RGWHTTPManager::RGWHTTPManager(CephContext *_cct, RGWCompletionManager *_cm) : cct(_cct),
completion_mgr(_cm)
{
multi_handle = (void *)curl_multi_init();
thread_pipe[0] = -1;
thread_pipe[1] = -1;
}
RGWHTTPManager::~RGWHTTPManager() {
stop();
if (multi_handle)
curl_multi_cleanup((CURLM *)multi_handle);
}
void RGWHTTPManager::register_request(rgw_http_req_data *req_data)
{
std::unique_lock rl{reqs_lock};
req_data->id = num_reqs;
req_data->registered = true;
reqs[num_reqs] = req_data;
num_reqs++;
ldout(cct, 20) << __func__ << " mgr=" << this << " req_data->id=" << req_data->id << ", curl_handle=" << req_data->curl_handle << dendl;
}
bool RGWHTTPManager::unregister_request(rgw_http_req_data *req_data)
{
std::unique_lock rl{reqs_lock};
if (!req_data->registered) {
return false;
}
req_data->get();
req_data->registered = false;
unregistered_reqs.push_back(req_data);
ldout(cct, 20) << __func__ << " mgr=" << this << " req_data->id=" << req_data->id << ", curl_handle=" << req_data->curl_handle << dendl;
return true;
}
void RGWHTTPManager::complete_request(rgw_http_req_data *req_data)
{
std::unique_lock rl{reqs_lock};
_complete_request(req_data);
}
void RGWHTTPManager::_complete_request(rgw_http_req_data *req_data)
{
map<uint64_t, rgw_http_req_data *>::iterator iter = reqs.find(req_data->id);
if (iter != reqs.end()) {
reqs.erase(iter);
}
{
std::lock_guard l{req_data->lock};
req_data->mgr = nullptr;
}
if (completion_mgr) {
completion_mgr->complete(NULL, req_data->control_io_id, req_data->user_info);
}
req_data->put();
}
void RGWHTTPManager::finish_request(rgw_http_req_data *req_data, int ret, long http_status)
{
req_data->finish(ret, http_status);
complete_request(req_data);
}
void RGWHTTPManager::_finish_request(rgw_http_req_data *req_data, int ret)
{
req_data->finish(ret);
_complete_request(req_data);
}
void RGWHTTPManager::_set_req_state(set_state& ss)
{
ss.req->set_state(ss.bitmask);
}
/*
* hook request to the curl multi handle
*/
int RGWHTTPManager::link_request(rgw_http_req_data *req_data)
{
ldout(cct, 20) << __func__ << " req_data=" << req_data << " req_data->id=" << req_data->id << ", curl_handle=" << req_data->curl_handle << dendl;
CURLMcode mstatus = curl_multi_add_handle((CURLM *)multi_handle, req_data->get_easy_handle());
if (mstatus) {
dout(0) << "ERROR: failed on curl_multi_add_handle, status=" << mstatus << dendl;
return -EIO;
}
return 0;
}
/*
* unhook request from the curl multi handle, and finish request if it wasn't finished yet as
* there will be no more processing on this request
*/
void RGWHTTPManager::_unlink_request(rgw_http_req_data *req_data)
{
if (req_data->curl_handle) {
curl_multi_remove_handle((CURLM *)multi_handle, req_data->get_easy_handle());
}
if (!req_data->is_done()) {
_finish_request(req_data, -ECANCELED);
}
}
void RGWHTTPManager::unlink_request(rgw_http_req_data *req_data)
{
std::unique_lock wl{reqs_lock};
_unlink_request(req_data);
}
void RGWHTTPManager::manage_pending_requests()
{
reqs_lock.lock_shared();
if (max_threaded_req == num_reqs &&
unregistered_reqs.empty() &&
reqs_change_state.empty()) {
reqs_lock.unlock_shared();
return;
}
reqs_lock.unlock_shared();
std::unique_lock wl{reqs_lock};
if (!reqs_change_state.empty()) {
for (auto siter : reqs_change_state) {
_set_req_state(siter);
}
reqs_change_state.clear();
}
if (!unregistered_reqs.empty()) {
for (auto& r : unregistered_reqs) {
_unlink_request(r);
r->put();
}
unregistered_reqs.clear();
}
map<uint64_t, rgw_http_req_data *>::iterator iter = reqs.find(max_threaded_req);
list<std::pair<rgw_http_req_data *, int> > remove_reqs;
for (; iter != reqs.end(); ++iter) {
rgw_http_req_data *req_data = iter->second;
int r = link_request(req_data);
if (r < 0) {
ldout(cct, 0) << "ERROR: failed to link http request" << dendl;
remove_reqs.push_back(std::make_pair(iter->second, r));
} else {
max_threaded_req = iter->first + 1;
}
}
for (auto piter : remove_reqs) {
rgw_http_req_data *req_data = piter.first;
int r = piter.second;
_finish_request(req_data, r);
}
}
int RGWHTTPManager::add_request(RGWHTTPClient *client)
{
rgw_http_req_data *req_data = new rgw_http_req_data;
int ret = client->init_request(req_data);
if (ret < 0) {
req_data->put();
req_data = NULL;
return ret;
}
req_data->mgr = this;
req_data->client = client;
req_data->control_io_id = client->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_CONTROL);
req_data->user_info = client->get_io_user_info();
register_request(req_data);
if (!is_started) {
ret = link_request(req_data);
if (ret < 0) {
req_data->put();
req_data = NULL;
}
return ret;
}
ret = signal_thread();
if (ret < 0) {
finish_request(req_data, ret);
}
return ret;
}
int RGWHTTPManager::remove_request(RGWHTTPClient *client)
{
rgw_http_req_data *req_data = client->get_req_data();
if (!is_started) {
unlink_request(req_data);
return 0;
}
if (!unregister_request(req_data)) {
return 0;
}
int ret = signal_thread();
if (ret < 0) {
return ret;
}
return 0;
}
int RGWHTTPManager::set_request_state(RGWHTTPClient *client, RGWHTTPRequestSetState state)
{
rgw_http_req_data *req_data = client->get_req_data();
ceph_assert(ceph_mutex_is_locked(req_data->lock));
/* can only do that if threaded */
if (!is_started) {
return -EINVAL;
}
bool suggested_wr_paused = req_data->write_paused;
bool suggested_rd_paused = req_data->read_paused;
switch (state) {
case SET_WRITE_PAUSED:
suggested_wr_paused = true;
break;
case SET_WRITE_RESUME:
suggested_wr_paused = false;
break;
case SET_READ_PAUSED:
suggested_rd_paused = true;
break;
case SET_READ_RESUME:
suggested_rd_paused = false;
break;
default:
/* shouldn't really be here */
return -EIO;
}
if (suggested_wr_paused == req_data->write_paused &&
suggested_rd_paused == req_data->read_paused) {
return 0;
}
req_data->write_paused = suggested_wr_paused;
req_data->read_paused = suggested_rd_paused;
int bitmask = CURLPAUSE_CONT;
if (req_data->write_paused) {
bitmask |= CURLPAUSE_SEND;
}
if (req_data->read_paused) {
bitmask |= CURLPAUSE_RECV;
}
reqs_change_state.push_back(set_state(req_data, bitmask));
int ret = signal_thread();
if (ret < 0) {
return ret;
}
return 0;
}
int RGWHTTPManager::start()
{
if (pipe_cloexec(thread_pipe, 0) < 0) {
int e = errno;
ldout(cct, 0) << "ERROR: pipe(): " << cpp_strerror(e) << dendl;
return -e;
}
// enable non-blocking reads
if (::fcntl(thread_pipe[0], F_SETFL, O_NONBLOCK) < 0) {
int e = errno;
ldout(cct, 0) << "ERROR: fcntl(): " << cpp_strerror(e) << dendl;
TEMP_FAILURE_RETRY(::close(thread_pipe[0]));
TEMP_FAILURE_RETRY(::close(thread_pipe[1]));
return -e;
}
is_started = true;
reqs_thread = new ReqsThread(this);
reqs_thread->create("http_manager");
return 0;
}
void RGWHTTPManager::stop()
{
if (is_stopped) {
return;
}
is_stopped = true;
if (is_started) {
going_down = true;
signal_thread();
reqs_thread->join();
delete reqs_thread;
TEMP_FAILURE_RETRY(::close(thread_pipe[1]));
TEMP_FAILURE_RETRY(::close(thread_pipe[0]));
}
}
int RGWHTTPManager::signal_thread()
{
uint32_t buf = 0;
int ret = write(thread_pipe[1], (void *)&buf, sizeof(buf));
if (ret < 0) {
ret = -errno;
ldout(cct, 0) << "ERROR: " << __func__ << ": write() returned ret=" << ret << dendl;
return ret;
}
return 0;
}
void *RGWHTTPManager::reqs_thread_entry()
{
int still_running;
int mstatus;
ldout(cct, 20) << __func__ << ": start" << dendl;
while (!going_down) {
int ret = do_curl_wait(cct, (CURLM *)multi_handle, thread_pipe[0]);
if (ret < 0) {
dout(0) << "ERROR: do_curl_wait() returned: " << ret << dendl;
return NULL;
}
manage_pending_requests();
mstatus = curl_multi_perform((CURLM *)multi_handle, &still_running);
switch (mstatus) {
case CURLM_OK:
case CURLM_CALL_MULTI_PERFORM:
break;
default:
dout(10) << "curl_multi_perform returned: " << mstatus << dendl;
break;
}
int msgs_left;
CURLMsg *msg;
while ((msg = curl_multi_info_read((CURLM *)multi_handle, &msgs_left))) {
if (msg->msg == CURLMSG_DONE) {
int result = msg->data.result;
CURL *e = msg->easy_handle;
rgw_http_req_data *req_data;
curl_easy_getinfo(e, CURLINFO_PRIVATE, (void **)&req_data);
curl_multi_remove_handle((CURLM *)multi_handle, e);
long http_status;
int status;
if (!req_data->user_ret) {
curl_easy_getinfo(e, CURLINFO_RESPONSE_CODE, (void **)&http_status);
status = rgw_http_error_to_errno(http_status);
if (result != CURLE_OK && status == 0) {
dout(0) << "ERROR: curl error: " << curl_easy_strerror((CURLcode)result) << ", maybe network unstable" << dendl;
status = -EAGAIN;
}
} else {
status = *req_data->user_ret;
rgw_err err;
set_req_state_err(err, status, 0);
http_status = err.http_ret;
}
int id = req_data->id;
finish_request(req_data, status, http_status);
switch (result) {
case CURLE_OK:
break;
case CURLE_OPERATION_TIMEDOUT:
dout(0) << "WARNING: curl operation timed out, network average transfer speed less than "
<< cct->_conf->rgw_curl_low_speed_limit << " Bytes per second during " << cct->_conf->rgw_curl_low_speed_time << " seconds." << dendl;
default:
dout(20) << "ERROR: msg->data.result=" << result << " req_data->id=" << id << " http_status=" << http_status << dendl;
dout(20) << "ERROR: curl error: " << curl_easy_strerror((CURLcode)result) << " req_data->error_buf=" << req_data->error_buf << dendl;
break;
}
}
}
}
std::unique_lock rl{reqs_lock};
for (auto r : unregistered_reqs) {
_unlink_request(r);
}
unregistered_reqs.clear();
auto all_reqs = std::move(reqs);
for (auto iter : all_reqs) {
_unlink_request(iter.second);
}
reqs.clear();
if (completion_mgr) {
completion_mgr->go_down();
}
return 0;
}
void rgw_http_client_init(CephContext *cct)
{
curl_global_init(CURL_GLOBAL_ALL);
rgw_http_manager = new RGWHTTPManager(cct);
rgw_http_manager->start();
}
void rgw_http_client_cleanup()
{
rgw_http_manager->stop();
delete rgw_http_manager;
curl_global_cleanup();
}
int RGWHTTP::send(RGWHTTPClient *req) {
if (!req) {
return 0;
}
int r = rgw_http_manager->add_request(req);
if (r < 0) {
return r;
}
return 0;
}
int RGWHTTP::process(RGWHTTPClient *req, optional_yield y) {
if (!req) {
return 0;
}
int r = send(req);
if (r < 0) {
return r;
}
return req->wait(y);
}
| 30,536 | 23.948529 | 148 |
cc
|
null |
ceph-main/src/rgw/rgw_http_client.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "common/async/yield_context.h"
#include "common/Cond.h"
#include "rgw_common.h"
#include "rgw_string.h"
#include "rgw_http_client_types.h"
#include <atomic>
using param_pair_t = std::pair<std::string, std::string>;
using param_vec_t = std::vector<param_pair_t>;
void rgw_http_client_init(CephContext *cct);
void rgw_http_client_cleanup();
struct rgw_http_req_data;
class RGWHTTPManager;
class RGWHTTPClient : public RGWIOProvider,
public NoDoutPrefix
{
friend class RGWHTTPManager;
bufferlist send_bl;
bufferlist::iterator send_iter;
bool has_send_len;
long http_status;
bool send_data_hint{false};
size_t receive_pause_skip{0}; /* how many bytes to skip next time receive_data is called
due to being paused */
void *user_info{nullptr};
rgw_http_req_data *req_data;
bool verify_ssl; // Do not validate self signed certificates, default to false
std::string ca_path;
std::string client_cert;
std::string client_key;
std::atomic<unsigned> stopped { 0 };
protected:
CephContext *cct;
std::string method;
std::string url;
std::string protocol;
std::string host;
std::string resource_prefix;
size_t send_len{0};
param_vec_t headers;
long req_timeout{0L};
void init();
RGWHTTPManager *get_manager();
int init_request(rgw_http_req_data *req_data);
virtual int receive_header(void *ptr, size_t len) {
return 0;
}
virtual int receive_data(void *ptr, size_t len, bool *pause) {
return 0;
}
virtual int send_data(void *ptr, size_t len, bool *pause=nullptr) {
return 0;
}
/* Callbacks for libcurl. */
static size_t receive_http_header(void *ptr,
size_t size,
size_t nmemb,
void *_info);
static size_t receive_http_data(void *ptr,
size_t size,
size_t nmemb,
void *_info);
static size_t send_http_data(void *ptr,
size_t size,
size_t nmemb,
void *_info);
ceph::mutex& get_req_lock();
/* needs to be called under req_lock() */
void _set_write_paused(bool pause);
void _set_read_paused(bool pause);
public:
static const long HTTP_STATUS_NOSTATUS = 0;
static const long HTTP_STATUS_UNAUTHORIZED = 401;
static const long HTTP_STATUS_NOTFOUND = 404;
static constexpr int HTTPCLIENT_IO_READ = 0x1;
static constexpr int HTTPCLIENT_IO_WRITE = 0x2;
static constexpr int HTTPCLIENT_IO_CONTROL = 0x4;
virtual ~RGWHTTPClient();
explicit RGWHTTPClient(CephContext *cct,
const std::string& _method,
const std::string& _url);
std::ostream& gen_prefix(std::ostream& out) const override;
void append_header(const std::string& name, const std::string& val) {
headers.push_back(std::pair<std::string, std::string>(name, val));
}
void set_send_length(size_t len) {
send_len = len;
has_send_len = true;
}
void set_send_data_hint(bool hint) {
send_data_hint = hint;
}
long get_http_status() const {
return http_status;
}
void set_http_status(long _http_status) {
http_status = _http_status;
}
void set_verify_ssl(bool flag) {
verify_ssl = flag;
}
// set request timeout in seconds
// zero (default) mean that request will never timeout
void set_req_timeout(long timeout) {
req_timeout = timeout;
}
int process(optional_yield y);
int wait(optional_yield y);
void cancel();
bool is_done();
rgw_http_req_data *get_req_data() { return req_data; }
std::string to_str();
int get_req_retcode();
void set_url(const std::string& _url) {
url = _url;
}
void set_method(const std::string& _method) {
method = _method;
}
void set_io_user_info(void *_user_info) override {
user_info = _user_info;
}
void *get_io_user_info() override {
return user_info;
}
void set_ca_path(const std::string& _ca_path) {
ca_path = _ca_path;
}
void set_client_cert(const std::string& _client_cert) {
client_cert = _client_cert;
}
void set_client_key(const std::string& _client_key) {
client_key = _client_key;
}
};
class RGWHTTPHeadersCollector : public RGWHTTPClient {
public:
typedef std::string header_name_t;
typedef std::string header_value_t;
typedef std::set<header_name_t, ltstr_nocase> header_spec_t;
RGWHTTPHeadersCollector(CephContext * const cct,
const std::string& method,
const std::string& url,
const header_spec_t &relevant_headers)
: RGWHTTPClient(cct, method, url),
relevant_headers(relevant_headers) {
}
std::map<header_name_t, header_value_t, ltstr_nocase> get_headers() const {
return found_headers;
}
/* Throws std::out_of_range */
const header_value_t& get_header_value(const header_name_t& name) const {
return found_headers.at(name);
}
protected:
int receive_header(void *ptr, size_t len) override;
private:
const std::set<header_name_t, ltstr_nocase> relevant_headers;
std::map<header_name_t, header_value_t, ltstr_nocase> found_headers;
};
class RGWHTTPTransceiver : public RGWHTTPHeadersCollector {
bufferlist * const read_bl;
std::string post_data;
size_t post_data_index;
public:
RGWHTTPTransceiver(CephContext * const cct,
const std::string& method,
const std::string& url,
bufferlist * const read_bl,
const header_spec_t intercept_headers = {})
: RGWHTTPHeadersCollector(cct, method, url, intercept_headers),
read_bl(read_bl),
post_data_index(0) {
}
RGWHTTPTransceiver(CephContext * const cct,
const std::string& method,
const std::string& url,
bufferlist * const read_bl,
const bool verify_ssl,
const header_spec_t intercept_headers = {})
: RGWHTTPHeadersCollector(cct, method, url, intercept_headers),
read_bl(read_bl),
post_data_index(0) {
set_verify_ssl(verify_ssl);
}
void set_post_data(const std::string& _post_data) {
this->post_data = _post_data;
}
protected:
int send_data(void* ptr, size_t len, bool *pause=nullptr) override;
int receive_data(void *ptr, size_t len, bool *pause) override {
read_bl->append((char *)ptr, len);
return 0;
}
};
typedef RGWHTTPTransceiver RGWPostHTTPData;
class RGWCompletionManager;
enum RGWHTTPRequestSetState {
SET_NOP = 0,
SET_WRITE_PAUSED = 1,
SET_WRITE_RESUME = 2,
SET_READ_PAUSED = 3,
SET_READ_RESUME = 4,
};
class RGWHTTPManager {
struct set_state {
rgw_http_req_data *req;
int bitmask;
set_state(rgw_http_req_data *_req, int _bitmask) : req(_req), bitmask(_bitmask) {}
};
CephContext *cct;
RGWCompletionManager *completion_mgr;
void *multi_handle;
bool is_started = false;
std::atomic<unsigned> going_down { 0 };
std::atomic<unsigned> is_stopped { 0 };
ceph::shared_mutex reqs_lock = ceph::make_shared_mutex("RGWHTTPManager::reqs_lock");
std::map<uint64_t, rgw_http_req_data *> reqs;
std::list<rgw_http_req_data *> unregistered_reqs;
std::list<set_state> reqs_change_state;
std::map<uint64_t, rgw_http_req_data *> complete_reqs;
int64_t num_reqs = 0;
int64_t max_threaded_req = 0;
int thread_pipe[2];
void register_request(rgw_http_req_data *req_data);
void complete_request(rgw_http_req_data *req_data);
void _complete_request(rgw_http_req_data *req_data);
bool unregister_request(rgw_http_req_data *req_data);
void _unlink_request(rgw_http_req_data *req_data);
void unlink_request(rgw_http_req_data *req_data);
void finish_request(rgw_http_req_data *req_data, int r, long http_status = -1);
void _finish_request(rgw_http_req_data *req_data, int r);
void _set_req_state(set_state& ss);
int link_request(rgw_http_req_data *req_data);
void manage_pending_requests();
class ReqsThread : public Thread {
RGWHTTPManager *manager;
public:
explicit ReqsThread(RGWHTTPManager *_m) : manager(_m) {}
void *entry() override;
};
ReqsThread *reqs_thread = nullptr;
void *reqs_thread_entry();
int signal_thread();
public:
RGWHTTPManager(CephContext *_cct, RGWCompletionManager *completion_mgr = NULL);
~RGWHTTPManager();
int start();
void stop();
int add_request(RGWHTTPClient *client);
int remove_request(RGWHTTPClient *client);
int set_request_state(RGWHTTPClient *client, RGWHTTPRequestSetState state);
};
class RGWHTTP
{
public:
static int send(RGWHTTPClient *req);
static int process(RGWHTTPClient *req, optional_yield y);
};
| 9,012 | 24.825215 | 90 |
h
|
null |
ceph-main/src/rgw/rgw_http_client_curl.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_http_client_curl.h"
#include <mutex>
#include <vector>
#include <curl/curl.h>
#include "rgw_common.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
#ifdef WITH_CURL_OPENSSL
#include <openssl/crypto.h>
#endif
#if defined(WITH_CURL_OPENSSL) && OPENSSL_API_COMPAT < 0x10100000L
namespace openssl {
class RGWSSLSetup
{
std::vector <std::mutex> locks;
public:
explicit RGWSSLSetup(int n) : locks (n){}
void set_lock(int id){
try {
locks.at(id).lock();
} catch (std::out_of_range& e) {
dout(0) << __func__ << " failed to set locks" << dendl;
}
}
void clear_lock(int id){
try {
locks.at(id).unlock();
} catch (std::out_of_range& e) {
dout(0) << __func__ << " failed to unlock" << dendl;
}
}
};
void rgw_ssl_locking_callback(int mode, int id, const char *file, int line)
{
static RGWSSLSetup locks(CRYPTO_num_locks());
if (mode & CRYPTO_LOCK)
locks.set_lock(id);
else
locks.clear_lock(id);
}
unsigned long rgw_ssl_thread_id_callback(){
return (unsigned long)pthread_self();
}
void init_ssl(){
CRYPTO_set_id_callback((unsigned long (*) ()) rgw_ssl_thread_id_callback);
CRYPTO_set_locking_callback(rgw_ssl_locking_callback);
}
} /* namespace openssl */
#endif // WITH_CURL_OPENSSL
namespace rgw {
namespace curl {
#if defined(WITH_CURL_OPENSSL) && OPENSSL_API_COMPAT < 0x10100000L
void init_ssl() {
::openssl::init_ssl();
}
bool fe_inits_ssl(boost::optional <const fe_map_t&> m, long& curl_global_flags){
if (m) {
for (const auto& kv: *m){
if (kv.first == "beast"){
std::string cert;
kv.second->get_val("ssl_certificate","", &cert);
if (!cert.empty()){
/* TODO this flag is no op for curl > 7.57 */
curl_global_flags &= ~CURL_GLOBAL_SSL;
return true;
}
}
}
}
return false;
}
#endif // WITH_CURL_OPENSSL
std::once_flag curl_init_flag;
void setup_curl(boost::optional<const fe_map_t&> m) {
long curl_global_flags = CURL_GLOBAL_ALL;
#if defined(WITH_CURL_OPENSSL) && OPENSSL_API_COMPAT < 0x10100000L
if (!fe_inits_ssl(m, curl_global_flags))
init_ssl();
#endif
std::call_once(curl_init_flag, curl_global_init, curl_global_flags);
rgw_setup_saved_curl_handles();
}
void cleanup_curl() {
rgw_release_all_curl_handles();
curl_global_cleanup();
}
} /* namespace curl */
} /* namespace rgw */
| 2,530 | 21.39823 | 80 |
cc
|
null |
ceph-main/src/rgw/rgw_http_client_curl.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 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.
*
*/
#pragma once
#include <map>
#include <boost/optional.hpp>
#include "rgw_frontend.h"
namespace rgw {
namespace curl {
using fe_map_t = std::multimap <std::string, RGWFrontendConfig *>;
void setup_curl(boost::optional<const fe_map_t&> m);
void cleanup_curl();
}
}
| 680 | 21.7 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_http_client_types.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <atomic>
struct rgw_io_id {
int64_t id{0};
int channels{0};
rgw_io_id() {}
rgw_io_id(int64_t _id, int _channels) : id(_id), channels(_channels) {}
bool intersects(const rgw_io_id& rhs) {
return (id == rhs.id && ((channels | rhs.channels) != 0));
}
bool operator<(const rgw_io_id& rhs) const {
if (id < rhs.id) {
return true;
}
return (id == rhs.id &&
channels < rhs.channels);
}
};
class RGWIOIDProvider
{
std::atomic<int64_t> max = {0};
public:
RGWIOIDProvider() {}
int64_t get_next() {
return ++max;
}
};
class RGWIOProvider
{
int64_t id{-1};
public:
RGWIOProvider() {}
virtual ~RGWIOProvider() = default;
void assign_io(RGWIOIDProvider& io_id_provider, int io_type = -1);
rgw_io_id get_io_id(int io_type) {
return rgw_io_id{id, io_type};
}
virtual void set_io_user_info(void *_user_info) = 0;
virtual void *get_io_user_info() = 0;
};
| 1,367 | 18.542857 | 73 |
h
|
null |
ceph-main/src/rgw/rgw_http_errors.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "rgw_common.h"
typedef const std::map<int,const std::pair<int, const char*>> rgw_http_errors;
extern rgw_http_errors rgw_http_s3_errors;
extern rgw_http_errors rgw_http_swift_errors;
extern rgw_http_errors rgw_http_sts_errors;
extern rgw_http_errors rgw_http_iam_errors;
static inline int rgw_http_error_to_errno(int http_err)
{
if (http_err >= 200 && http_err <= 299)
return 0;
switch (http_err) {
case 304:
return -ERR_NOT_MODIFIED;
case 400:
return -EINVAL;
case 401:
return -EPERM;
case 403:
return -EACCES;
case 404:
return -ENOENT;
case 405:
return -ERR_METHOD_NOT_ALLOWED;
case 409:
return -ENOTEMPTY;
case 503:
return -EBUSY;
default:
return -EIO;
}
return 0; /* unreachable */
}
| 938 | 19.866667 | 78 |
h
|
null |
ceph-main/src/rgw/rgw_iam_policy.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <cstring>
#include <iostream>
#include <regex>
#include <sstream>
#include <stack>
#include <utility>
#include <arpa/inet.h>
#include <experimental/iterator>
#include "rapidjson/reader.h"
#include "include/expected.hpp"
#include "rgw_auth.h"
#include "rgw_iam_policy.h"
namespace {
constexpr int dout_subsys = ceph_subsys_rgw;
}
using std::dec;
using std::hex;
using std::int64_t;
using std::size_t;
using std::string;
using std::stringstream;
using std::ostream;
using std::uint16_t;
using std::uint64_t;
using boost::container::flat_set;
using std::regex;
using std::regex_match;
using std::smatch;
using rapidjson::BaseReaderHandler;
using rapidjson::UTF8;
using rapidjson::SizeType;
using rapidjson::Reader;
using rapidjson::kParseCommentsFlag;
using rapidjson::kParseNumbersAsStringsFlag;
using rapidjson::StringStream;
using rgw::auth::Principal;
namespace rgw {
namespace IAM {
#include "rgw_iam_policy_keywords.frag.cc"
struct actpair {
const char* name;
const uint64_t bit;
};
static const actpair actpairs[] =
{{ "s3:AbortMultipartUpload", s3AbortMultipartUpload },
{ "s3:CreateBucket", s3CreateBucket },
{ "s3:DeleteBucketPolicy", s3DeleteBucketPolicy },
{ "s3:DeleteBucket", s3DeleteBucket },
{ "s3:DeleteBucketWebsite", s3DeleteBucketWebsite },
{ "s3:DeleteObject", s3DeleteObject },
{ "s3:DeleteObjectVersion", s3DeleteObjectVersion },
{ "s3:DeleteObjectTagging", s3DeleteObjectTagging },
{ "s3:DeleteObjectVersionTagging", s3DeleteObjectVersionTagging },
{ "s3:DeleteBucketPublicAccessBlock", s3DeleteBucketPublicAccessBlock},
{ "s3:DeletePublicAccessBlock", s3DeletePublicAccessBlock},
{ "s3:DeleteReplicationConfiguration", s3DeleteReplicationConfiguration },
{ "s3:GetAccelerateConfiguration", s3GetAccelerateConfiguration },
{ "s3:GetBucketAcl", s3GetBucketAcl },
{ "s3:GetBucketCORS", s3GetBucketCORS },
{ "s3:GetBucketEncryption", s3GetBucketEncryption },
{ "s3:GetBucketLocation", s3GetBucketLocation },
{ "s3:GetBucketLogging", s3GetBucketLogging },
{ "s3:GetBucketNotification", s3GetBucketNotification },
{ "s3:GetBucketPolicy", s3GetBucketPolicy },
{ "s3:GetBucketPolicyStatus", s3GetBucketPolicyStatus },
{ "s3:GetBucketPublicAccessBlock", s3GetBucketPublicAccessBlock },
{ "s3:GetBucketRequestPayment", s3GetBucketRequestPayment },
{ "s3:GetBucketTagging", s3GetBucketTagging },
{ "s3:GetBucketVersioning", s3GetBucketVersioning },
{ "s3:GetBucketWebsite", s3GetBucketWebsite },
{ "s3:GetLifecycleConfiguration", s3GetLifecycleConfiguration },
{ "s3:GetBucketObjectLockConfiguration", s3GetBucketObjectLockConfiguration },
{ "s3:GetPublicAccessBlock", s3GetPublicAccessBlock },
{ "s3:GetObjectAcl", s3GetObjectAcl },
{ "s3:GetObject", s3GetObject },
{ "s3:GetObjectTorrent", s3GetObjectTorrent },
{ "s3:GetObjectVersionAcl", s3GetObjectVersionAcl },
{ "s3:GetObjectVersion", s3GetObjectVersion },
{ "s3:GetObjectVersionTorrent", s3GetObjectVersionTorrent },
{ "s3:GetObjectTagging", s3GetObjectTagging },
{ "s3:GetObjectVersionTagging", s3GetObjectVersionTagging},
{ "s3:GetObjectRetention", s3GetObjectRetention},
{ "s3:GetObjectLegalHold", s3GetObjectLegalHold},
{ "s3:GetReplicationConfiguration", s3GetReplicationConfiguration },
{ "s3:ListAllMyBuckets", s3ListAllMyBuckets },
{ "s3:ListBucketMultipartUploads", s3ListBucketMultipartUploads },
{ "s3:ListBucket", s3ListBucket },
{ "s3:ListBucketVersions", s3ListBucketVersions },
{ "s3:ListMultipartUploadParts", s3ListMultipartUploadParts },
{ "s3:PutAccelerateConfiguration", s3PutAccelerateConfiguration },
{ "s3:PutBucketAcl", s3PutBucketAcl },
{ "s3:PutBucketCORS", s3PutBucketCORS },
{ "s3:PutBucketEncryption", s3PutBucketEncryption },
{ "s3:PutBucketLogging", s3PutBucketLogging },
{ "s3:PutBucketNotification", s3PutBucketNotification },
{ "s3:PutBucketPolicy", s3PutBucketPolicy },
{ "s3:PutBucketRequestPayment", s3PutBucketRequestPayment },
{ "s3:PutBucketTagging", s3PutBucketTagging },
{ "s3:PutBucketVersioning", s3PutBucketVersioning },
{ "s3:PutBucketWebsite", s3PutBucketWebsite },
{ "s3:PutLifecycleConfiguration", s3PutLifecycleConfiguration },
{ "s3:PutBucketObjectLockConfiguration", s3PutBucketObjectLockConfiguration },
{ "s3:PutObjectAcl", s3PutObjectAcl },
{ "s3:PutObject", s3PutObject },
{ "s3:PutObjectVersionAcl", s3PutObjectVersionAcl },
{ "s3:PutObjectTagging", s3PutObjectTagging },
{ "s3:PutObjectVersionTagging", s3PutObjectVersionTagging },
{ "s3:PutObjectRetention", s3PutObjectRetention },
{ "s3:PutObjectLegalHold", s3PutObjectLegalHold },
{ "s3:BypassGovernanceRetention", s3BypassGovernanceRetention },
{ "s3:PutBucketPublicAccessBlock", s3PutBucketPublicAccessBlock },
{ "s3:PutPublicAccessBlock", s3PutPublicAccessBlock },
{ "s3:PutReplicationConfiguration", s3PutReplicationConfiguration },
{ "s3:RestoreObject", s3RestoreObject },
{ "iam:PutUserPolicy", iamPutUserPolicy },
{ "iam:GetUserPolicy", iamGetUserPolicy },
{ "iam:DeleteUserPolicy", iamDeleteUserPolicy },
{ "iam:ListUserPolicies", iamListUserPolicies },
{ "iam:CreateRole", iamCreateRole},
{ "iam:DeleteRole", iamDeleteRole},
{ "iam:GetRole", iamGetRole},
{ "iam:ModifyRoleTrustPolicy", iamModifyRoleTrustPolicy},
{ "iam:ListRoles", iamListRoles},
{ "iam:PutRolePolicy", iamPutRolePolicy},
{ "iam:GetRolePolicy", iamGetRolePolicy},
{ "iam:ListRolePolicies", iamListRolePolicies},
{ "iam:DeleteRolePolicy", iamDeleteRolePolicy},
{ "iam:CreateOIDCProvider", iamCreateOIDCProvider},
{ "iam:DeleteOIDCProvider", iamDeleteOIDCProvider},
{ "iam:GetOIDCProvider", iamGetOIDCProvider},
{ "iam:ListOIDCProviders", iamListOIDCProviders},
{ "iam:TagRole", iamTagRole},
{ "iam:ListRoleTags", iamListRoleTags},
{ "iam:UntagRole", iamUntagRole},
{ "iam:UpdateRole", iamUpdateRole},
{ "sts:AssumeRole", stsAssumeRole},
{ "sts:AssumeRoleWithWebIdentity", stsAssumeRoleWithWebIdentity},
{ "sts:GetSessionToken", stsGetSessionToken},
{ "sts:TagSession", stsTagSession},
};
struct PolicyParser;
const Keyword top[1]{{"<Top>", TokenKind::pseudo, TokenID::Top, 0, false,
false}};
const Keyword cond_key[1]{{"<Condition Key>", TokenKind::cond_key,
TokenID::CondKey, 0, true, false}};
struct ParseState {
PolicyParser* pp;
const Keyword* w;
bool arraying = false;
bool objecting = false;
bool cond_ifexists = false;
void reset();
void annotate(std::string&& a);
boost::optional<Principal> parse_principal(string&& s, string* errmsg);
ParseState(PolicyParser* pp, const Keyword* w)
: pp(pp), w(w) {}
bool obj_start();
bool obj_end();
bool array_start() {
if (w->arrayable && !arraying) {
arraying = true;
return true;
}
annotate(fmt::format("`{}` does not take array.",
w->name));
return false;
}
bool array_end();
bool key(const char* s, size_t l);
bool do_string(CephContext* cct, const char* s, size_t l);
bool number(const char* str, size_t l);
};
// If this confuses you, look up the Curiously Recurring Template Pattern
struct PolicyParser : public BaseReaderHandler<UTF8<>, PolicyParser> {
keyword_hash tokens;
std::vector<ParseState> s;
CephContext* cct;
const string& tenant;
Policy& policy;
uint32_t v = 0;
const bool reject_invalid_principals;
uint32_t seen = 0;
std::string annotation{"No error?"};
uint32_t dex(TokenID in) const {
switch (in) {
case TokenID::Version:
return 0x1;
case TokenID::Id:
return 0x2;
case TokenID::Statement:
return 0x4;
case TokenID::Sid:
return 0x8;
case TokenID::Effect:
return 0x10;
case TokenID::Principal:
return 0x20;
case TokenID::NotPrincipal:
return 0x40;
case TokenID::Action:
return 0x80;
case TokenID::NotAction:
return 0x100;
case TokenID::Resource:
return 0x200;
case TokenID::NotResource:
return 0x400;
case TokenID::Condition:
return 0x800;
case TokenID::AWS:
return 0x1000;
case TokenID::Federated:
return 0x2000;
case TokenID::Service:
return 0x4000;
case TokenID::CanonicalUser:
return 0x8000;
default:
ceph_abort();
}
}
bool test(TokenID in) {
return seen & dex(in);
}
void set(TokenID in) {
seen |= dex(in);
if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) |
dex(TokenID::Principal) | dex(TokenID::NotPrincipal) |
dex(TokenID::Action) | dex(TokenID::NotAction) |
dex(TokenID::Resource) | dex(TokenID::NotResource) |
dex(TokenID::Condition) | dex(TokenID::AWS) |
dex(TokenID::Federated) | dex(TokenID::Service) |
dex(TokenID::CanonicalUser))) {
v |= dex(in);
}
}
void set(std::initializer_list<TokenID> l) {
for (auto in : l) {
seen |= dex(in);
if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) |
dex(TokenID::Principal) | dex(TokenID::NotPrincipal) |
dex(TokenID::Action) | dex(TokenID::NotAction) |
dex(TokenID::Resource) | dex(TokenID::NotResource) |
dex(TokenID::Condition) | dex(TokenID::AWS) |
dex(TokenID::Federated) | dex(TokenID::Service) |
dex(TokenID::CanonicalUser))) {
v |= dex(in);
}
}
}
void reset(TokenID in) {
seen &= ~dex(in);
if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) |
dex(TokenID::Principal) | dex(TokenID::NotPrincipal) |
dex(TokenID::Action) | dex(TokenID::NotAction) |
dex(TokenID::Resource) | dex(TokenID::NotResource) |
dex(TokenID::Condition) | dex(TokenID::AWS) |
dex(TokenID::Federated) | dex(TokenID::Service) |
dex(TokenID::CanonicalUser))) {
v &= ~dex(in);
}
}
void reset(std::initializer_list<TokenID> l) {
for (auto in : l) {
seen &= ~dex(in);
if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) |
dex(TokenID::Principal) | dex(TokenID::NotPrincipal) |
dex(TokenID::Action) | dex(TokenID::NotAction) |
dex(TokenID::Resource) | dex(TokenID::NotResource) |
dex(TokenID::Condition) | dex(TokenID::AWS) |
dex(TokenID::Federated) | dex(TokenID::Service) |
dex(TokenID::CanonicalUser))) {
v &= ~dex(in);
}
}
}
void reset(uint32_t& v) {
seen &= ~v;
v = 0;
}
PolicyParser(CephContext* cct, const string& tenant, Policy& policy,
bool reject_invalid_principals)
: cct(cct), tenant(tenant), policy(policy),
reject_invalid_principals(reject_invalid_principals) {}
PolicyParser(const PolicyParser& policy) = delete;
bool StartObject() {
if (s.empty()) {
s.push_back({this, top});
s.back().objecting = true;
return true;
}
return s.back().obj_start();
}
bool EndObject(SizeType memberCount) {
if (s.empty()) {
annotation = "Attempt to end unopened object at top level.";
return false;
}
return s.back().obj_end();
}
bool Key(const char* str, SizeType length, bool copy) {
if (s.empty()) {
annotation = "Key not allowed at top level.";
return false;
}
return s.back().key(str, length);
}
bool String(const char* str, SizeType length, bool copy) {
if (s.empty()) {
annotation = "String not allowed at top level.";
return false;
}
return s.back().do_string(cct, str, length);
}
bool RawNumber(const char* str, SizeType length, bool copy) {
if (s.empty()) {
annotation = "Number not allowed at top level.";
return false;
}
return s.back().number(str, length);
}
bool StartArray() {
if (s.empty()) {
annotation = "Array not allowed at top level.";
return false;
}
return s.back().array_start();
}
bool EndArray(SizeType) {
if (s.empty()) {
return false;
}
return s.back().array_end();
}
bool Default() {
return false;
}
};
// I really despise this misfeature of C++.
//
void ParseState::annotate(std::string&& a) {
pp->annotation = std::move(a);
}
bool ParseState::obj_end() {
if (objecting) {
objecting = false;
if (!arraying) {
pp->s.pop_back();
} else {
reset();
}
return true;
}
annotate(
fmt::format("Attempt to end unopened object on keyword `{}`.",
w->name));
return false;
}
bool ParseState::key(const char* s, size_t l) {
auto token_len = l;
bool ifexists = false;
if (w->id == TokenID::Condition && w->kind == TokenKind::statement) {
static constexpr char IfExists[] = "IfExists";
if (boost::algorithm::ends_with(std::string_view{s, l}, IfExists)) {
ifexists = true;
token_len -= sizeof(IfExists)-1;
}
}
auto k = pp->tokens.lookup(s, token_len);
if (!k) {
if (w->kind == TokenKind::cond_op) {
auto id = w->id;
auto& t = pp->policy.statements.back();
auto c_ife = cond_ifexists;
pp->s.emplace_back(pp, cond_key);
t.conditions.emplace_back(id, s, l, c_ife);
return true;
} else {
annotate(fmt::format("Unknown key `{}`.", std::string_view{s, token_len}));
return false;
}
}
// If the token we're going with belongs within the condition at the
// top of the stack and we haven't already encountered it, push it
// on the stack
// Top
if ((((w->id == TokenID::Top) && (k->kind == TokenKind::top)) ||
// Statement
((w->id == TokenID::Statement) && (k->kind == TokenKind::statement)) ||
/// Principal
((w->id == TokenID::Principal || w->id == TokenID::NotPrincipal) &&
(k->kind == TokenKind::princ_type))) &&
// Check that it hasn't been encountered. Note that this
// conjoins with the run of disjunctions above.
!pp->test(k->id)) {
pp->set(k->id);
pp->s.emplace_back(pp, k);
return true;
} else if ((w->id == TokenID::Condition) &&
(k->kind == TokenKind::cond_op)) {
pp->s.emplace_back(pp, k);
pp->s.back().cond_ifexists = ifexists;
return true;
}
annotate(fmt::format("Token `{}` is not allowed in the context of `{}`.",
k->name, w->name));
return false;
}
// I should just rewrite a few helper functions to use iterators,
// which will make all of this ever so much nicer.
boost::optional<Principal> ParseState::parse_principal(string&& s,
string* errmsg) {
if ((w->id == TokenID::AWS) && (s == "*")) {
// Wildcard!
return Principal::wildcard();
} else if (w->id == TokenID::CanonicalUser) {
// Do nothing for now.
if (errmsg)
*errmsg = "RGW does not support canonical users.";
return boost::none;
} else if (w->id == TokenID::AWS || w->id == TokenID::Federated) {
// AWS and Federated ARNs
if (auto a = ARN::parse(s)) {
if (a->resource == "root") {
return Principal::tenant(std::move(a->account));
}
static const char rx_str[] = "([^/]*)/(.*)";
static const regex rx(rx_str, sizeof(rx_str) - 1,
std::regex_constants::ECMAScript |
std::regex_constants::optimize);
smatch match;
if (regex_match(a->resource, match, rx) && match.size() == 3) {
if (match[1] == "user") {
return Principal::user(std::move(a->account),
match[2]);
}
if (match[1] == "role") {
return Principal::role(std::move(a->account),
match[2]);
}
if (match[1] == "oidc-provider") {
return Principal::oidc_provider(std::move(match[2]));
}
if (match[1] == "assumed-role") {
return Principal::assumed_role(std::move(a->account), match[2]);
}
}
} else if (std::none_of(s.begin(), s.end(),
[](const char& c) {
return (c == ':') || (c == '/');
})) {
// Since tenants are simply prefixes, there's no really good
// way to see if one exists or not. So we return the thing and
// let them try to match against it.
return Principal::tenant(std::move(s));
}
if (errmsg)
*errmsg =
fmt::format(
"`{}` is not a supported AWS or Federated ARN. Supported ARNs are "
"forms like: "
"`arn:aws:iam::tenant:root` or a bare tenant name for a tenant, "
"`arn:aws:iam::tenant:role/role-name` for a role, "
"`arn:aws:sts::tenant:assumed-role/role-name/role-session-name` "
"for an assumed role, "
"`arn:aws:iam::tenant:user/user-name` for a user, "
"`arn:aws:iam::tenant:oidc-provider/idp-url` for OIDC.", s);
}
if (errmsg)
*errmsg = fmt::format("RGW does not support principals of type `{}`.",
w->name);
return boost::none;
}
bool ParseState::do_string(CephContext* cct, const char* s, size_t l) {
auto k = pp->tokens.lookup(s, l);
Policy& p = pp->policy;
bool is_action = false;
bool is_validaction = false;
Statement* t = p.statements.empty() ? nullptr : &(p.statements.back());
// Top level!
if (w->id == TokenID::Version) {
if (k && k->kind == TokenKind::version_key) {
p.version = static_cast<Version>(k->specific);
} else {
annotate(
fmt::format("`{}` is not a valid version. Valid versions are "
"`2008-10-17` and `2012-10-17`.",
std::string_view{s, l}));
return false;
}
} else if (w->id == TokenID::Id) {
p.id = string(s, l);
// Statement
} else if (w->id == TokenID::Sid) {
t->sid.emplace(s, l);
} else if (w->id == TokenID::Effect) {
if (k && k->kind == TokenKind::effect_key) {
t->effect = static_cast<Effect>(k->specific);
} else {
annotate(fmt::format("`{}` is not a valid effect.",
std::string_view{s, l}));
return false;
}
} else if (w->id == TokenID::Principal && s && *s == '*') {
t->princ.emplace(Principal::wildcard());
} else if (w->id == TokenID::NotPrincipal && s && *s == '*') {
t->noprinc.emplace(Principal::wildcard());
} else if ((w->id == TokenID::Action) ||
(w->id == TokenID::NotAction)) {
is_action = true;
if (*s == '*') {
is_validaction = true;
(w->id == TokenID::Action ?
t->action = allValue : t->notaction = allValue);
} else {
for (auto& p : actpairs) {
if (match_policy({s, l}, p.name, MATCH_POLICY_ACTION)) {
is_validaction = true;
(w->id == TokenID::Action ? t->action[p.bit] = 1 : t->notaction[p.bit] = 1);
}
if ((t->action & s3AllValue) == s3AllValue) {
t->action[s3All] = 1;
}
if ((t->notaction & s3AllValue) == s3AllValue) {
t->notaction[s3All] = 1;
}
if ((t->action & iamAllValue) == iamAllValue) {
t->action[iamAll] = 1;
}
if ((t->notaction & iamAllValue) == iamAllValue) {
t->notaction[iamAll] = 1;
}
if ((t->action & stsAllValue) == stsAllValue) {
t->action[stsAll] = 1;
}
if ((t->notaction & stsAllValue) == stsAllValue) {
t->notaction[stsAll] = 1;
}
}
}
} else if (w->id == TokenID::Resource || w->id == TokenID::NotResource) {
auto a = ARN::parse({s, l}, true);
if (!a) {
annotate(
fmt::format("`{}` is not a valid ARN. Resource ARNs should have a "
"format like `arn:aws:s3::tenant:resource' or "
"`arn:aws:s3:::resource`.",
std::string_view{s, l}));
return false;
}
// You can't specify resources for someone ELSE'S account.
if (a->account.empty() || a->account == pp->tenant ||
a->account == "*") {
if (a->account.empty() || a->account == "*")
a->account = pp->tenant;
(w->id == TokenID::Resource ? t->resource : t->notresource)
.emplace(std::move(*a));
} else {
annotate(fmt::format("Policy owned by tenant `{}` cannot grant access to "
"resource owned by tenant `{}`.",
pp->tenant, a->account));
return false;
}
} else if (w->kind == TokenKind::cond_key) {
auto& t = pp->policy.statements.back();
if (l > 0 && *s == '$') {
if (l >= 2 && *(s+1) == '{') {
if (l > 0 && *(s+l-1) == '}') {
t.conditions.back().isruntime = true;
} else {
annotate(fmt::format("Invalid interpolation `{}`.",
std::string_view{s, l}));
return false;
}
} else {
annotate(fmt::format("Invalid interpolation `{}`.",
std::string_view{s, l}));
return false;
}
}
t.conditions.back().vals.emplace_back(s, l);
// Principals
} else if (w->kind == TokenKind::princ_type) {
if (pp->s.size() <= 1) {
annotate(fmt::format("Principle isn't allowed at top level."));
return false;
}
auto& pri = pp->s[pp->s.size() - 2].w->id == TokenID::Principal ?
t->princ : t->noprinc;
string errmsg;
if (auto o = parse_principal({s, l}, &errmsg)) {
pri.emplace(std::move(*o));
} else if (pp->reject_invalid_principals) {
annotate(std::move(errmsg));
return false;
} else {
ldout(cct, 0) << "Ignored principle `" << std::string_view{s, l} << "`: "
<< errmsg << dendl;
}
} else {
// Failure
annotate(fmt::format("`{}` is not valid in the context of `{}`.",
std::string_view{s, l}, w->name));
return false;
}
if (!arraying) {
pp->s.pop_back();
}
if (is_action && !is_validaction) {
annotate(fmt::format("`{}` is not a valid action.",
std::string_view{s, l}));
return false;
}
return true;
}
bool ParseState::number(const char* s, size_t l) {
// Top level!
if (w->kind == TokenKind::cond_key) {
auto& t = pp->policy.statements.back();
t.conditions.back().vals.emplace_back(s, l);
} else {
// Failure
annotate("Numbers are not allowed outside condition arguments.");
return false;
}
if (!arraying) {
pp->s.pop_back();
}
return true;
}
void ParseState::reset() {
pp->reset(pp->v);
}
bool ParseState::obj_start() {
if (w->objectable && !objecting) {
objecting = true;
if (w->id == TokenID::Statement) {
pp->policy.statements.emplace_back();
}
return true;
}
annotate(fmt::format("The {} keyword cannot introduce an object.",
w->name));
return false;
}
bool ParseState::array_end() {
if (arraying && !objecting) {
pp->s.pop_back();
return true;
}
annotate("Attempt to close unopened array.");
return false;
}
ostream& operator <<(ostream& m, const MaskedIP& ip) {
// I have a theory about why std::bitset is the way it is.
if (ip.v6) {
for (int i = 7; i >= 0; --i) {
uint16_t hextet = 0;
for (int j = 15; j >= 0; --j) {
hextet |= (ip.addr[(i * 16) + j] << j);
}
m << hex << (unsigned int) hextet;
if (i != 0) {
m << ":";
}
}
} else {
// It involves Satan.
for (int i = 3; i >= 0; --i) {
uint8_t b = 0;
for (int j = 7; j >= 0; --j) {
b |= (ip.addr[(i * 8) + j] << j);
}
m << (unsigned int) b;
if (i != 0) {
m << ".";
}
}
}
m << "/" << dec << ip.prefix;
// It would explain a lot
return m;
}
bool Condition::eval(const Environment& env) const {
std::vector<std::string> runtime_vals;
auto i = env.find(key);
if (op == TokenID::Null) {
return i == env.end() ? true : false;
}
if (i == env.end()) {
if (op == TokenID::ForAllValuesStringEquals ||
op == TokenID::ForAllValuesStringEqualsIgnoreCase ||
op == TokenID::ForAllValuesStringLike) {
return true;
} else {
return ifexists;
}
}
if (isruntime) {
string k = vals.back();
k.erase(0,2); //erase $, {
k.erase(k.length() - 1, 1); //erase }
const auto& it = env.equal_range(k);
for (auto itr = it.first; itr != it.second; itr++) {
runtime_vals.emplace_back(itr->second);
}
}
const auto& s = i->second;
const auto& itr = env.equal_range(key);
switch (op) {
// String!
case TokenID::ForAnyValueStringEquals:
case TokenID::StringEquals:
return orrible(std::equal_to<std::string>(), itr, isruntime? runtime_vals : vals);
case TokenID::StringNotEquals:
return orrible(std::not_fn(std::equal_to<std::string>()),
itr, isruntime? runtime_vals : vals);
case TokenID::ForAnyValueStringEqualsIgnoreCase:
case TokenID::StringEqualsIgnoreCase:
return orrible(ci_equal_to(), itr, isruntime? runtime_vals : vals);
case TokenID::StringNotEqualsIgnoreCase:
return orrible(std::not_fn(ci_equal_to()), itr, isruntime? runtime_vals : vals);
case TokenID::ForAnyValueStringLike:
case TokenID::StringLike:
return orrible(string_like(), itr, isruntime? runtime_vals : vals);
case TokenID::StringNotLike:
return orrible(std::not_fn(string_like()), itr, isruntime? runtime_vals : vals);
case TokenID::ForAllValuesStringEquals:
return andible(std::equal_to<std::string>(), itr, isruntime? runtime_vals : vals);
case TokenID::ForAllValuesStringLike:
return andible(string_like(), itr, isruntime? runtime_vals : vals);
case TokenID::ForAllValuesStringEqualsIgnoreCase:
return andible(ci_equal_to(), itr, isruntime? runtime_vals : vals);
// Numeric
case TokenID::NumericEquals:
return shortible(std::equal_to<double>(), as_number, s, vals);
case TokenID::NumericNotEquals:
return shortible(std::not_fn(std::equal_to<double>()),
as_number, s, vals);
case TokenID::NumericLessThan:
return shortible(std::less<double>(), as_number, s, vals);
case TokenID::NumericLessThanEquals:
return shortible(std::less_equal<double>(), as_number, s, vals);
case TokenID::NumericGreaterThan:
return shortible(std::greater<double>(), as_number, s, vals);
case TokenID::NumericGreaterThanEquals:
return shortible(std::greater_equal<double>(), as_number, s, vals);
// Date!
case TokenID::DateEquals:
return shortible(std::equal_to<ceph::real_time>(), as_date, s, vals);
case TokenID::DateNotEquals:
return shortible(std::not_fn(std::equal_to<ceph::real_time>()),
as_date, s, vals);
case TokenID::DateLessThan:
return shortible(std::less<ceph::real_time>(), as_date, s, vals);
case TokenID::DateLessThanEquals:
return shortible(std::less_equal<ceph::real_time>(), as_date, s, vals);
case TokenID::DateGreaterThan:
return shortible(std::greater<ceph::real_time>(), as_date, s, vals);
case TokenID::DateGreaterThanEquals:
return shortible(std::greater_equal<ceph::real_time>(), as_date, s,
vals);
// Bool!
case TokenID::Bool:
return shortible(std::equal_to<bool>(), as_bool, s, vals);
// Binary!
case TokenID::BinaryEquals:
return shortible(std::equal_to<ceph::bufferlist>(), as_binary, s,
vals);
// IP Address!
case TokenID::IpAddress:
return shortible(std::equal_to<MaskedIP>(), as_network, s, vals);
case TokenID::NotIpAddress:
{
auto xc = as_network(s);
if (!xc) {
return false;
}
for (const string& d : vals) {
auto xd = as_network(d);
if (!xd) {
continue;
}
if (xc == xd) {
return false;
}
}
return true;
}
#if 0
// Amazon Resource Names! (Does S3 need this?)
TokenID::ArnEquals, TokenID::ArnNotEquals, TokenID::ArnLike,
TokenID::ArnNotLike,
#endif
default:
return false;
}
}
boost::optional<MaskedIP> Condition::as_network(const string& s) {
MaskedIP m;
if (s.empty()) {
return boost::none;
}
m.v6 = (s.find(':') == string::npos) ? false : true;
auto slash = s.find('/');
if (slash == string::npos) {
m.prefix = m.v6 ? 128 : 32;
} else {
char* end = 0;
m.prefix = strtoul(s.data() + slash + 1, &end, 10);
if (*end != 0 || (m.v6 && m.prefix > 128) ||
(!m.v6 && m.prefix > 32)) {
return boost::none;
}
}
string t;
auto p = &s;
if (slash != string::npos) {
t.assign(s, 0, slash);
p = &t;
}
if (m.v6) {
struct in6_addr a;
if (inet_pton(AF_INET6, p->c_str(), static_cast<void*>(&a)) != 1) {
return boost::none;
}
m.addr |= Address(a.s6_addr[15]) << 0;
m.addr |= Address(a.s6_addr[14]) << 8;
m.addr |= Address(a.s6_addr[13]) << 16;
m.addr |= Address(a.s6_addr[12]) << 24;
m.addr |= Address(a.s6_addr[11]) << 32;
m.addr |= Address(a.s6_addr[10]) << 40;
m.addr |= Address(a.s6_addr[9]) << 48;
m.addr |= Address(a.s6_addr[8]) << 56;
m.addr |= Address(a.s6_addr[7]) << 64;
m.addr |= Address(a.s6_addr[6]) << 72;
m.addr |= Address(a.s6_addr[5]) << 80;
m.addr |= Address(a.s6_addr[4]) << 88;
m.addr |= Address(a.s6_addr[3]) << 96;
m.addr |= Address(a.s6_addr[2]) << 104;
m.addr |= Address(a.s6_addr[1]) << 112;
m.addr |= Address(a.s6_addr[0]) << 120;
} else {
struct in_addr a;
if (inet_pton(AF_INET, p->c_str(), static_cast<void*>(&a)) != 1) {
return boost::none;
}
m.addr = ntohl(a.s_addr);
}
return m;
}
namespace {
const char* condop_string(const TokenID t) {
switch (t) {
case TokenID::StringEquals:
return "StringEquals";
case TokenID::StringNotEquals:
return "StringNotEquals";
case TokenID::StringEqualsIgnoreCase:
return "StringEqualsIgnoreCase";
case TokenID::StringNotEqualsIgnoreCase:
return "StringNotEqualsIgnoreCase";
case TokenID::StringLike:
return "StringLike";
case TokenID::StringNotLike:
return "StringNotLike";
// Numeric!
case TokenID::NumericEquals:
return "NumericEquals";
case TokenID::NumericNotEquals:
return "NumericNotEquals";
case TokenID::NumericLessThan:
return "NumericLessThan";
case TokenID::NumericLessThanEquals:
return "NumericLessThanEquals";
case TokenID::NumericGreaterThan:
return "NumericGreaterThan";
case TokenID::NumericGreaterThanEquals:
return "NumericGreaterThanEquals";
case TokenID::DateEquals:
return "DateEquals";
case TokenID::DateNotEquals:
return "DateNotEquals";
case TokenID::DateLessThan:
return "DateLessThan";
case TokenID::DateLessThanEquals:
return "DateLessThanEquals";
case TokenID::DateGreaterThan:
return "DateGreaterThan";
case TokenID::DateGreaterThanEquals:
return "DateGreaterThanEquals";
case TokenID::Bool:
return "Bool";
case TokenID::BinaryEquals:
return "BinaryEquals";
case TokenID::IpAddress:
return "case TokenID::IpAddress";
case TokenID::NotIpAddress:
return "NotIpAddress";
case TokenID::ArnEquals:
return "ArnEquals";
case TokenID::ArnNotEquals:
return "ArnNotEquals";
case TokenID::ArnLike:
return "ArnLike";
case TokenID::ArnNotLike:
return "ArnNotLike";
case TokenID::Null:
return "Null";
default:
return "InvalidConditionOperator";
}
}
template<typename Iterator>
ostream& print_array(ostream& m, Iterator begin, Iterator end) {
if (begin == end) {
m << "[]";
} else {
m << "[ ";
std::copy(begin, end, std::experimental::make_ostream_joiner(m, ", "));
m << " ]";
}
return m;
}
template<typename Iterator>
ostream& print_dict(ostream& m, Iterator begin, Iterator end) {
m << "{ ";
std::copy(begin, end, std::experimental::make_ostream_joiner(m, ", "));
m << " }";
return m;
}
}
ostream& operator <<(ostream& m, const Condition& c) {
m << condop_string(c.op);
if (c.ifexists) {
m << "IfExists";
}
m << ": { " << c.key;
print_array(m, c.vals.cbegin(), c.vals.cend());
return m << " }";
}
Effect Statement::eval(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida,
uint64_t act, boost::optional<const ARN&> res, boost::optional<PolicyPrincipal&> princ_type) const {
if (eval_principal(e, ida, princ_type) == Effect::Deny) {
return Effect::Pass;
}
if (res && resource.empty() && notresource.empty()) {
return Effect::Pass;
}
if (!res && (!resource.empty() || !notresource.empty())) {
return Effect::Pass;
}
if (!resource.empty() && res) {
if (!std::any_of(resource.begin(), resource.end(),
[&res](const ARN& pattern) {
return pattern.match(*res);
})) {
return Effect::Pass;
}
} else if (!notresource.empty() && res) {
if (std::any_of(notresource.begin(), notresource.end(),
[&res](const ARN& pattern) {
return pattern.match(*res);
})) {
return Effect::Pass;
}
}
if (!(action[act] == 1) || (notaction[act] == 1)) {
return Effect::Pass;
}
if (std::all_of(conditions.begin(),
conditions.end(),
[&e](const Condition& c) { return c.eval(e);})) {
return effect;
}
return Effect::Pass;
}
Effect Statement::eval_principal(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type) const {
if (princ_type) {
*princ_type = PolicyPrincipal::Other;
}
if (ida) {
if (princ.empty() && noprinc.empty()) {
return Effect::Deny;
}
if (ida->get_identity_type() != TYPE_ROLE && !princ.empty() && !ida->is_identity(princ)) {
return Effect::Deny;
}
if (ida->get_identity_type() == TYPE_ROLE && !princ.empty()) {
bool princ_matched = false;
for (auto p : princ) { // Check each principal to determine the type of the one that has matched
boost::container::flat_set<Principal> id;
id.insert(p);
if (ida->is_identity(id)) {
if (p.is_assumed_role() || p.is_user()) {
if (princ_type) *princ_type = PolicyPrincipal::Session;
} else {
if (princ_type) *princ_type = PolicyPrincipal::Role;
}
princ_matched = true;
}
}
if (!princ_matched) {
return Effect::Deny;
}
} else if (!noprinc.empty() && ida->is_identity(noprinc)) {
return Effect::Deny;
}
}
return Effect::Allow;
}
Effect Statement::eval_conditions(const Environment& e) const {
if (std::all_of(conditions.begin(),
conditions.end(),
[&e](const Condition& c) { return c.eval(e);})) {
return Effect::Allow;
}
return Effect::Deny;
}
namespace {
const char* action_bit_string(uint64_t action) {
switch (action) {
case s3GetObject:
return "s3:GetObject";
case s3GetObjectVersion:
return "s3:GetObjectVersion";
case s3PutObject:
return "s3:PutObject";
case s3GetObjectAcl:
return "s3:GetObjectAcl";
case s3GetObjectVersionAcl:
return "s3:GetObjectVersionAcl";
case s3PutObjectAcl:
return "s3:PutObjectAcl";
case s3PutObjectVersionAcl:
return "s3:PutObjectVersionAcl";
case s3DeleteObject:
return "s3:DeleteObject";
case s3DeleteObjectVersion:
return "s3:DeleteObjectVersion";
case s3ListMultipartUploadParts:
return "s3:ListMultipartUploadParts";
case s3AbortMultipartUpload:
return "s3:AbortMultipartUpload";
case s3GetObjectTorrent:
return "s3:GetObjectTorrent";
case s3GetObjectVersionTorrent:
return "s3:GetObjectVersionTorrent";
case s3RestoreObject:
return "s3:RestoreObject";
case s3CreateBucket:
return "s3:CreateBucket";
case s3DeleteBucket:
return "s3:DeleteBucket";
case s3ListBucket:
return "s3:ListBucket";
case s3ListBucketVersions:
return "s3:ListBucketVersions";
case s3ListAllMyBuckets:
return "s3:ListAllMyBuckets";
case s3ListBucketMultipartUploads:
return "s3:ListBucketMultipartUploads";
case s3GetAccelerateConfiguration:
return "s3:GetAccelerateConfiguration";
case s3PutAccelerateConfiguration:
return "s3:PutAccelerateConfiguration";
case s3GetBucketAcl:
return "s3:GetBucketAcl";
case s3PutBucketAcl:
return "s3:PutBucketAcl";
case s3GetBucketCORS:
return "s3:GetBucketCORS";
case s3PutBucketCORS:
return "s3:PutBucketCORS";
case s3GetBucketEncryption:
return "s3:GetBucketEncryption";
case s3PutBucketEncryption:
return "s3:PutBucketEncryption";
case s3GetBucketVersioning:
return "s3:GetBucketVersioning";
case s3PutBucketVersioning:
return "s3:PutBucketVersioning";
case s3GetBucketRequestPayment:
return "s3:GetBucketRequestPayment";
case s3PutBucketRequestPayment:
return "s3:PutBucketRequestPayment";
case s3GetBucketLocation:
return "s3:GetBucketLocation";
case s3GetBucketPolicy:
return "s3:GetBucketPolicy";
case s3DeleteBucketPolicy:
return "s3:DeleteBucketPolicy";
case s3PutBucketPolicy:
return "s3:PutBucketPolicy";
case s3GetBucketNotification:
return "s3:GetBucketNotification";
case s3PutBucketNotification:
return "s3:PutBucketNotification";
case s3GetBucketLogging:
return "s3:GetBucketLogging";
case s3PutBucketLogging:
return "s3:PutBucketLogging";
case s3GetBucketTagging:
return "s3:GetBucketTagging";
case s3PutBucketTagging:
return "s3:PutBucketTagging";
case s3GetBucketWebsite:
return "s3:GetBucketWebsite";
case s3PutBucketWebsite:
return "s3:PutBucketWebsite";
case s3DeleteBucketWebsite:
return "s3:DeleteBucketWebsite";
case s3GetLifecycleConfiguration:
return "s3:GetLifecycleConfiguration";
case s3PutLifecycleConfiguration:
return "s3:PutLifecycleConfiguration";
case s3PutReplicationConfiguration:
return "s3:PutReplicationConfiguration";
case s3GetReplicationConfiguration:
return "s3:GetReplicationConfiguration";
case s3DeleteReplicationConfiguration:
return "s3:DeleteReplicationConfiguration";
case s3PutObjectTagging:
return "s3:PutObjectTagging";
case s3PutObjectVersionTagging:
return "s3:PutObjectVersionTagging";
case s3GetObjectTagging:
return "s3:GetObjectTagging";
case s3GetObjectVersionTagging:
return "s3:GetObjectVersionTagging";
case s3DeleteObjectTagging:
return "s3:DeleteObjectTagging";
case s3DeleteObjectVersionTagging:
return "s3:DeleteObjectVersionTagging";
case s3PutBucketObjectLockConfiguration:
return "s3:PutBucketObjectLockConfiguration";
case s3GetBucketObjectLockConfiguration:
return "s3:GetBucketObjectLockConfiguration";
case s3PutObjectRetention:
return "s3:PutObjectRetention";
case s3GetObjectRetention:
return "s3:GetObjectRetention";
case s3PutObjectLegalHold:
return "s3:PutObjectLegalHold";
case s3GetObjectLegalHold:
return "s3:GetObjectLegalHold";
case s3BypassGovernanceRetention:
return "s3:BypassGovernanceRetention";
case iamPutUserPolicy:
return "iam:PutUserPolicy";
case iamGetUserPolicy:
return "iam:GetUserPolicy";
case iamListUserPolicies:
return "iam:ListUserPolicies";
case iamDeleteUserPolicy:
return "iam:DeleteUserPolicy";
case iamCreateRole:
return "iam:CreateRole";
case iamDeleteRole:
return "iam:DeleteRole";
case iamGetRole:
return "iam:GetRole";
case iamModifyRoleTrustPolicy:
return "iam:ModifyRoleTrustPolicy";
case iamListRoles:
return "iam:ListRoles";
case iamPutRolePolicy:
return "iam:PutRolePolicy";
case iamGetRolePolicy:
return "iam:GetRolePolicy";
case iamListRolePolicies:
return "iam:ListRolePolicies";
case iamDeleteRolePolicy:
return "iam:DeleteRolePolicy";
case iamCreateOIDCProvider:
return "iam:CreateOIDCProvider";
case iamDeleteOIDCProvider:
return "iam:DeleteOIDCProvider";
case iamGetOIDCProvider:
return "iam:GetOIDCProvider";
case iamListOIDCProviders:
return "iam:ListOIDCProviders";
case iamTagRole:
return "iam:TagRole";
case iamListRoleTags:
return "iam:ListRoleTags";
case iamUntagRole:
return "iam:UntagRole";
case iamUpdateRole:
return "iam:UpdateRole";
case stsAssumeRole:
return "sts:AssumeRole";
case stsAssumeRoleWithWebIdentity:
return "sts:AssumeRoleWithWebIdentity";
case stsGetSessionToken:
return "sts:GetSessionToken";
case stsTagSession:
return "sts:TagSession";
}
return "s3Invalid";
}
ostream& print_actions(ostream& m, const Action_t a) {
bool begun = false;
m << "[ ";
for (auto i = 0U; i < allCount; ++i) {
if (a[i] == 1) {
if (begun) {
m << ", ";
} else {
begun = true;
}
m << action_bit_string(i);
}
}
if (begun) {
m << " ]";
} else {
m << "]";
}
return m;
}
}
ostream& operator <<(ostream& m, const Statement& s) {
m << "{ ";
if (s.sid) {
m << "Sid: " << *s.sid << ", ";
}
if (!s.princ.empty()) {
m << "Principal: ";
print_dict(m, s.princ.cbegin(), s.princ.cend());
m << ", ";
}
if (!s.noprinc.empty()) {
m << "NotPrincipal: ";
print_dict(m, s.noprinc.cbegin(), s.noprinc.cend());
m << ", ";
}
m << "Effect: " <<
(s.effect == Effect::Allow ?
(const char*) "Allow" :
(const char*) "Deny");
if (s.action.any() || s.notaction.any() || !s.resource.empty() ||
!s.notresource.empty() || !s.conditions.empty()) {
m << ", ";
}
if (s.action.any()) {
m << "Action: ";
print_actions(m, s.action);
if (s.notaction.any() || !s.resource.empty() ||
!s.notresource.empty() || !s.conditions.empty()) {
m << ", ";
}
}
if (s.notaction.any()) {
m << "NotAction: ";
print_actions(m, s.notaction);
if (!s.resource.empty() || !s.notresource.empty() ||
!s.conditions.empty()) {
m << ", ";
}
}
if (!s.resource.empty()) {
m << "Resource: ";
print_array(m, s.resource.cbegin(), s.resource.cend());
if (!s.notresource.empty() || !s.conditions.empty()) {
m << ", ";
}
}
if (!s.notresource.empty()) {
m << "NotResource: ";
print_array(m, s.notresource.cbegin(), s.notresource.cend());
if (!s.conditions.empty()) {
m << ", ";
}
}
if (!s.conditions.empty()) {
m << "Condition: ";
print_dict(m, s.conditions.cbegin(), s.conditions.cend());
}
return m << " }";
}
Policy::Policy(CephContext* cct, const string& tenant,
const bufferlist& _text,
bool reject_invalid_principals)
: text(_text.to_str()) {
StringStream ss(text.data());
PolicyParser pp(cct, tenant, *this, reject_invalid_principals);
auto pr = Reader{}.Parse<kParseNumbersAsStringsFlag |
kParseCommentsFlag>(ss, pp);
if (!pr) {
throw PolicyParseException(pr, pp.annotation);
}
}
Effect Policy::eval(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida,
std::uint64_t action, boost::optional<const ARN&> resource,
boost::optional<PolicyPrincipal&> princ_type) const {
auto allowed = false;
for (auto& s : statements) {
auto g = s.eval(e, ida, action, resource, princ_type);
if (g == Effect::Deny) {
return g;
} else if (g == Effect::Allow) {
allowed = true;
}
}
return allowed ? Effect::Allow : Effect::Pass;
}
Effect Policy::eval_principal(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type) const {
auto allowed = false;
for (auto& s : statements) {
auto g = s.eval_principal(e, ida, princ_type);
if (g == Effect::Deny) {
return g;
} else if (g == Effect::Allow) {
allowed = true;
}
}
return allowed ? Effect::Allow : Effect::Deny;
}
Effect Policy::eval_conditions(const Environment& e) const {
auto allowed = false;
for (auto& s : statements) {
auto g = s.eval_conditions(e);
if (g == Effect::Deny) {
return g;
} else if (g == Effect::Allow) {
allowed = true;
}
}
return allowed ? Effect::Allow : Effect::Deny;
}
ostream& operator <<(ostream& m, const Policy& p) {
m << "{ Version: "
<< (p.version == Version::v2008_10_17 ? "2008-10-17" : "2012-10-17");
if (p.id || !p.statements.empty()) {
m << ", ";
}
if (p.id) {
m << "Id: " << *p.id;
if (!p.statements.empty()) {
m << ", ";
}
}
if (!p.statements.empty()) {
m << "Statements: ";
print_array(m, p.statements.cbegin(), p.statements.cend());
m << ", ";
}
return m << " }";
}
static const Environment iam_all_env = {
{"aws:SourceIp","1.1.1.1"},
{"aws:UserId","anonymous"},
{"s3:x-amz-server-side-encryption-aws-kms-key-id","secret"}
};
struct IsPublicStatement
{
bool operator() (const Statement &s) const {
if (s.effect == Effect::Allow) {
for (const auto& p : s.princ) {
if (p.is_wildcard()) {
return s.eval_conditions(iam_all_env) == Effect::Allow;
}
}
// no princ should not contain fixed values
return std::none_of(s.noprinc.begin(), s.noprinc.end(), [](const rgw::auth::Principal& p) {
return p.is_wildcard();
});
}
return false;
}
};
bool is_public(const Policy& p)
{
return std::any_of(p.statements.begin(), p.statements.end(), IsPublicStatement());
}
} // namespace IAM
} // namespace rgw
| 44,595 | 25.800481 | 111 |
cc
|
null |
ceph-main/src/rgw/rgw_iam_policy.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <bitset>
#include <chrono>
#include <cstdint>
#include <iostream>
#include <string>
#include <string_view>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/optional.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/variant.hpp>
#include <fmt/format.h>
#include "common/ceph_time.h"
#include "common/iso_8601.h"
#include "rapidjson/error/error.h"
#include "rapidjson/error/en.h"
#include "rgw_acl.h"
#include "rgw_basic_types.h"
#include "rgw_iam_policy_keywords.h"
#include "rgw_string.h"
#include "rgw_arn.h"
namespace rgw {
namespace auth {
class Identity;
}
}
namespace rgw {
namespace IAM {
static constexpr std::uint64_t s3GetObject = 0;
static constexpr std::uint64_t s3GetObjectVersion = 1;
static constexpr std::uint64_t s3PutObject = 2;
static constexpr std::uint64_t s3GetObjectAcl = 3;
static constexpr std::uint64_t s3GetObjectVersionAcl = 4;
static constexpr std::uint64_t s3PutObjectAcl = 5;
static constexpr std::uint64_t s3PutObjectVersionAcl = 6;
static constexpr std::uint64_t s3DeleteObject = 7;
static constexpr std::uint64_t s3DeleteObjectVersion = 8;
static constexpr std::uint64_t s3ListMultipartUploadParts = 9;
static constexpr std::uint64_t s3AbortMultipartUpload = 10;
static constexpr std::uint64_t s3GetObjectTorrent = 11;
static constexpr std::uint64_t s3GetObjectVersionTorrent = 12;
static constexpr std::uint64_t s3RestoreObject = 13;
static constexpr std::uint64_t s3CreateBucket = 14;
static constexpr std::uint64_t s3DeleteBucket = 15;
static constexpr std::uint64_t s3ListBucket = 16;
static constexpr std::uint64_t s3ListBucketVersions = 17;
static constexpr std::uint64_t s3ListAllMyBuckets = 18;
static constexpr std::uint64_t s3ListBucketMultipartUploads = 19;
static constexpr std::uint64_t s3GetAccelerateConfiguration = 20;
static constexpr std::uint64_t s3PutAccelerateConfiguration = 21;
static constexpr std::uint64_t s3GetBucketAcl = 22;
static constexpr std::uint64_t s3PutBucketAcl = 23;
static constexpr std::uint64_t s3GetBucketCORS = 24;
static constexpr std::uint64_t s3PutBucketCORS = 25;
static constexpr std::uint64_t s3GetBucketVersioning = 26;
static constexpr std::uint64_t s3PutBucketVersioning = 27;
static constexpr std::uint64_t s3GetBucketRequestPayment = 28;
static constexpr std::uint64_t s3PutBucketRequestPayment = 29;
static constexpr std::uint64_t s3GetBucketLocation = 30;
static constexpr std::uint64_t s3GetBucketPolicy = 31;
static constexpr std::uint64_t s3DeleteBucketPolicy = 32;
static constexpr std::uint64_t s3PutBucketPolicy = 33;
static constexpr std::uint64_t s3GetBucketNotification = 34;
static constexpr std::uint64_t s3PutBucketNotification = 35;
static constexpr std::uint64_t s3GetBucketLogging = 36;
static constexpr std::uint64_t s3PutBucketLogging = 37;
static constexpr std::uint64_t s3GetBucketTagging = 38;
static constexpr std::uint64_t s3PutBucketTagging = 39;
static constexpr std::uint64_t s3GetBucketWebsite = 40;
static constexpr std::uint64_t s3PutBucketWebsite = 41;
static constexpr std::uint64_t s3DeleteBucketWebsite = 42;
static constexpr std::uint64_t s3GetLifecycleConfiguration = 43;
static constexpr std::uint64_t s3PutLifecycleConfiguration = 44;
static constexpr std::uint64_t s3PutReplicationConfiguration = 45;
static constexpr std::uint64_t s3GetReplicationConfiguration = 46;
static constexpr std::uint64_t s3DeleteReplicationConfiguration = 47;
static constexpr std::uint64_t s3GetObjectTagging = 48;
static constexpr std::uint64_t s3PutObjectTagging = 49;
static constexpr std::uint64_t s3DeleteObjectTagging = 50;
static constexpr std::uint64_t s3GetObjectVersionTagging = 51;
static constexpr std::uint64_t s3PutObjectVersionTagging = 52;
static constexpr std::uint64_t s3DeleteObjectVersionTagging = 53;
static constexpr std::uint64_t s3PutBucketObjectLockConfiguration = 54;
static constexpr std::uint64_t s3GetBucketObjectLockConfiguration = 55;
static constexpr std::uint64_t s3PutObjectRetention = 56;
static constexpr std::uint64_t s3GetObjectRetention = 57;
static constexpr std::uint64_t s3PutObjectLegalHold = 58;
static constexpr std::uint64_t s3GetObjectLegalHold = 59;
static constexpr std::uint64_t s3BypassGovernanceRetention = 60;
static constexpr std::uint64_t s3GetBucketPolicyStatus = 61;
static constexpr std::uint64_t s3PutPublicAccessBlock = 62;
static constexpr std::uint64_t s3GetPublicAccessBlock = 63;
static constexpr std::uint64_t s3DeletePublicAccessBlock = 64;
static constexpr std::uint64_t s3GetBucketPublicAccessBlock = 65;
static constexpr std::uint64_t s3PutBucketPublicAccessBlock = 66;
static constexpr std::uint64_t s3DeleteBucketPublicAccessBlock = 67;
static constexpr std::uint64_t s3GetBucketEncryption = 68;
static constexpr std::uint64_t s3PutBucketEncryption = 69;
static constexpr std::uint64_t s3All = 70;
static constexpr std::uint64_t iamPutUserPolicy = s3All + 1;
static constexpr std::uint64_t iamGetUserPolicy = s3All + 2;
static constexpr std::uint64_t iamDeleteUserPolicy = s3All + 3;
static constexpr std::uint64_t iamListUserPolicies = s3All + 4;
static constexpr std::uint64_t iamCreateRole = s3All + 5;
static constexpr std::uint64_t iamDeleteRole = s3All + 6;
static constexpr std::uint64_t iamModifyRoleTrustPolicy = s3All + 7;
static constexpr std::uint64_t iamGetRole = s3All + 8;
static constexpr std::uint64_t iamListRoles = s3All + 9;
static constexpr std::uint64_t iamPutRolePolicy = s3All + 10;
static constexpr std::uint64_t iamGetRolePolicy = s3All + 11;
static constexpr std::uint64_t iamListRolePolicies = s3All + 12;
static constexpr std::uint64_t iamDeleteRolePolicy = s3All + 13;
static constexpr std::uint64_t iamCreateOIDCProvider = s3All + 14;
static constexpr std::uint64_t iamDeleteOIDCProvider = s3All + 15;
static constexpr std::uint64_t iamGetOIDCProvider = s3All + 16;
static constexpr std::uint64_t iamListOIDCProviders = s3All + 17;
static constexpr std::uint64_t iamTagRole = s3All + 18;
static constexpr std::uint64_t iamListRoleTags = s3All + 19;
static constexpr std::uint64_t iamUntagRole = s3All + 20;
static constexpr std::uint64_t iamUpdateRole = s3All + 21;
static constexpr std::uint64_t iamAll = s3All + 22;
static constexpr std::uint64_t stsAssumeRole = iamAll + 1;
static constexpr std::uint64_t stsAssumeRoleWithWebIdentity = iamAll + 2;
static constexpr std::uint64_t stsGetSessionToken = iamAll + 3;
static constexpr std::uint64_t stsTagSession = iamAll + 4;
static constexpr std::uint64_t stsAll = iamAll + 5;
static constexpr std::uint64_t s3Count = s3All;
static constexpr std::uint64_t allCount = stsAll + 1;
using Action_t = std::bitset<allCount>;
using NotAction_t = Action_t;
template <size_t N>
constexpr std::bitset<N> make_bitmask(size_t s) {
// unfortunately none of the shift/logic operators of std::bitset have a constexpr variation
return s < 64 ? std::bitset<N> ((1ULL << s) - 1) :
std::bitset<N>((1ULL << 63) - 1) | make_bitmask<N> (s - 63) << 63;
}
template <size_t N>
constexpr std::bitset<N> set_cont_bits(size_t start, size_t end)
{
return (make_bitmask<N>(end - start)) << start;
}
static const Action_t None(0);
static const Action_t s3AllValue = set_cont_bits<allCount>(0,s3All);
static const Action_t iamAllValue = set_cont_bits<allCount>(s3All+1,iamAll);
static const Action_t stsAllValue = set_cont_bits<allCount>(iamAll+1,stsAll);
static const Action_t allValue = set_cont_bits<allCount>(0,allCount);
namespace {
// Please update the table in doc/radosgw/s3/authentication.rst if you
// modify this function.
inline int op_to_perm(std::uint64_t op) {
switch (op) {
case s3GetObject:
case s3GetObjectTorrent:
case s3GetObjectVersion:
case s3GetObjectVersionTorrent:
case s3GetObjectTagging:
case s3GetObjectVersionTagging:
case s3GetObjectRetention:
case s3GetObjectLegalHold:
case s3ListAllMyBuckets:
case s3ListBucket:
case s3ListBucketMultipartUploads:
case s3ListBucketVersions:
case s3ListMultipartUploadParts:
return RGW_PERM_READ;
case s3AbortMultipartUpload:
case s3CreateBucket:
case s3DeleteBucket:
case s3DeleteObject:
case s3DeleteObjectVersion:
case s3PutObject:
case s3PutObjectTagging:
case s3PutObjectVersionTagging:
case s3DeleteObjectTagging:
case s3DeleteObjectVersionTagging:
case s3RestoreObject:
case s3PutObjectRetention:
case s3PutObjectLegalHold:
case s3BypassGovernanceRetention:
return RGW_PERM_WRITE;
case s3GetAccelerateConfiguration:
case s3GetBucketAcl:
case s3GetBucketCORS:
case s3GetBucketEncryption:
case s3GetBucketLocation:
case s3GetBucketLogging:
case s3GetBucketNotification:
case s3GetBucketPolicy:
case s3GetBucketPolicyStatus:
case s3GetBucketRequestPayment:
case s3GetBucketTagging:
case s3GetBucketVersioning:
case s3GetBucketWebsite:
case s3GetLifecycleConfiguration:
case s3GetObjectAcl:
case s3GetObjectVersionAcl:
case s3GetReplicationConfiguration:
case s3GetBucketObjectLockConfiguration:
case s3GetBucketPublicAccessBlock:
return RGW_PERM_READ_ACP;
case s3DeleteBucketPolicy:
case s3DeleteBucketWebsite:
case s3DeleteReplicationConfiguration:
case s3PutAccelerateConfiguration:
case s3PutBucketAcl:
case s3PutBucketCORS:
case s3PutBucketEncryption:
case s3PutBucketLogging:
case s3PutBucketNotification:
case s3PutBucketPolicy:
case s3PutBucketRequestPayment:
case s3PutBucketTagging:
case s3PutBucketVersioning:
case s3PutBucketWebsite:
case s3PutLifecycleConfiguration:
case s3PutObjectAcl:
case s3PutObjectVersionAcl:
case s3PutReplicationConfiguration:
case s3PutBucketObjectLockConfiguration:
case s3PutBucketPublicAccessBlock:
return RGW_PERM_WRITE_ACP;
case s3All:
return RGW_PERM_FULL_CONTROL;
}
return RGW_PERM_INVALID;
}
}
enum class PolicyPrincipal {
Role,
Session,
Other
};
using Environment = std::unordered_multimap<std::string, std::string>;
using Address = std::bitset<128>;
struct MaskedIP {
bool v6;
Address addr;
// Since we're mapping IPv6 to IPv4 addresses, we may want to
// consider making the prefix always be in terms of a v6 address
// and just use the v6 bit to rewrite it as a v4 prefix for
// output.
unsigned int prefix;
};
std::ostream& operator <<(std::ostream& m, const MaskedIP& ip);
inline bool operator ==(const MaskedIP& l, const MaskedIP& r) {
auto shift = std::max((l.v6 ? 128 : 32) - ((int) l.prefix),
(r.v6 ? 128 : 32) - ((int) r.prefix));
ceph_assert(shift >= 0);
return (l.addr >> shift) == (r.addr >> shift);
}
struct Condition {
TokenID op;
// Originally I was going to use a perfect hash table, but Marcus
// says keys are to be added at run-time not compile time.
// In future development, use symbol internment.
std::string key;
bool ifexists = false;
bool isruntime = false; //Is evaluated during run-time
// Much to my annoyance there is no actual way to do this in a
// typed way that is compatible with AWS. I know this because I've
// seen examples where the same value is used as a string in one
// context and a date in another.
std::vector<std::string> vals;
Condition() = default;
Condition(TokenID op, const char* s, std::size_t len, bool ifexists)
: op(op), key(s, len), ifexists(ifexists) {}
bool eval(const Environment& e) const;
static boost::optional<double> as_number(const std::string& s) {
std::size_t p = 0;
try {
double d = std::stod(s, &p);
if (p < s.length()) {
return boost::none;
}
return d;
} catch (const std::logic_error& e) {
return boost::none;
}
}
static boost::optional<ceph::real_time> as_date(const std::string& s) {
std::size_t p = 0;
try {
double d = std::stod(s, &p);
if (p == s.length()) {
return ceph::real_time(
std::chrono::seconds(static_cast<uint64_t>(d)) +
std::chrono::nanoseconds(
static_cast<uint64_t>((d - static_cast<uint64_t>(d))
* 1000000000)));
}
return from_iso_8601(std::string_view(s), false);
} catch (const std::logic_error& e) {
return boost::none;
}
}
static boost::optional<bool> as_bool(const std::string& s) {
std::size_t p = 0;
if (s.empty() || boost::iequals(s, "false")) {
return false;
}
try {
double d = std::stod(s, &p);
if (p == s.length()) {
return !((d == +0.0) || (d == -0.0) || std::isnan(d));
}
} catch (const std::logic_error& e) {
// Fallthrough
}
return true;
}
static boost::optional<ceph::bufferlist> as_binary(const std::string& s) {
// In a just world
ceph::bufferlist base64;
// I could populate a bufferlist
base64.push_back(buffer::create_static(
s.length(),
const_cast<char*>(s.data()))); // Yuck
// From a base64 encoded std::string.
ceph::bufferlist bin;
try {
bin.decode_base64(base64);
} catch (const ceph::buffer::malformed_input& e) {
return boost::none;
}
return bin;
}
static boost::optional<MaskedIP> as_network(const std::string& s);
struct ci_equal_to {
bool operator ()(const std::string& s1,
const std::string& s2) const {
return boost::iequals(s1, s2);
}
};
struct string_like {
bool operator ()(const std::string& input,
const std::string& pattern) const {
return match_wildcards(pattern, input, 0);
}
};
struct ci_starts_with {
bool operator()(const std::string& s1,
const std::string& s2) const {
return boost::istarts_with(s1, s2);
}
};
using unordered_multimap_it_pair = std::pair <std::unordered_multimap<std::string,std::string>::const_iterator, std::unordered_multimap<std::string,std::string>::const_iterator>;
template<typename F>
static bool andible(F&& f, const unordered_multimap_it_pair& it,
const std::vector<std::string>& v) {
for (auto itr = it.first; itr != it.second; itr++) {
bool matched = false;
for (const auto& d : v) {
if (f(itr->second, d)) {
matched = true;
}
}
if (!matched)
return false;
}
return true;
}
template<typename F>
static bool orrible(F&& f, const unordered_multimap_it_pair& it,
const std::vector<std::string>& v) {
for (auto itr = it.first; itr != it.second; itr++) {
for (const auto& d : v) {
if (f(itr->second, d)) {
return true;
}
}
}
return false;
}
template<typename F, typename X>
static bool shortible(F&& f, X& x, const std::string& c,
const std::vector<std::string>& v) {
auto xc = std::forward<X>(x)(c);
if (!xc) {
return false;
}
for (const auto& d : v) {
auto xd = x(d);
if (!xd) {
continue;
}
if (f(*xc, *xd)) {
return true;
}
}
return false;
}
template <typename F>
bool has_key_p(const std::string& _key, F p) const {
return p(key, _key);
}
template <typename F>
bool has_val_p(const std::string& _val, F p) const {
for (auto val : vals) {
if (p(val, _val))
return true;
}
return false;
}
};
std::ostream& operator <<(std::ostream& m, const Condition& c);
struct Statement {
boost::optional<std::string> sid = boost::none;
boost::container::flat_set<rgw::auth::Principal> princ;
boost::container::flat_set<rgw::auth::Principal> noprinc;
// Every statement MUST provide an effect. I just initialize it to
// deny as defensive programming.
Effect effect = Effect::Deny;
Action_t action = 0;
NotAction_t notaction = 0;
boost::container::flat_set<ARN> resource;
boost::container::flat_set<ARN> notresource;
std::vector<Condition> conditions;
Effect eval(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida,
std::uint64_t action, boost::optional<const ARN&> resource, boost::optional<PolicyPrincipal&> princ_type=boost::none) const;
Effect eval_principal(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type=boost::none) const;
Effect eval_conditions(const Environment& e) const;
};
std::ostream& operator <<(std::ostream& m, const Statement& s);
struct PolicyParseException : public std::exception {
rapidjson::ParseResult pr;
std::string msg;
explicit PolicyParseException(const rapidjson::ParseResult pr,
const std::string& annotation)
: pr(pr),
msg(fmt::format("At character offset {}, {}",
pr.Offset(),
(pr.Code() == rapidjson::kParseErrorTermination ?
annotation :
rapidjson::GetParseError_En(pr.Code())))) {}
const char* what() const noexcept override {
return msg.c_str();
}
};
struct Policy {
std::string text;
Version version = Version::v2008_10_17;
boost::optional<std::string> id = boost::none;
std::vector<Statement> statements;
// reject_invalid_principals should be set to
// `cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals")`
// when executing operations that *set* a bucket policy, but should
// be false when reading a stored bucket policy so as not to break
// backwards configuration.
Policy(CephContext* cct, const std::string& tenant,
const bufferlist& text,
bool reject_invalid_principals);
Effect eval(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida,
std::uint64_t action, boost::optional<const ARN&> resource, boost::optional<PolicyPrincipal&> princ_type=boost::none) const;
Effect eval_principal(const Environment& e,
boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type=boost::none) const;
Effect eval_conditions(const Environment& e) const;
template <typename F>
bool has_conditional(const std::string& conditional, F p) const {
for (const auto&s: statements){
if (std::any_of(s.conditions.begin(), s.conditions.end(),
[&](const Condition& c) { return c.has_key_p(conditional, p);}))
return true;
}
return false;
}
template <typename F>
bool has_conditional_value(const std::string& conditional, F p) const {
for (const auto&s: statements){
if (std::any_of(s.conditions.begin(), s.conditions.end(),
[&](const Condition& c) { return c.has_val_p(conditional, p);}))
return true;
}
return false;
}
bool has_conditional(const std::string& c) const {
return has_conditional(c, Condition::ci_equal_to());
}
bool has_partial_conditional(const std::string& c) const {
return has_conditional(c, Condition::ci_starts_with());
}
// Example: ${s3:ResourceTag}
bool has_partial_conditional_value(const std::string& c) const {
return has_conditional_value(c, Condition::ci_starts_with());
}
};
std::ostream& operator <<(std::ostream& m, const Policy& p);
bool is_public(const Policy& p);
}
}
| 19,086 | 31.908621 | 180 |
h
|
null |
ceph-main/src/rgw/rgw_iam_policy_keywords.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
namespace rgw {
namespace IAM {
enum class TokenKind {
pseudo, top, statement, cond_op, cond_key, version_key, effect_key,
princ_type
};
enum class TokenID {
/// Pseudo-token
Top,
/// Top-level tokens
Version, Id, Statement,
/// Statement level tokens
Sid, Effect, Principal, NotPrincipal, Action, NotAction,
Resource, NotResource, Condition,
/// Condition Operators!
/// Any of these, except Null, can have an IfExists variant.
// String!
StringEquals, StringNotEquals, StringEqualsIgnoreCase,
StringNotEqualsIgnoreCase, StringLike, StringNotLike,
ForAllValuesStringEquals, ForAnyValueStringEquals,
ForAllValuesStringLike, ForAnyValueStringLike,
ForAllValuesStringEqualsIgnoreCase, ForAnyValueStringEqualsIgnoreCase,
// Numeric!
NumericEquals, NumericNotEquals, NumericLessThan, NumericLessThanEquals,
NumericGreaterThan, NumericGreaterThanEquals,
// Date!
DateEquals, DateNotEquals, DateLessThan, DateLessThanEquals,
DateGreaterThan, DateGreaterThanEquals,
// Bool!
Bool,
// Binary!
BinaryEquals,
// IP Address!
IpAddress, NotIpAddress,
// Amazon Resource Names! (Does S3 need this?)
ArnEquals, ArnNotEquals, ArnLike, ArnNotLike,
// Null!
Null,
#if 0 // Keys are done at runtime now
/// Condition Keys!
awsCurrentTime,
awsEpochTime,
awsTokenIssueTime,
awsMultiFactorAuthPresent,
awsMultiFactorAuthAge,
awsPrincipalType,
awsReferer,
awsSecureTransport,
awsSourceArn,
awsSourceIp,
awsSourceVpc,
awsSourceVpce,
awsUserAgent,
awsuserid,
awsusername,
s3x_amz_acl,
s3x_amz_grant_permission,
s3x_amz_copy_source,
s3x_amz_server_side_encryption,
s3x_amz_server_side_encryption_aws_kms_key_id,
s3x_amz_metadata_directive,
s3x_amz_storage_class,
s3VersionId,
s3LocationConstraint,
s3prefix,
s3delimiter,
s3max_keys,
s3signatureversion,
s3authType,
s3signatureAge,
s3x_amz_content_sha256,
#else
CondKey,
#endif
///
/// Versions!
///
v2008_10_17,
v2012_10_17,
///
/// Effects!
///
Allow,
Deny,
/// Principal Types!
AWS,
Federated,
Service,
CanonicalUser
};
enum class Version {
v2008_10_17,
v2012_10_17
};
enum class Effect {
Allow,
Deny,
Pass
};
enum class Type {
string,
number,
date,
boolean,
binary,
ipaddr,
arn,
null
};
}
}
| 2,454 | 16.535714 | 74 |
h
|
null |
ceph-main/src/rgw/rgw_jsonparser.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <errno.h>
#include <string.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "common/Formatter.h"
#include "common/ceph_json.h"
#include "rgw_common.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
void dump_array(JSONObj *obj)
{
JSONObjIter iter = obj->find_first();
for (; !iter.end(); ++iter) {
JSONObj *o = *iter;
cout << "data=" << o->get_data() << std::endl;
}
}
struct Key {
string user;
string access_key;
string secret_key;
void decode_json(JSONObj *obj) {
JSONDecoder::decode_json("user", user, obj);
JSONDecoder::decode_json("access_key", access_key, obj);
JSONDecoder::decode_json("secret_key", secret_key, obj);
}
};
struct UserInfo {
string uid;
string display_name;
int max_buckets;
list<Key> keys;
void decode_json(JSONObj *obj) {
JSONDecoder::decode_json("user_id", uid, obj);
JSONDecoder::decode_json("display_name", display_name, obj);
JSONDecoder::decode_json("max_buckets", max_buckets, obj);
JSONDecoder::decode_json("keys", keys, obj);
}
};
int main(int argc, char **argv) {
JSONParser parser;
char buf[1024];
bufferlist bl;
for (;;) {
int done;
int len;
len = fread(buf, 1, sizeof(buf), stdin);
if (ferror(stdin)) {
cerr << "read error" << std::endl;
exit(-1);
}
done = feof(stdin);
bool ret = parser.parse(buf, len);
if (!ret)
cerr << "parse error" << std::endl;
if (done) {
bl.append(buf, len);
break;
}
}
JSONObjIter iter = parser.find_first();
for (; !iter.end(); ++iter) {
JSONObj *obj = *iter;
cout << "is_object=" << obj->is_object() << std::endl;
cout << "is_array=" << obj->is_array() << std::endl;
cout << "name=" << obj->get_name() << std::endl;
cout << "data=" << obj->get_data() << std::endl;
}
iter = parser.find_first("conditions");
if (!iter.end()) {
JSONObj *obj = *iter;
JSONObjIter iter2 = obj->find_first();
for (; !iter2.end(); ++iter2) {
JSONObj *child = *iter2;
cout << "is_object=" << child->is_object() << std::endl;
cout << "is_array=" << child->is_array() << std::endl;
if (child->is_array()) {
dump_array(child);
}
cout << "name=" << child->get_name() <<std::endl;
cout << "data=" << child->get_data() <<std::endl;
}
}
RGWUserInfo ui;
try {
ui.decode_json(&parser);
} catch (const JSONDecoder::err& e) {
cout << "failed to decode JSON input: " << e.what() << std::endl;
exit(1);
}
JSONFormatter formatter(true);
formatter.open_object_section("user_info");
ui.dump(&formatter);
formatter.close_section();
formatter.flush(std::cout);
std::cout << std::endl;
}
| 2,902 | 20.664179 | 70 |
cc
|
null |
ceph-main/src/rgw/rgw_kafka.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_kafka.h"
#include "rgw_url.h"
#include <librdkafka/rdkafka.h>
#include "include/ceph_assert.h"
#include <sstream>
#include <cstring>
#include <unordered_map>
#include <string>
#include <vector>
#include <thread>
#include <atomic>
#include <mutex>
#include <boost/lockfree/queue.hpp>
#include "common/dout.h"
#define dout_subsys ceph_subsys_rgw
// TODO investigation, not necessarily issues:
// (1) in case of single threaded writer context use spsc_queue
// (2) check performance of emptying queue to local list, and go over the list and publish
// (3) use std::shared_mutex (c++17) or equivalent for the connections lock
// cmparisson operator between topic pointer and name
bool operator==(const rd_kafka_topic_t* rkt, const std::string& name) {
return name == std::string_view(rd_kafka_topic_name(rkt));
}
namespace rgw::kafka {
// status codes for publishing
static const int STATUS_CONNECTION_CLOSED = -0x1002;
static const int STATUS_QUEUE_FULL = -0x1003;
static const int STATUS_MAX_INFLIGHT = -0x1004;
static const int STATUS_MANAGER_STOPPED = -0x1005;
static const int STATUS_CONNECTION_IDLE = -0x1006;
// status code for connection opening
static const int STATUS_CONF_ALLOC_FAILED = -0x2001;
static const int STATUS_CONF_REPLCACE = -0x2002;
static const int STATUS_OK = 0x0;
// struct for holding the callback and its tag in the callback list
struct reply_callback_with_tag_t {
uint64_t tag;
reply_callback_t cb;
reply_callback_with_tag_t(uint64_t _tag, reply_callback_t _cb) : tag(_tag), cb(_cb) {}
bool operator==(uint64_t rhs) {
return tag == rhs;
}
};
typedef std::vector<reply_callback_with_tag_t> CallbackList;
// struct for holding the connection state object as well as list of topics
// it is used inside an intrusive ref counted pointer (boost::intrusive_ptr)
// since references to deleted objects may still exist in the calling code
struct connection_t {
rd_kafka_t* producer = nullptr;
rd_kafka_conf_t* temp_conf = nullptr;
std::vector<rd_kafka_topic_t*> topics;
uint64_t delivery_tag = 1;
int status = STATUS_OK;
CephContext* const cct;
CallbackList callbacks;
const std::string broker;
const bool use_ssl;
const bool verify_ssl; // TODO currently iognored, not supported in librdkafka v0.11.6
const boost::optional<std::string> ca_location;
const std::string user;
const std::string password;
const boost::optional<std::string> mechanism;
utime_t timestamp = ceph_clock_now();
// cleanup of all internal connection resource
// the object can still remain, and internal connection
// resources created again on successful reconnection
void destroy(int s) {
status = s;
// destroy temporary conf (if connection was never established)
if (temp_conf) {
rd_kafka_conf_destroy(temp_conf);
return;
}
if (!is_ok()) {
// no producer, nothing to destroy
return;
}
// wait for all remaining acks/nacks
rd_kafka_flush(producer, 5*1000 /* wait for max 5 seconds */);
// destroy all topics
std::for_each(topics.begin(), topics.end(), [](auto topic) {rd_kafka_topic_destroy(topic);});
// destroy producer
rd_kafka_destroy(producer);
producer = nullptr;
// fire all remaining callbacks (if not fired by rd_kafka_flush)
std::for_each(callbacks.begin(), callbacks.end(), [this](auto& cb_tag) {
cb_tag.cb(status);
ldout(cct, 20) << "Kafka destroy: invoking callback with tag=" << cb_tag.tag <<
" for: " << broker << dendl;
});
callbacks.clear();
delivery_tag = 1;
ldout(cct, 20) << "Kafka destroy: complete for: " << broker << dendl;
}
bool is_ok() const {
return (producer != nullptr);
}
// ctor for setting immutable values
connection_t(CephContext* _cct, const std::string& _broker, bool _use_ssl, bool _verify_ssl,
const boost::optional<const std::string&>& _ca_location,
const std::string& _user, const std::string& _password, const boost::optional<const std::string&>& _mechanism) :
cct(_cct), broker(_broker), use_ssl(_use_ssl), verify_ssl(_verify_ssl), ca_location(_ca_location), user(_user), password(_password), mechanism(_mechanism) {}
// dtor also destroys the internals
~connection_t() {
destroy(status);
}
};
// convert int status to string - including RGW specific values
std::string status_to_string(int s) {
switch (s) {
case STATUS_OK:
return "STATUS_OK";
case STATUS_CONNECTION_CLOSED:
return "RGW_KAFKA_STATUS_CONNECTION_CLOSED";
case STATUS_QUEUE_FULL:
return "RGW_KAFKA_STATUS_QUEUE_FULL";
case STATUS_MAX_INFLIGHT:
return "RGW_KAFKA_STATUS_MAX_INFLIGHT";
case STATUS_MANAGER_STOPPED:
return "RGW_KAFKA_STATUS_MANAGER_STOPPED";
case STATUS_CONF_ALLOC_FAILED:
return "RGW_KAFKA_STATUS_CONF_ALLOC_FAILED";
case STATUS_CONF_REPLCACE:
return "RGW_KAFKA_STATUS_CONF_REPLCACE";
case STATUS_CONNECTION_IDLE:
return "RGW_KAFKA_STATUS_CONNECTION_IDLE";
}
return std::string(rd_kafka_err2str((rd_kafka_resp_err_t)s));
}
void message_callback(rd_kafka_t* rk, const rd_kafka_message_t* rkmessage, void* opaque) {
ceph_assert(opaque);
const auto conn = reinterpret_cast<connection_t*>(opaque);
const auto result = rkmessage->err;
if (!rkmessage->_private) {
ldout(conn->cct, 20) << "Kafka run: n/ack received, (no callback) with result=" << result << dendl;
return;
}
const auto tag = reinterpret_cast<uint64_t*>(rkmessage->_private);
const auto& callbacks_end = conn->callbacks.end();
const auto& callbacks_begin = conn->callbacks.begin();
const auto tag_it = std::find(callbacks_begin, callbacks_end, *tag);
if (tag_it != callbacks_end) {
ldout(conn->cct, 20) << "Kafka run: n/ack received, invoking callback with tag=" <<
*tag << " and result=" << rd_kafka_err2str(result) << dendl;
tag_it->cb(result);
conn->callbacks.erase(tag_it);
} else {
// TODO add counter for acks with no callback
ldout(conn->cct, 10) << "Kafka run: unsolicited n/ack received with tag=" <<
*tag << dendl;
}
delete tag;
// rkmessage is destroyed automatically by librdkafka
}
void log_callback(const rd_kafka_t* rk, int level, const char *fac, const char *buf) {
ceph_assert(rd_kafka_opaque(rk));
const auto conn = reinterpret_cast<connection_t*>(rd_kafka_opaque(rk));
if (level <= 3)
ldout(conn->cct, 1) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl;
else if (level <= 5)
ldout(conn->cct, 2) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl;
else if (level <= 6)
ldout(conn->cct, 10) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl;
else
ldout(conn->cct, 20) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl;
}
void poll_err_callback(rd_kafka_t *rk, int err, const char *reason, void *opaque) {
const auto conn = reinterpret_cast<connection_t*>(rd_kafka_opaque(rk));
ldout(conn->cct, 10) << "Kafka run: poll error(" << err << "): " << reason << dendl;
}
using connection_t_ptr = std::unique_ptr<connection_t>;
// utility function to create a producer, when the connection object already exists
bool new_producer(connection_t* conn) {
// reset all status codes
conn->status = STATUS_OK;
char errstr[512] = {0};
conn->temp_conf = rd_kafka_conf_new();
if (!conn->temp_conf) {
conn->status = STATUS_CONF_ALLOC_FAILED;
return false;
}
// get list of brokers based on the bootsrap broker
if (rd_kafka_conf_set(conn->temp_conf, "bootstrap.servers", conn->broker.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
if (conn->use_ssl) {
if (!conn->user.empty()) {
// use SSL+SASL
if (rd_kafka_conf_set(conn->temp_conf, "security.protocol", "SASL_SSL", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK ||
rd_kafka_conf_set(conn->temp_conf, "sasl.username", conn->user.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK ||
rd_kafka_conf_set(conn->temp_conf, "sasl.password", conn->password.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured SSL+SASL security" << dendl;
if (conn->mechanism) {
if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", conn->mechanism->c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured SASL mechanism" << dendl;
} else {
if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", "PLAIN", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: using default SASL mechanism" << dendl;
}
} else {
// use only SSL
if (rd_kafka_conf_set(conn->temp_conf, "security.protocol", "SSL", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured SSL security" << dendl;
}
if (conn->ca_location) {
if (rd_kafka_conf_set(conn->temp_conf, "ssl.ca.location", conn->ca_location->c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured CA location" << dendl;
} else {
ldout(conn->cct, 20) << "Kafka connect: using default CA location" << dendl;
}
// Note: when librdkafka.1.0 is available the following line could be uncommented instead of the callback setting call
// if (rd_kafka_conf_set(conn->temp_conf, "enable.ssl.certificate.verification", "0", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured security" << dendl;
} else if (!conn->user.empty()) {
// use SASL+PLAINTEXT
if (rd_kafka_conf_set(conn->temp_conf, "security.protocol", "SASL_PLAINTEXT", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK ||
rd_kafka_conf_set(conn->temp_conf, "sasl.username", conn->user.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK ||
rd_kafka_conf_set(conn->temp_conf, "sasl.password", conn->password.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured SASL_PLAINTEXT" << dendl;
if (conn->mechanism) {
if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", conn->mechanism->c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: successfully configured SASL mechanism" << dendl;
} else {
if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", "PLAIN", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error;
ldout(conn->cct, 20) << "Kafka connect: using default SASL mechanism" << dendl;
}
}
// set the global callback for delivery success/fail
rd_kafka_conf_set_dr_msg_cb(conn->temp_conf, message_callback);
// set the global opaque pointer to be the connection itself
rd_kafka_conf_set_opaque(conn->temp_conf, conn);
// redirect kafka logs to RGW
rd_kafka_conf_set_log_cb(conn->temp_conf, log_callback);
// define poll callback to allow reconnect
rd_kafka_conf_set_error_cb(conn->temp_conf, poll_err_callback);
// create the producer
if (conn->producer) {
ldout(conn->cct, 5) << "Kafka connect: producer already exists. detroying the existing before creating a new one" << dendl;
conn->destroy(STATUS_CONF_REPLCACE);
}
conn->producer = rd_kafka_new(RD_KAFKA_PRODUCER, conn->temp_conf, errstr, sizeof(errstr));
if (!conn->producer) {
conn->status = rd_kafka_last_error();
ldout(conn->cct, 1) << "Kafka connect: failed to create producer: " << errstr << dendl;
return false;
}
ldout(conn->cct, 20) << "Kafka connect: successfully created new producer" << dendl;
{
// set log level of producer
const auto log_level = conn->cct->_conf->subsys.get_log_level(ceph_subsys_rgw);
if (log_level <= 1)
rd_kafka_set_log_level(conn->producer, 3);
else if (log_level <= 2)
rd_kafka_set_log_level(conn->producer, 5);
else if (log_level <= 10)
rd_kafka_set_log_level(conn->producer, 6);
else
rd_kafka_set_log_level(conn->producer, 7);
}
// conf ownership passed to producer
conn->temp_conf = nullptr;
return true;
conf_error:
conn->status = rd_kafka_last_error();
ldout(conn->cct, 1) << "Kafka connect: configuration failed: " << errstr << dendl;
return false;
}
// struct used for holding messages in the message queue
struct message_wrapper_t {
std::string conn_name;
std::string topic;
std::string message;
const reply_callback_t cb;
message_wrapper_t(const std::string& _conn_name,
const std::string& _topic,
const std::string& _message,
reply_callback_t _cb) : conn_name(_conn_name), topic(_topic), message(_message), cb(_cb) {}
};
typedef std::unordered_map<std::string, connection_t_ptr> ConnectionList;
typedef boost::lockfree::queue<message_wrapper_t*, boost::lockfree::fixed_sized<true>> MessageQueue;
class Manager {
public:
const size_t max_connections;
const size_t max_inflight;
const size_t max_queue;
const size_t max_idle_time;
private:
std::atomic<size_t> connection_count;
bool stopped;
int read_timeout_ms;
ConnectionList connections;
MessageQueue messages;
std::atomic<size_t> queued;
std::atomic<size_t> dequeued;
CephContext* const cct;
mutable std::mutex connections_lock;
std::thread runner;
// TODO use rd_kafka_produce_batch for better performance
void publish_internal(message_wrapper_t* message) {
const std::unique_ptr<message_wrapper_t> msg_deleter(message);
const auto conn_it = connections.find(message->conn_name);
if (conn_it == connections.end()) {
ldout(cct, 1) << "Kafka publish: connection was deleted while message was in the queue. error: " << STATUS_CONNECTION_CLOSED << dendl;
if (message->cb) {
message->cb(STATUS_CONNECTION_CLOSED);
}
return;
}
auto& conn = conn_it->second;
conn->timestamp = ceph_clock_now();
if (!conn->is_ok()) {
// connection had an issue while message was in the queue
// TODO add error stats
ldout(conn->cct, 1) << "Kafka publish: producer was closed while message was in the queue. error: " << status_to_string(conn->status) << dendl;
if (message->cb) {
message->cb(conn->status);
}
return;
}
// create a new topic unless it was already created
auto topic_it = std::find(conn->topics.begin(), conn->topics.end(), message->topic);
rd_kafka_topic_t* topic = nullptr;
if (topic_it == conn->topics.end()) {
topic = rd_kafka_topic_new(conn->producer, message->topic.c_str(), nullptr);
if (!topic) {
const auto err = rd_kafka_last_error();
ldout(conn->cct, 1) << "Kafka publish: failed to create topic: " << message->topic << " error: " << status_to_string(err) << dendl;
if (message->cb) {
message->cb(err);
}
conn->destroy(err);
return;
}
// TODO use the topics list as an LRU cache
conn->topics.push_back(topic);
ldout(conn->cct, 20) << "Kafka publish: successfully created topic: " << message->topic << dendl;
} else {
topic = *topic_it;
ldout(conn->cct, 20) << "Kafka publish: reused existing topic: " << message->topic << dendl;
}
const auto tag = (message->cb == nullptr ? nullptr : new uint64_t(conn->delivery_tag++));
const auto rc = rd_kafka_produce(
topic,
// TODO: non builtin partitioning
RD_KAFKA_PARTITION_UA,
// make a copy of the payload
// so it is safe to pass the pointer from the string
RD_KAFKA_MSG_F_COPY,
message->message.data(),
message->message.length(),
// optional key and its length
nullptr,
0,
// opaque data: tag, used in the global callback
// in order to invoke the real callback
// null if no callback exists
tag);
if (rc == -1) {
const auto err = rd_kafka_last_error();
ldout(conn->cct, 10) << "Kafka publish: failed to produce: " << rd_kafka_err2str(err) << dendl;
// TODO: dont error on full queue, and don't destroy connection, retry instead
// immediatly invoke callback on error if needed
if (message->cb) {
message->cb(err);
}
conn->destroy(err);
delete tag;
return;
}
if (tag) {
auto const q_len = conn->callbacks.size();
if (q_len < max_inflight) {
ldout(conn->cct, 20) << "Kafka publish (with callback, tag=" << *tag << "): OK. Queue has: " << q_len << " callbacks" << dendl;
conn->callbacks.emplace_back(*tag, message->cb);
} else {
// immediately invoke callback with error - this is not a connection error
ldout(conn->cct, 1) << "Kafka publish (with callback): failed with error: callback queue full" << dendl;
message->cb(STATUS_MAX_INFLIGHT);
// tag will be deleted when the global callback is invoked
}
} else {
ldout(conn->cct, 20) << "Kafka publish (no callback): OK" << dendl;
}
// coverity[leaked_storage:SUPPRESS]
}
// the managers thread:
// (1) empty the queue of messages to be published
// (2) loop over all connections and read acks
// (3) manages deleted connections
// (4) TODO reconnect on connection errors
// (5) TODO cleanup timedout callbacks
void run() noexcept {
while (!stopped) {
// publish all messages in the queue
auto reply_count = 0U;
const auto send_count = messages.consume_all(std::bind(&Manager::publish_internal, this, std::placeholders::_1));
dequeued += send_count;
ConnectionList::iterator conn_it;
ConnectionList::const_iterator end_it;
{
// thread safe access to the connection list
// once the iterators are fetched they are guaranteed to remain valid
std::lock_guard lock(connections_lock);
conn_it = connections.begin();
end_it = connections.end();
}
// loop over all connections to read acks
for (;conn_it != end_it;) {
auto& conn = conn_it->second;
// Checking the connection idlesness
if(conn->timestamp.sec() + max_idle_time < ceph_clock_now()) {
ldout(conn->cct, 20) << "kafka run: deleting a connection due to idle behaviour: " << ceph_clock_now() << dendl;
std::lock_guard lock(connections_lock);
conn_it = connections.erase(conn_it);
--connection_count; \
continue;
}
// try to reconnect the connection if it has an error
if (!conn->is_ok()) {
ldout(conn->cct, 10) << "Kafka run: connection status is: " << status_to_string(conn->status) << dendl;
const auto& broker = conn_it->first;
ldout(conn->cct, 20) << "Kafka run: retry connection" << dendl;
if (new_producer(conn.get()) == false) {
ldout(conn->cct, 10) << "Kafka run: connection (" << broker << ") retry failed" << dendl;
// TODO: add error counter for failed retries
// TODO: add exponential backoff for retries
} else {
ldout(conn->cct, 10) << "Kafka run: connection (" << broker << ") retry successfull" << dendl;
}
++conn_it;
continue;
}
reply_count += rd_kafka_poll(conn->producer, read_timeout_ms);
// just increment the iterator
++conn_it;
}
// if no messages were received or published
// across all connection, sleep for 100ms
if (send_count == 0 && reply_count == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}
// used in the dtor for message cleanup
static void delete_message(const message_wrapper_t* message) {
delete message;
}
public:
Manager(size_t _max_connections,
size_t _max_inflight,
size_t _max_queue,
int _read_timeout_ms,
CephContext* _cct) :
max_connections(_max_connections),
max_inflight(_max_inflight),
max_queue(_max_queue),
max_idle_time(30),
connection_count(0),
stopped(false),
read_timeout_ms(_read_timeout_ms),
connections(_max_connections),
messages(max_queue),
queued(0),
dequeued(0),
cct(_cct),
runner(&Manager::run, this) {
// The hashmap has "max connections" as the initial number of buckets,
// and allows for 10 collisions per bucket before rehash.
// This is to prevent rehashing so that iterators are not invalidated
// when a new connection is added.
connections.max_load_factor(10.0);
// give the runner thread a name for easier debugging
const auto rc = ceph_pthread_setname(runner.native_handle(), "kafka_manager");
ceph_assert(rc==0);
}
// non copyable
Manager(const Manager&) = delete;
const Manager& operator=(const Manager&) = delete;
// stop the main thread
void stop() {
stopped = true;
}
// connect to a broker, or reuse an existing connection if already connected
bool connect(std::string& broker,
const std::string& url,
bool use_ssl,
bool verify_ssl,
boost::optional<const std::string&> ca_location,
boost::optional<const std::string&> mechanism) {
if (stopped) {
ldout(cct, 1) << "Kafka connect: manager is stopped" << dendl;
return false;
}
std::string user;
std::string password;
if (!parse_url_authority(url, broker, user, password)) {
// TODO: increment counter
ldout(cct, 1) << "Kafka connect: URL parsing failed" << dendl;
return false;
}
// this should be validated by the regex in parse_url()
ceph_assert(user.empty() == password.empty());
if (!user.empty() && !use_ssl && !g_conf().get_val<bool>("rgw_allow_notification_secrets_in_cleartext")) {
ldout(cct, 1) << "Kafka connect: user/password are only allowed over secure connection" << dendl;
return false;
}
std::lock_guard lock(connections_lock);
const auto it = connections.find(broker);
// note that ssl vs. non-ssl connection to the same host are two separate conenctions
if (it != connections.end()) {
// connection found - return even if non-ok
ldout(cct, 20) << "Kafka connect: connection found" << dendl;
return it->second.get();
}
// connection not found, creating a new one
if (connection_count >= max_connections) {
// TODO: increment counter
ldout(cct, 1) << "Kafka connect: max connections exceeded" << dendl;
return false;
}
// create_connection must always return a connection object
// even if error occurred during creation.
// in such a case the creation will be retried in the main thread
++connection_count;
ldout(cct, 10) << "Kafka connect: new connection is created. Total connections: " << connection_count << dendl;
auto conn = connections.emplace(broker, std::make_unique<connection_t>(cct, broker, use_ssl, verify_ssl, ca_location, user, password, mechanism)).first->second.get();
if (!new_producer(conn)) {
ldout(cct, 10) << "Kafka connect: new connection is created. But producer creation failed. will retry" << dendl;
}
return true;
}
// TODO publish with confirm is needed in "none" case as well, cb should be invoked publish is ok (no ack)
int publish(const std::string& conn_name,
const std::string& topic,
const std::string& message) {
if (stopped) {
return STATUS_MANAGER_STOPPED;
}
auto message_wrapper = std::make_unique<message_wrapper_t>(conn_name, topic, message, nullptr);
if (messages.push(message_wrapper.get())) {
std::ignore = message_wrapper.release();
++queued;
return STATUS_OK;
}
return STATUS_QUEUE_FULL;
}
int publish_with_confirm(const std::string& conn_name,
const std::string& topic,
const std::string& message,
reply_callback_t cb) {
if (stopped) {
return STATUS_MANAGER_STOPPED;
}
auto message_wrapper = std::make_unique<message_wrapper_t>(conn_name, topic, message, cb);
if (messages.push(message_wrapper.get())) {
std::ignore = message_wrapper.release();
++queued;
return STATUS_OK;
}
return STATUS_QUEUE_FULL;
}
// dtor wait for thread to stop
// then connection are cleaned-up
~Manager() {
stopped = true;
runner.join();
messages.consume_all(delete_message);
}
// get the number of connections
size_t get_connection_count() const {
return connection_count;
}
// get the number of in-flight messages
size_t get_inflight() const {
size_t sum = 0;
std::lock_guard lock(connections_lock);
std::for_each(connections.begin(), connections.end(), [&sum](auto& conn_pair) {
sum += conn_pair.second->callbacks.size();
});
return sum;
}
// running counter of the queued messages
size_t get_queued() const {
return queued;
}
// running counter of the dequeued messages
size_t get_dequeued() const {
return dequeued;
}
};
// singleton manager
// note that the manager itself is not a singleton, and multiple instances may co-exist
// TODO make the pointer atomic in allocation and deallocation to avoid race conditions
static Manager* s_manager = nullptr;
static const size_t MAX_CONNECTIONS_DEFAULT = 256;
static const size_t MAX_INFLIGHT_DEFAULT = 8192;
static const size_t MAX_QUEUE_DEFAULT = 8192;
static const int READ_TIMEOUT_MS_DEFAULT = 500;
bool init(CephContext* cct) {
if (s_manager) {
return false;
}
// TODO: take conf from CephContext
s_manager = new Manager(MAX_CONNECTIONS_DEFAULT, MAX_INFLIGHT_DEFAULT, MAX_QUEUE_DEFAULT, READ_TIMEOUT_MS_DEFAULT, cct);
return true;
}
void shutdown() {
delete s_manager;
s_manager = nullptr;
}
bool connect(std::string& broker, const std::string& url, bool use_ssl, bool verify_ssl,
boost::optional<const std::string&> ca_location,
boost::optional<const std::string&> mechanism) {
if (!s_manager) return false;
return s_manager->connect(broker, url, use_ssl, verify_ssl, ca_location, mechanism);
}
int publish(const std::string& conn_name,
const std::string& topic,
const std::string& message) {
if (!s_manager) return STATUS_MANAGER_STOPPED;
return s_manager->publish(conn_name, topic, message);
}
int publish_with_confirm(const std::string& conn_name,
const std::string& topic,
const std::string& message,
reply_callback_t cb) {
if (!s_manager) return STATUS_MANAGER_STOPPED;
return s_manager->publish_with_confirm(conn_name, topic, message, cb);
}
size_t get_connection_count() {
if (!s_manager) return 0;
return s_manager->get_connection_count();
}
size_t get_inflight() {
if (!s_manager) return 0;
return s_manager->get_inflight();
}
size_t get_queued() {
if (!s_manager) return 0;
return s_manager->get_queued();
}
size_t get_dequeued() {
if (!s_manager) return 0;
return s_manager->get_dequeued();
}
size_t get_max_connections() {
if (!s_manager) return MAX_CONNECTIONS_DEFAULT;
return s_manager->max_connections;
}
size_t get_max_inflight() {
if (!s_manager) return MAX_INFLIGHT_DEFAULT;
return s_manager->max_inflight;
}
size_t get_max_queue() {
if (!s_manager) return MAX_QUEUE_DEFAULT;
return s_manager->max_queue;
}
} // namespace kafka
| 28,163 | 36.702811 | 315 |
cc
|
null |
ceph-main/src/rgw/rgw_kafka.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string>
#include <functional>
#include <boost/optional.hpp>
#include "include/common_fwd.h"
namespace rgw::kafka {
// the reply callback is expected to get an integer parameter
// indicating the result, and not to return anything
typedef std::function<void(int)> reply_callback_t;
// initialize the kafka manager
bool init(CephContext* cct);
// shutdown the kafka manager
void shutdown();
// connect to a kafka endpoint
bool connect(std::string& broker, const std::string& url, bool use_ssl, bool verify_ssl, boost::optional<const std::string&> ca_location, boost::optional<const std::string&> mechanism);
// publish a message over a connection that was already created
int publish(const std::string& conn_name,
const std::string& topic,
const std::string& message);
// publish a message over a connection that was already created
// and pass a callback that will be invoked (async) when broker confirms
// receiving the message
int publish_with_confirm(const std::string& conn_name,
const std::string& topic,
const std::string& message,
reply_callback_t cb);
// convert the integer status returned from the "publish" function to a string
std::string status_to_string(int s);
// number of connections
size_t get_connection_count();
// return the number of messages that were sent
// to broker, but were not yet acked/nacked/timedout
size_t get_inflight();
// running counter of successfully queued messages
size_t get_queued();
// running counter of dequeued messages
size_t get_dequeued();
// number of maximum allowed connections
size_t get_max_connections();
// number of maximum allowed inflight messages
size_t get_max_inflight();
// maximum number of messages in the queue
size_t get_max_queue();
}
| 1,873 | 26.970149 | 185 |
h
|
null |
ceph-main/src/rgw/rgw_keystone.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <errno.h>
#include <fnmatch.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include "common/errno.h"
#include "common/ceph_json.h"
#include "include/types.h"
#include "include/str_list.h"
#include "rgw_common.h"
#include "rgw_keystone.h"
#include "common/armor.h"
#include "common/Cond.h"
#include "rgw_perf_counters.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
#define PKI_ANS1_PREFIX "MII"
using namespace std;
bool rgw_is_pki_token(const string& token)
{
return token.compare(0, sizeof(PKI_ANS1_PREFIX) - 1, PKI_ANS1_PREFIX) == 0;
}
void rgw_get_token_id(const string& token, string& token_id)
{
if (!rgw_is_pki_token(token)) {
token_id = token;
return;
}
unsigned char m[CEPH_CRYPTO_MD5_DIGESTSIZE];
MD5 hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
hash.Update((const unsigned char *)token.c_str(), token.size());
hash.Final(m);
char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);
token_id = calc_md5;
}
namespace rgw {
namespace keystone {
ApiVersion CephCtxConfig::get_api_version() const noexcept
{
switch (g_ceph_context->_conf->rgw_keystone_api_version) {
case 3:
return ApiVersion::VER_3;
case 2:
return ApiVersion::VER_2;
default:
dout(0) << "ERROR: wrong Keystone API version: "
<< g_ceph_context->_conf->rgw_keystone_api_version
<< "; falling back to v2" << dendl;
return ApiVersion::VER_2;
}
}
std::string CephCtxConfig::get_endpoint_url() const noexcept
{
static const std::string url = g_ceph_context->_conf->rgw_keystone_url;
if (url.empty() || boost::algorithm::ends_with(url, "/")) {
return url;
} else {
static const std::string url_normalised = url + '/';
return url_normalised;
}
}
/* secrets */
const std::string CephCtxConfig::empty{""};
static inline std::string read_secret(const std::string& file_path)
{
using namespace std;
constexpr int16_t size{1024};
char buf[size];
string s;
s.reserve(size);
ifstream ifs(file_path, ios::in | ios::binary);
if (ifs) {
while (true) {
auto sbuf = ifs.rdbuf();
auto len = sbuf->sgetn(buf, size);
if (!len)
break;
s.append(buf, len);
}
boost::algorithm::trim(s);
if (s.back() == '\n')
s.pop_back();
}
return s;
}
std::string CephCtxConfig::get_admin_token() const noexcept
{
auto& atv = g_ceph_context->_conf->rgw_keystone_admin_token_path;
if (!atv.empty()) {
return read_secret(atv);
} else {
auto& atv = g_ceph_context->_conf->rgw_keystone_admin_token;
if (!atv.empty()) {
return atv;
}
}
return empty;
}
std::string CephCtxConfig::get_admin_password() const noexcept {
auto& apv = g_ceph_context->_conf->rgw_keystone_admin_password_path;
if (!apv.empty()) {
return read_secret(apv);
} else {
auto& apv = g_ceph_context->_conf->rgw_keystone_admin_password;
if (!apv.empty()) {
return apv;
}
}
return empty;
}
int Service::get_admin_token(const DoutPrefixProvider *dpp,
CephContext* const cct,
TokenCache& token_cache,
const Config& config,
std::string& token)
{
/* Let's check whether someone uses the deprecated "admin token" feauture
* based on a shared secret from keystone.conf file. */
const auto& admin_token = config.get_admin_token();
if (! admin_token.empty()) {
token = std::string(admin_token.data(), admin_token.length());
return 0;
}
TokenEnvelope t;
/* Try cache first before calling Keystone for a new admin token. */
if (token_cache.find_admin(t)) {
ldpp_dout(dpp, 20) << "found cached admin token" << dendl;
token = t.token.id;
return 0;
}
/* Call Keystone now. */
const auto ret = issue_admin_token_request(dpp, cct, config, t);
if (! ret) {
token_cache.add_admin(t);
token = t.token.id;
}
return ret;
}
int Service::issue_admin_token_request(const DoutPrefixProvider *dpp,
CephContext* const cct,
const Config& config,
TokenEnvelope& t)
{
std::string token_url = config.get_endpoint_url();
if (token_url.empty()) {
return -EINVAL;
}
bufferlist token_bl;
RGWGetKeystoneAdminToken token_req(cct, "POST", "", &token_bl);
token_req.append_header("Content-Type", "application/json");
JSONFormatter jf;
const auto keystone_version = config.get_api_version();
if (keystone_version == ApiVersion::VER_2) {
AdminTokenRequestVer2 req_serializer(config);
req_serializer.dump(&jf);
std::stringstream ss;
jf.flush(ss);
token_req.set_post_data(ss.str());
token_req.set_send_length(ss.str().length());
token_url.append("v2.0/tokens");
} else if (keystone_version == ApiVersion::VER_3) {
AdminTokenRequestVer3 req_serializer(config);
req_serializer.dump(&jf);
std::stringstream ss;
jf.flush(ss);
token_req.set_post_data(ss.str());
token_req.set_send_length(ss.str().length());
token_url.append("v3/auth/tokens");
} else {
return -ENOTSUP;
}
token_req.set_url(token_url);
const int ret = token_req.process(null_yield);
if (ret < 0) {
return ret;
}
/* Detect rejection earlier than during the token parsing step. */
if (token_req.get_http_status() ==
RGWGetKeystoneAdminToken::HTTP_STATUS_UNAUTHORIZED) {
return -EACCES;
}
if (t.parse(dpp, cct, token_req.get_subject_token(), token_bl,
keystone_version) != 0) {
return -EINVAL;
}
return 0;
}
int Service::get_keystone_barbican_token(const DoutPrefixProvider *dpp,
CephContext * const cct,
std::string& token)
{
using keystone_config_t = rgw::keystone::CephCtxConfig;
using keystone_cache_t = rgw::keystone::TokenCache;
auto& config = keystone_config_t::get_instance();
auto& token_cache = keystone_cache_t::get_instance<keystone_config_t>();
std::string token_url = config.get_endpoint_url();
if (token_url.empty()) {
return -EINVAL;
}
rgw::keystone::TokenEnvelope t;
/* Try cache first. */
if (token_cache.find_barbican(t)) {
ldpp_dout(dpp, 20) << "found cached barbican token" << dendl;
token = t.token.id;
return 0;
}
bufferlist token_bl;
RGWKeystoneHTTPTransceiver token_req(cct, "POST", "", &token_bl);
token_req.append_header("Content-Type", "application/json");
JSONFormatter jf;
const auto keystone_version = config.get_api_version();
if (keystone_version == ApiVersion::VER_2) {
rgw::keystone::BarbicanTokenRequestVer2 req_serializer(cct);
req_serializer.dump(&jf);
std::stringstream ss;
jf.flush(ss);
token_req.set_post_data(ss.str());
token_req.set_send_length(ss.str().length());
token_url.append("v2.0/tokens");
} else if (keystone_version == ApiVersion::VER_3) {
BarbicanTokenRequestVer3 req_serializer(cct);
req_serializer.dump(&jf);
std::stringstream ss;
jf.flush(ss);
token_req.set_post_data(ss.str());
token_req.set_send_length(ss.str().length());
token_url.append("v3/auth/tokens");
} else {
return -ENOTSUP;
}
token_req.set_url(token_url);
ldpp_dout(dpp, 20) << "Requesting secret from barbican url=" << token_url << dendl;
const int ret = token_req.process(null_yield);
if (ret < 0) {
ldpp_dout(dpp, 20) << "Barbican process error:" << token_bl.c_str() << dendl;
return ret;
}
/* Detect rejection earlier than during the token parsing step. */
if (token_req.get_http_status() ==
RGWKeystoneHTTPTransceiver::HTTP_STATUS_UNAUTHORIZED) {
return -EACCES;
}
if (t.parse(dpp, cct, token_req.get_subject_token(), token_bl,
keystone_version) != 0) {
return -EINVAL;
}
token_cache.add_barbican(t);
token = t.token.id;
return 0;
}
bool TokenEnvelope::has_role(const std::string& r) const
{
list<Role>::const_iterator iter;
for (iter = roles.cbegin(); iter != roles.cend(); ++iter) {
if (fnmatch(r.c_str(), ((*iter).name.c_str()), 0) == 0) {
return true;
}
}
return false;
}
int TokenEnvelope::parse(const DoutPrefixProvider *dpp,
CephContext* const cct,
const std::string& token_str,
ceph::bufferlist& bl,
const ApiVersion version)
{
JSONParser parser;
if (! parser.parse(bl.c_str(), bl.length())) {
ldpp_dout(dpp, 0) << "Keystone token parse error: malformed json" << dendl;
return -EINVAL;
}
JSONObjIter token_iter = parser.find_first("token");
JSONObjIter access_iter = parser.find_first("access");
try {
if (version == rgw::keystone::ApiVersion::VER_2) {
if (! access_iter.end()) {
decode_v2(*access_iter);
} else if (! token_iter.end()) {
/* TokenEnvelope structure doesn't follow Identity API v2, so let's
* fallback to v3. Otherwise we can assume it's wrongly formatted.
* The whole mechanism is a workaround for s3_token middleware that
* speaks in v2 disregarding the promise to go with v3. */
decode_v3(*token_iter);
/* Identity v3 conveys the token inforamtion not as a part of JSON but
* in the X-Subject-Token HTTP header we're getting from caller. */
token.id = token_str;
} else {
return -EINVAL;
}
} else if (version == rgw::keystone::ApiVersion::VER_3) {
if (! token_iter.end()) {
decode_v3(*token_iter);
/* v3 suceeded. We have to fill token.id from external input as it
* isn't a part of the JSON response anymore. It has been moved
* to X-Subject-Token HTTP header instead. */
token.id = token_str;
} else if (! access_iter.end()) {
/* If the token cannot be parsed according to V3, try V2. */
decode_v2(*access_iter);
} else {
return -EINVAL;
}
} else {
return -ENOTSUP;
}
} catch (const JSONDecoder::err& err) {
ldpp_dout(dpp, 0) << "Keystone token parse error: " << err.what() << dendl;
return -EINVAL;
}
return 0;
}
/*
* Maybe one day we'll have the parser find this in Keystone replies.
* But for now, we use the confguration to augment the list of roles.
*/
void TokenEnvelope::update_roles(const std::vector<std::string> & admin,
const std::vector<std::string> & reader)
{
for (auto& iter: roles) {
for (const auto& r : admin) {
if (fnmatch(r.c_str(), iter.name.c_str(), 0) == 0) {
iter.is_admin = true;
break;
}
}
for (const auto& r : reader) {
if (fnmatch(r.c_str(), iter.name.c_str(), 0) == 0) {
iter.is_reader = true;
break;
}
}
}
}
bool TokenCache::find(const std::string& token_id,
rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
return find_locked(token_id, token, tokens, tokens_lru);
}
bool TokenCache::find_service(const std::string& token_id,
rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
return find_locked(token_id, token, service_tokens, service_tokens_lru);
}
bool TokenCache::find_locked(const std::string& token_id, rgw::keystone::TokenEnvelope& token,
std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru)
{
ceph_assert(ceph_mutex_is_locked_by_me(lock));
map<string, token_entry>::iterator iter = tokens.find(token_id);
if (iter == tokens.end()) {
if (perfcounter) perfcounter->inc(l_rgw_keystone_token_cache_miss);
return false;
}
token_entry& entry = iter->second;
tokens_lru.erase(entry.lru_iter);
if (entry.token.expired()) {
tokens.erase(iter);
if (perfcounter) perfcounter->inc(l_rgw_keystone_token_cache_hit);
return false;
}
token = entry.token;
tokens_lru.push_front(token_id);
entry.lru_iter = tokens_lru.begin();
if (perfcounter) perfcounter->inc(l_rgw_keystone_token_cache_hit);
return true;
}
bool TokenCache::find_admin(rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
return find_locked(admin_token_id, token, tokens, tokens_lru);
}
bool TokenCache::find_barbican(rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
return find_locked(barbican_token_id, token, tokens, tokens_lru);
}
void TokenCache::add(const std::string& token_id,
const rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
add_locked(token_id, token, tokens, tokens_lru);
}
void TokenCache::add_service(const std::string& token_id,
const rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
add_locked(token_id, token, service_tokens, service_tokens_lru);
}
void TokenCache::add_locked(const std::string& token_id, const rgw::keystone::TokenEnvelope& token,
std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru)
{
ceph_assert(ceph_mutex_is_locked_by_me(lock));
map<string, token_entry>::iterator iter = tokens.find(token_id);
if (iter != tokens.end()) {
token_entry& e = iter->second;
tokens_lru.erase(e.lru_iter);
}
tokens_lru.push_front(token_id);
token_entry& entry = tokens[token_id];
entry.token = token;
entry.lru_iter = tokens_lru.begin();
while (tokens_lru.size() > max) {
list<string>::reverse_iterator riter = tokens_lru.rbegin();
iter = tokens.find(*riter);
ceph_assert(iter != tokens.end());
tokens.erase(iter);
tokens_lru.pop_back();
}
}
void TokenCache::add_admin(const rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
rgw_get_token_id(token.token.id, admin_token_id);
add_locked(admin_token_id, token, tokens, tokens_lru);
}
void TokenCache::add_barbican(const rgw::keystone::TokenEnvelope& token)
{
std::lock_guard l{lock};
rgw_get_token_id(token.token.id, barbican_token_id);
add_locked(barbican_token_id, token, tokens, tokens_lru);
}
void TokenCache::invalidate(const DoutPrefixProvider *dpp, const std::string& token_id)
{
std::lock_guard l{lock};
map<string, token_entry>::iterator iter = tokens.find(token_id);
if (iter == tokens.end())
return;
ldpp_dout(dpp, 20) << "invalidating revoked token id=" << token_id << dendl;
token_entry& e = iter->second;
tokens_lru.erase(e.lru_iter);
tokens.erase(iter);
}
bool TokenCache::going_down() const
{
return down_flag;
}
}; /* namespace keystone */
}; /* namespace rgw */
void rgw::keystone::TokenEnvelope::Token::decode_json(JSONObj *obj)
{
string expires_iso8601;
struct tm t;
JSONDecoder::decode_json("id", id, obj, true);
JSONDecoder::decode_json("tenant", tenant_v2, obj, true);
JSONDecoder::decode_json("expires", expires_iso8601, obj, true);
if (parse_iso8601(expires_iso8601.c_str(), &t)) {
expires = internal_timegm(&t);
} else {
expires = 0;
throw JSONDecoder::err("Failed to parse ISO8601 expiration date from Keystone response.");
}
}
void rgw::keystone::TokenEnvelope::Role::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("id", id, obj);
JSONDecoder::decode_json("name", name, obj, true);
}
void rgw::keystone::TokenEnvelope::Domain::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("id", id, obj, true);
JSONDecoder::decode_json("name", name, obj, true);
}
void rgw::keystone::TokenEnvelope::Project::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("id", id, obj, true);
JSONDecoder::decode_json("name", name, obj, true);
JSONDecoder::decode_json("domain", domain, obj);
}
void rgw::keystone::TokenEnvelope::User::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("id", id, obj, true);
JSONDecoder::decode_json("name", name, obj, true);
JSONDecoder::decode_json("domain", domain, obj);
JSONDecoder::decode_json("roles", roles_v2, obj);
}
void rgw::keystone::TokenEnvelope::decode_v3(JSONObj* const root_obj)
{
std::string expires_iso8601;
JSONDecoder::decode_json("user", user, root_obj, true);
JSONDecoder::decode_json("expires_at", expires_iso8601, root_obj, true);
JSONDecoder::decode_json("roles", roles, root_obj, true);
JSONDecoder::decode_json("project", project, root_obj, true);
struct tm t;
if (parse_iso8601(expires_iso8601.c_str(), &t)) {
token.expires = internal_timegm(&t);
} else {
token.expires = 0;
throw JSONDecoder::err("Failed to parse ISO8601 expiration date"
"from Keystone response.");
}
}
void rgw::keystone::TokenEnvelope::decode_v2(JSONObj* const root_obj)
{
JSONDecoder::decode_json("user", user, root_obj, true);
JSONDecoder::decode_json("token", token, root_obj, true);
roles = user.roles_v2;
project = token.tenant_v2;
}
/* This utility function shouldn't conflict with the overload of std::to_string
* provided by string_ref since Boost 1.54 as it's defined outside of the std
* namespace. I hope we'll remove it soon - just after merging the Matt's PR
* for bundled Boost. It would allow us to forget that CentOS 7 has Boost 1.53. */
static inline std::string to_string(const std::string_view& s)
{
return std::string(s.data(), s.length());
}
void rgw::keystone::AdminTokenRequestVer2::dump(Formatter* const f) const
{
f->open_object_section("token_request");
f->open_object_section("auth");
f->open_object_section("passwordCredentials");
encode_json("username", ::to_string(conf.get_admin_user()), f);
encode_json("password", ::to_string(conf.get_admin_password()), f);
f->close_section();
encode_json("tenantName", ::to_string(conf.get_admin_tenant()), f);
f->close_section();
f->close_section();
}
void rgw::keystone::AdminTokenRequestVer3::dump(Formatter* const f) const
{
f->open_object_section("token_request");
f->open_object_section("auth");
f->open_object_section("identity");
f->open_array_section("methods");
f->dump_string("", "password");
f->close_section();
f->open_object_section("password");
f->open_object_section("user");
f->open_object_section("domain");
encode_json("name", ::to_string(conf.get_admin_domain()), f);
f->close_section();
encode_json("name", ::to_string(conf.get_admin_user()), f);
encode_json("password", ::to_string(conf.get_admin_password()), f);
f->close_section();
f->close_section();
f->close_section();
f->open_object_section("scope");
f->open_object_section("project");
if (! conf.get_admin_project().empty()) {
encode_json("name", ::to_string(conf.get_admin_project()), f);
} else {
encode_json("name", ::to_string(conf.get_admin_tenant()), f);
}
f->open_object_section("domain");
encode_json("name", ::to_string(conf.get_admin_domain()), f);
f->close_section();
f->close_section();
f->close_section();
f->close_section();
f->close_section();
}
void rgw::keystone::BarbicanTokenRequestVer2::dump(Formatter* const f) const
{
f->open_object_section("token_request");
f->open_object_section("auth");
f->open_object_section("passwordCredentials");
encode_json("username", cct->_conf->rgw_keystone_barbican_user, f);
encode_json("password", cct->_conf->rgw_keystone_barbican_password, f);
f->close_section();
encode_json("tenantName", cct->_conf->rgw_keystone_barbican_tenant, f);
f->close_section();
f->close_section();
}
void rgw::keystone::BarbicanTokenRequestVer3::dump(Formatter* const f) const
{
f->open_object_section("token_request");
f->open_object_section("auth");
f->open_object_section("identity");
f->open_array_section("methods");
f->dump_string("", "password");
f->close_section();
f->open_object_section("password");
f->open_object_section("user");
f->open_object_section("domain");
encode_json("name", cct->_conf->rgw_keystone_barbican_domain, f);
f->close_section();
encode_json("name", cct->_conf->rgw_keystone_barbican_user, f);
encode_json("password", cct->_conf->rgw_keystone_barbican_password, f);
f->close_section();
f->close_section();
f->close_section();
f->open_object_section("scope");
f->open_object_section("project");
if (!cct->_conf->rgw_keystone_barbican_project.empty()) {
encode_json("name", cct->_conf->rgw_keystone_barbican_project, f);
} else {
encode_json("name", cct->_conf->rgw_keystone_barbican_tenant, f);
}
f->open_object_section("domain");
encode_json("name", cct->_conf->rgw_keystone_barbican_domain, f);
f->close_section();
f->close_section();
f->close_section();
f->close_section();
f->close_section();
}
| 21,435 | 29.276836 | 108 |
cc
|
null |
ceph-main/src/rgw/rgw_keystone.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <atomic>
#include <string_view>
#include <type_traits>
#include <utility>
#include <boost/optional.hpp>
#include "rgw_common.h"
#include "rgw_http_client.h"
#include "common/ceph_mutex.h"
#include "global/global_init.h"
bool rgw_is_pki_token(const std::string& token);
void rgw_get_token_id(const std::string& token, std::string& token_id);
static inline std::string rgw_get_token_id(const std::string& token)
{
std::string token_id;
rgw_get_token_id(token, token_id);
return token_id;
}
namespace rgw {
namespace keystone {
enum class ApiVersion {
VER_2,
VER_3
};
class Config {
protected:
Config() = default;
virtual ~Config() = default;
public:
virtual std::string get_endpoint_url() const noexcept = 0;
virtual ApiVersion get_api_version() const noexcept = 0;
virtual std::string get_admin_token() const noexcept = 0;
virtual std::string_view get_admin_user() const noexcept = 0;
virtual std::string get_admin_password() const noexcept = 0;
virtual std::string_view get_admin_tenant() const noexcept = 0;
virtual std::string_view get_admin_project() const noexcept = 0;
virtual std::string_view get_admin_domain() const noexcept = 0;
};
class CephCtxConfig : public Config {
protected:
CephCtxConfig() = default;
virtual ~CephCtxConfig() = default;
const static std::string empty;
public:
static CephCtxConfig& get_instance() {
static CephCtxConfig instance;
return instance;
}
std::string get_endpoint_url() const noexcept override;
ApiVersion get_api_version() const noexcept override;
std::string get_admin_token() const noexcept override;
std::string_view get_admin_user() const noexcept override {
return g_ceph_context->_conf->rgw_keystone_admin_user;
}
std::string get_admin_password() const noexcept override;
std::string_view get_admin_tenant() const noexcept override {
return g_ceph_context->_conf->rgw_keystone_admin_tenant;
}
std::string_view get_admin_project() const noexcept override {
return g_ceph_context->_conf->rgw_keystone_admin_project;
}
std::string_view get_admin_domain() const noexcept override {
return g_ceph_context->_conf->rgw_keystone_admin_domain;
}
};
class TokenEnvelope;
class TokenCache;
class Service {
public:
class RGWKeystoneHTTPTransceiver : public RGWHTTPTransceiver {
public:
RGWKeystoneHTTPTransceiver(CephContext * const cct,
const std::string& method,
const std::string& url,
bufferlist * const token_body_bl)
: RGWHTTPTransceiver(cct, method, url, token_body_bl,
cct->_conf->rgw_keystone_verify_ssl,
{ "X-Subject-Token" }) {
}
const header_value_t& get_subject_token() const {
try {
return get_header_value("X-Subject-Token");
} catch (std::out_of_range&) {
static header_value_t empty_val;
return empty_val;
}
}
};
typedef RGWKeystoneHTTPTransceiver RGWValidateKeystoneToken;
typedef RGWKeystoneHTTPTransceiver RGWGetKeystoneAdminToken;
static int get_admin_token(const DoutPrefixProvider *dpp,
CephContext* const cct,
TokenCache& token_cache,
const Config& config,
std::string& token);
static int issue_admin_token_request(const DoutPrefixProvider *dpp,
CephContext* const cct,
const Config& config,
TokenEnvelope& token);
static int get_keystone_barbican_token(const DoutPrefixProvider *dpp,
CephContext * const cct,
std::string& token);
};
class TokenEnvelope {
public:
class Domain {
public:
std::string id;
std::string name;
void decode_json(JSONObj *obj);
};
class Project {
public:
Domain domain;
std::string id;
std::string name;
void decode_json(JSONObj *obj);
};
class Token {
public:
Token() : expires(0) { }
std::string id;
time_t expires;
Project tenant_v2;
void decode_json(JSONObj *obj);
};
class Role {
public:
Role() : is_admin(false), is_reader(false) { }
Role(const Role &r) {
id = r.id;
name = r.name;
is_admin = r.is_admin;
is_reader = r.is_reader;
}
std::string id;
std::string name;
bool is_admin;
bool is_reader;
void decode_json(JSONObj *obj);
};
class User {
public:
std::string id;
std::string name;
Domain domain;
std::list<Role> roles_v2;
void decode_json(JSONObj *obj);
};
Token token;
Project project;
User user;
std::list<Role> roles;
void decode_v3(JSONObj* obj);
void decode_v2(JSONObj* obj);
public:
/* We really need the default ctor because of the internals of TokenCache. */
TokenEnvelope() = default;
void set_expires(time_t expires) { token.expires = expires; }
time_t get_expires() const { return token.expires; }
const std::string& get_domain_id() const {return project.domain.id;};
const std::string& get_domain_name() const {return project.domain.name;};
const std::string& get_project_id() const {return project.id;};
const std::string& get_project_name() const {return project.name;};
const std::string& get_user_id() const {return user.id;};
const std::string& get_user_name() const {return user.name;};
bool has_role(const std::string& r) const;
bool expired() const {
const uint64_t now = ceph_clock_now().sec();
return std::cmp_greater_equal(now, get_expires());
}
int parse(const DoutPrefixProvider *dpp, CephContext* cct,
const std::string& token_str,
ceph::buffer::list& bl /* in */,
ApiVersion version);
void update_roles(const std::vector<std::string> & admin,
const std::vector<std::string> & reader);
};
class TokenCache {
struct token_entry {
TokenEnvelope token;
std::list<std::string>::iterator lru_iter;
};
std::atomic<bool> down_flag = { false };
const boost::intrusive_ptr<CephContext> cct;
std::string admin_token_id;
std::string barbican_token_id;
std::map<std::string, token_entry> tokens;
std::map<std::string, token_entry> service_tokens;
std::list<std::string> tokens_lru;
std::list<std::string> service_tokens_lru;
ceph::mutex lock = ceph::make_mutex("rgw::keystone::TokenCache");
const size_t max;
explicit TokenCache(const rgw::keystone::Config& config)
: cct(g_ceph_context),
max(cct->_conf->rgw_keystone_token_cache_size) {
}
~TokenCache() {
down_flag = true;
}
public:
TokenCache(const TokenCache&) = delete;
void operator=(const TokenCache&) = delete;
template<class ConfigT>
static TokenCache& get_instance() {
static_assert(std::is_base_of<rgw::keystone::Config, ConfigT>::value,
"ConfigT must be a subclass of rgw::keystone::Config");
/* In C++11 this is thread safe. */
static TokenCache instance(ConfigT::get_instance());
return instance;
}
bool find(const std::string& token_id, TokenEnvelope& token);
bool find_service(const std::string& token_id, TokenEnvelope& token);
boost::optional<TokenEnvelope> find(const std::string& token_id) {
TokenEnvelope token_envlp;
if (find(token_id, token_envlp)) {
return token_envlp;
}
return boost::none;
}
boost::optional<TokenEnvelope> find_service(const std::string& token_id) {
TokenEnvelope token_envlp;
if (find_service(token_id, token_envlp)) {
return token_envlp;
}
return boost::none;
}
bool find_admin(TokenEnvelope& token);
bool find_barbican(TokenEnvelope& token);
void add(const std::string& token_id, const TokenEnvelope& token);
void add_service(const std::string& token_id, const TokenEnvelope& token);
void add_admin(const TokenEnvelope& token);
void add_barbican(const TokenEnvelope& token);
void invalidate(const DoutPrefixProvider *dpp, const std::string& token_id);
bool going_down() const;
private:
void add_locked(const std::string& token_id, const TokenEnvelope& token,
std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru);
bool find_locked(const std::string& token_id, TokenEnvelope& token,
std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru);
};
class AdminTokenRequest {
public:
virtual ~AdminTokenRequest() = default;
virtual void dump(Formatter* f) const = 0;
};
class AdminTokenRequestVer2 : public AdminTokenRequest {
const Config& conf;
public:
explicit AdminTokenRequestVer2(const Config& conf)
: conf(conf) {
}
void dump(Formatter *f) const override;
};
class AdminTokenRequestVer3 : public AdminTokenRequest {
const Config& conf;
public:
explicit AdminTokenRequestVer3(const Config& conf)
: conf(conf) {
}
void dump(Formatter *f) const override;
};
class BarbicanTokenRequestVer2 : public AdminTokenRequest {
CephContext *cct;
public:
explicit BarbicanTokenRequestVer2(CephContext * const _cct)
: cct(_cct) {
}
void dump(Formatter *f) const override;
};
class BarbicanTokenRequestVer3 : public AdminTokenRequest {
CephContext *cct;
public:
explicit BarbicanTokenRequestVer3(CephContext * const _cct)
: cct(_cct) {
}
void dump(Formatter *f) const override;
};
}; /* namespace keystone */
}; /* namespace rgw */
| 9,715 | 27.162319 | 99 |
h
|
null |
ceph-main/src/rgw/rgw_kmip_client.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "common/Thread.h"
#include "include/compat.h"
#include "common/errno.h"
#include "rgw_common.h"
#include "rgw_kmip_client.h"
#include <atomic>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
RGWKMIPManager *rgw_kmip_manager;
int
RGWKMIPTransceiver::wait(optional_yield y)
{
if (done)
return ret;
std::unique_lock l{lock};
if (!done)
cond.wait(l);
if (ret) {
lderr(cct) << "kmip process failed, " << ret << dendl;
}
return ret;
}
int
RGWKMIPTransceiver::send()
{
int r = rgw_kmip_manager->add_request(this);
if (r < 0) {
lderr(cct) << "kmip send failed, " << r << dendl;
}
return r;
}
int
RGWKMIPTransceiver::process(optional_yield y)
{
int r = send();
if (r < 0)
return r;
return wait(y);
}
RGWKMIPTransceiver::~RGWKMIPTransceiver()
{
int i;
if (out)
free(out);
out = nullptr;
if (outlist->strings) {
for (i = 0; i < outlist->string_count; ++i) {
free(outlist->strings[i]);
}
free(outlist->strings);
outlist->strings = 0;
}
if (outkey->data) {
::ceph::crypto::zeroize_for_security(outkey->data, outkey->keylen);
free(outkey->data);
outkey->data = 0;
}
}
void
rgw_kmip_client_init(RGWKMIPManager &m)
{
rgw_kmip_manager = &m;
rgw_kmip_manager->start();
}
void
rgw_kmip_client_cleanup()
{
rgw_kmip_manager->stop();
delete rgw_kmip_manager;
}
| 1,493 | 17 | 71 |
cc
|
null |
ceph-main/src/rgw/rgw_kmip_client.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
class RGWKMIPManager;
class RGWKMIPTransceiver {
public:
enum kmip_operation {
CREATE,
LOCATE,
GET,
GET_ATTRIBUTES,
GET_ATTRIBUTE_LIST,
DESTROY
};
CephContext *cct;
kmip_operation operation;
char *name = 0;
char *unique_id = 0;
// output - must free
char *out = 0; // unique_id, several
struct { // unique_ids, locate
char **strings;
int string_count;
} outlist[1] = {{0, 0}};
struct { // key, get
unsigned char *data;
int keylen;
} outkey[1] = {0, 0};
// end must free
int ret;
bool done;
ceph::mutex lock = ceph::make_mutex("rgw_kmip_req::lock");
ceph::condition_variable cond;
int wait(optional_yield y);
RGWKMIPTransceiver(CephContext * const cct,
kmip_operation operation)
: cct(cct),
operation(operation),
ret(-EDOM),
done(false)
{}
~RGWKMIPTransceiver();
int send();
int process(optional_yield y);
};
class RGWKMIPManager {
protected:
CephContext *cct;
bool is_started = false;
RGWKMIPManager(CephContext *cct) : cct(cct) {};
public:
virtual ~RGWKMIPManager() { };
virtual int start() = 0;
virtual void stop() = 0;
virtual int add_request(RGWKMIPTransceiver*) = 0;
};
void rgw_kmip_client_init(RGWKMIPManager &);
void rgw_kmip_client_cleanup();
| 1,404 | 20.287879 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_kmip_client_impl.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <boost/intrusive/list.hpp>
#include <atomic>
#include <mutex>
#include <string.h>
#include "include/compat.h"
#include "common/errno.h"
#include "rgw_common.h"
#include "rgw_kmip_client.h"
#include "rgw_kmip_client_impl.h"
#include <openssl/err.h>
#include <openssl/ssl.h>
extern "C" {
#include "kmip.h"
#include "kmip_bio.h"
#include "kmip_memset.h"
};
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
static enum kmip_version protocol_version = KMIP_1_0;
struct RGWKmipHandle {
int uses;
mono_time lastuse;
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
KMIP kmip_ctx[1];
TextString textstrings[2];
UsernamePasswordCredential upc[1];
Credential credential[1];
int need_to_free_kmip;
size_t buffer_blocks, buffer_block_size, buffer_total_size;
uint8 *encoding;
explicit RGWKmipHandle() :
uses(0), ctx(0), ssl(0), bio(0),
need_to_free_kmip(0),
encoding(0) {
memset(kmip_ctx, 0, sizeof kmip_ctx);
memset(textstrings, 0, sizeof textstrings);
memset(upc, 0, sizeof upc);
memset(credential, 0, sizeof credential);
};
};
struct RGWKmipWorker: public Thread {
RGWKMIPManagerImpl &m;
RGWKmipWorker(RGWKMIPManagerImpl& m) : m(m) {}
void *entry() override;
void signal() {
std::lock_guard l{m.lock};
m.cond.notify_all();
}
};
static void
kmip_free_handle_stuff(RGWKmipHandle *kmip)
{
if (kmip->encoding) {
kmip_free_buffer(kmip->kmip_ctx,
kmip->encoding,
kmip->buffer_total_size);
kmip_set_buffer(kmip->kmip_ctx, NULL, 0);
}
if (kmip->need_to_free_kmip)
kmip_destroy(kmip->kmip_ctx);
if (kmip->bio)
BIO_free_all(kmip->bio);
if (kmip->ctx)
SSL_CTX_free(kmip->ctx);
}
class RGWKmipHandleBuilder {
private:
CephContext *cct;
const char *clientcert = 0;
const char *clientkey = 0;
const char *capath = 0;
const char *host = 0;
const char *portstring = 0;
const char *username = 0;
const char *password = 0;
public:
RGWKmipHandleBuilder(CephContext *cct) : cct(cct) {};
RGWKmipHandleBuilder& set_clientcert(const std::string &v) {
const char *s = v.c_str();
if (*s) {
clientcert = s;
}
return *this;
}
RGWKmipHandleBuilder& set_clientkey(const std::string &v) {
const char *s = v.c_str();
if (*s) {
clientkey = s;
}
return *this;
}
RGWKmipHandleBuilder& set_capath(const std::string &v) {
const char *s = v.c_str();
if (*s) {
capath = s;
}
return *this;
}
RGWKmipHandleBuilder& set_host(const char *v) {
host = v;
return *this;
}
RGWKmipHandleBuilder& set_portstring(const char *v) {
portstring = v;
return *this;
}
RGWKmipHandleBuilder& set_username(const std::string &v) {
const char *s = v.c_str();
if (*s) {
username = s;
}
return *this;
}
RGWKmipHandleBuilder& set_password(const std::string& v) {
const char *s = v.c_str();
if (*s) {
password = s;
}
return *this;
}
RGWKmipHandle *build() const;
};
static int
kmip_write_an_error_helper(const char *s, size_t l, void *u) {
CephContext *cct = (CephContext *)u;
std::string_view es(s, l);
lderr(cct) << es << dendl;
return l;
}
void
ERR_print_errors_ceph(CephContext *cct)
{
ERR_print_errors_cb(kmip_write_an_error_helper, cct);
}
RGWKmipHandle *
RGWKmipHandleBuilder::build() const
{
int failed = 1;
RGWKmipHandle *r = new RGWKmipHandle();
TextString *up = 0;
size_t ns;
r->ctx = SSL_CTX_new(TLS_client_method());
if (!clientcert)
;
else if (SSL_CTX_use_certificate_file(r->ctx, clientcert, SSL_FILETYPE_PEM) != 1) {
lderr(cct) << "ERROR: can't load client cert from "
<< clientcert << dendl;
ERR_print_errors_ceph(cct);
goto Done;
}
if (!clientkey)
;
else if (SSL_CTX_use_PrivateKey_file(r->ctx, clientkey,
SSL_FILETYPE_PEM) != 1) {
lderr(cct) << "ERROR: can't load client key from "
<< clientkey << dendl;
ERR_print_errors_ceph(cct);
goto Done;
}
if (!capath)
;
else if (SSL_CTX_load_verify_locations(r->ctx, capath, NULL) != 1) {
lderr(cct) << "ERROR: can't load cacert from "
<< capath << dendl;
ERR_print_errors_ceph(cct);
goto Done;
}
r->bio = BIO_new_ssl_connect(r->ctx);
if (!r->bio) {
lderr(cct) << "BIO_new_ssl_connect failed" << dendl;
goto Done;
}
BIO_get_ssl(r->bio, &r->ssl);
SSL_set_mode(r->ssl, SSL_MODE_AUTO_RETRY);
BIO_set_conn_hostname(r->bio, host);
BIO_set_conn_port(r->bio, portstring);
if (BIO_do_connect(r->bio) != 1) {
lderr(cct) << "BIO_do_connect failed to " << host
<< ":" << portstring << dendl;
ERR_print_errors_ceph(cct);
goto Done;
}
// setup kmip
kmip_init(r->kmip_ctx, NULL, 0, protocol_version);
r->need_to_free_kmip = 1;
r->buffer_blocks = 1;
r->buffer_block_size = 1024;
r->encoding = static_cast<uint8*>(r->kmip_ctx->calloc_func(
r->kmip_ctx->state, r->buffer_blocks, r->buffer_block_size));
if (!r->encoding) {
lderr(cct) << "kmip buffer alloc failed: "
<< r->buffer_blocks <<
" * " << r->buffer_block_size << dendl;
goto Done;
}
ns = r->buffer_blocks * r->buffer_block_size;
kmip_set_buffer(r->kmip_ctx, r->encoding, ns);
r->buffer_total_size = ns;
up = r->textstrings;
if (username) {
memset(r->upc, 0, sizeof *r->upc);
up->value = (char *) username;
up->size = strlen(username);
r->upc->username = up++;
if (password) {
up->value = (char *) password;
up->size = strlen(password);
r->upc->password = up++;
}
r->credential->credential_type = KMIP_CRED_USERNAME_AND_PASSWORD;
r->credential->credential_value = r->upc;
int i = kmip_add_credential(r->kmip_ctx, r->credential);
if (i != KMIP_OK) {
fprintf(stderr,"failed to add credential to kmip\n");
goto Done;
}
}
failed = 0;
Done:
if (!failed)
;
else if (!r)
;
else {
kmip_free_handle_stuff(r);
delete r;
r = 0;
}
return r;
}
struct RGWKmipHandles : public Thread {
CephContext *cct;
ceph::mutex cleaner_lock = ceph::make_mutex("RGWKmipHandles::cleaner_lock");
std::vector<RGWKmipHandle*> saved_kmip;
int cleaner_shutdown;
bool cleaner_active = false;
ceph::condition_variable cleaner_cond;
RGWKmipHandles(CephContext *cct) :
cct(cct), cleaner_shutdown{0} {
}
RGWKmipHandle* get_kmip_handle();
void release_kmip_handle_now(RGWKmipHandle* kmip);
void release_kmip_handle(RGWKmipHandle* kmip);
void flush_kmip_handles();
int do_one_entry(RGWKMIPTransceiver &element);
void* entry();
void start();
void stop();
};
RGWKmipHandle*
RGWKmipHandles::get_kmip_handle()
{
RGWKmipHandle* kmip = 0;
const char *hostaddr = cct->_conf->rgw_crypt_kmip_addr.c_str();
{
std::lock_guard lock{cleaner_lock};
if (!saved_kmip.empty()) {
kmip = *saved_kmip.begin();
saved_kmip.erase(saved_kmip.begin());
}
}
if (!kmip && hostaddr) {
char *hosttemp = strdup(hostaddr);
char *port = strchr(hosttemp, ':');
if (port)
*port++ = 0;
kmip = RGWKmipHandleBuilder{cct}
.set_clientcert(cct->_conf->rgw_crypt_kmip_client_cert)
.set_clientkey(cct->_conf->rgw_crypt_kmip_client_key)
.set_capath(cct->_conf->rgw_crypt_kmip_ca_path)
.set_host(hosttemp)
.set_portstring(port ? port : "5696")
.set_username(cct->_conf->rgw_crypt_kmip_username)
.set_password(cct->_conf->rgw_crypt_kmip_password)
.build();
free(hosttemp);
}
return kmip;
}
void
RGWKmipHandles::release_kmip_handle_now(RGWKmipHandle* kmip)
{
kmip_free_handle_stuff(kmip);
delete kmip;
}
#define MAXIDLE 5
void
RGWKmipHandles::release_kmip_handle(RGWKmipHandle* kmip)
{
if (cleaner_shutdown) {
release_kmip_handle_now(kmip);
} else {
std::lock_guard lock{cleaner_lock};
kmip->lastuse = mono_clock::now();
saved_kmip.insert(saved_kmip.begin(), 1, kmip);
}
}
void*
RGWKmipHandles::entry()
{
RGWKmipHandle* kmip;
std::unique_lock lock{cleaner_lock};
for (;;) {
if (cleaner_shutdown) {
if (saved_kmip.empty())
break;
} else {
cleaner_cond.wait_for(lock, std::chrono::seconds(MAXIDLE));
}
mono_time now = mono_clock::now();
while (!saved_kmip.empty()) {
auto cend = saved_kmip.end();
--cend;
kmip = *cend;
if (!cleaner_shutdown && now - kmip->lastuse
< std::chrono::seconds(MAXIDLE))
break;
saved_kmip.erase(cend);
release_kmip_handle_now(kmip);
}
}
return nullptr;
}
void
RGWKmipHandles::start()
{
std::lock_guard lock{cleaner_lock};
if (!cleaner_active) {
cleaner_active = true;
this->create("KMIPcleaner"); // len<16!!!
}
}
void
RGWKmipHandles::stop()
{
std::unique_lock lock{cleaner_lock};
cleaner_shutdown = 1;
cleaner_cond.notify_all();
if (cleaner_active) {
lock.unlock();
this->join();
cleaner_active = false;
}
}
void
RGWKmipHandles::flush_kmip_handles()
{
stop();
join();
if (!saved_kmip.empty()) {
ldout(cct, 0) << "ERROR: " << __func__ << " failed final cleanup" << dendl;
}
saved_kmip.shrink_to_fit();
}
int
RGWKMIPManagerImpl::start()
{
if (worker) {
lderr(cct) << "kmip worker already started" << dendl;
return -1;
}
worker = new RGWKmipWorker(*this);
worker->create("kmip worker");
return 0;
}
void
RGWKMIPManagerImpl::stop()
{
going_down = true;
if (worker) {
worker->signal();
worker->join();
delete worker;
worker = 0;
}
}
int
RGWKMIPManagerImpl::add_request(RGWKMIPTransceiver *req)
{
std::unique_lock l{lock};
if (going_down)
return -ECANCELED;
// requests is a boost::intrusive::list, which manages pointers and does not copy the instance
// coverity[leaked_storage:SUPPRESS]
requests.push_back(*new Request{*req});
l.unlock();
if (worker)
worker->signal();
return 0;
}
int
RGWKmipHandles::do_one_entry(RGWKMIPTransceiver &element)
{
auto h = get_kmip_handle();
std::unique_lock l{element.lock};
Attribute a[8], *ap;
TextString nvalue[1], uvalue[1];
Name nattr[1];
enum cryptographic_algorithm alg = KMIP_CRYPTOALG_AES;
int32 length = 256;
int32 mask = KMIP_CRYPTOMASK_ENCRYPT | KMIP_CRYPTOMASK_DECRYPT;
size_t ns;
ProtocolVersion pv[1];
RequestHeader rh[1];
RequestMessage rm[1];
Authentication auth[1];
ResponseMessage resp_m[1];
int i;
union {
CreateRequestPayload create_req[1];
LocateRequestPayload locate_req[1];
GetRequestPayload get_req[1];
GetAttributeListRequestPayload lsattrs_req[1];
GetAttributesRequestPayload getattrs_req[1];
} u[1];
RequestBatchItem rbi[1];
TemplateAttribute ta[1];
const char *what = "?";
int need_to_free_response = 0;
char *response = NULL;
int response_size = 0;
enum result_status rs;
ResponseBatchItem *req;
if (!h) {
element.ret = -ERR_SERVICE_UNAVAILABLE;
return element.ret;
}
memset(a, 0, sizeof *a);
for (i = 0; i < (int)(sizeof a/sizeof *a); ++i)
kmip_init_attribute(a+i);
ap = a;
switch(element.operation) {
case RGWKMIPTransceiver::CREATE:
ap->type = KMIP_ATTR_CRYPTOGRAPHIC_ALGORITHM;
ap->value = &alg;
++ap;
ap->type = KMIP_ATTR_CRYPTOGRAPHIC_LENGTH;
ap->value = &length;
++ap;
ap->type = KMIP_ATTR_CRYPTOGRAPHIC_USAGE_MASK;
ap->value = &mask;
++ap;
break;
default:
break;
}
if (element.name) {
memset(nvalue, 0, sizeof *nvalue);
nvalue->value = element.name;
nvalue->size = strlen(element.name);
memset(nattr, 0, sizeof *nattr);
nattr->value = nvalue;
nattr->type = KMIP_NAME_UNINTERPRETED_TEXT_STRING;
ap->type = KMIP_ATTR_NAME;
ap->value = nattr;
++ap;
}
if (element.unique_id) {
memset(uvalue, 0, sizeof *uvalue);
uvalue->value = element.unique_id;
uvalue->size = strlen(element.unique_id);
}
memset(pv, 0, sizeof *pv);
memset(rh, 0, sizeof *rh);
memset(rm, 0, sizeof *rm);
memset(auth, 0, sizeof *auth);
memset(resp_m, 0, sizeof *resp_m);
kmip_init_protocol_version(pv, h->kmip_ctx->version);
kmip_init_request_header(rh);
rh->protocol_version = pv;
rh->maximum_response_size = h->kmip_ctx->max_message_size;
rh->time_stamp = time(NULL);
rh->batch_count = 1;
memset(rbi, 0, sizeof *rbi);
kmip_init_request_batch_item(rbi);
memset(u, 0, sizeof *u);
rbi->request_payload = u;
switch(element.operation) {
case RGWKMIPTransceiver::CREATE:
memset(ta, 0, sizeof *ta);
ta->attributes = a;
ta->attribute_count = ap-a;
u->create_req->object_type = KMIP_OBJTYPE_SYMMETRIC_KEY;
u->create_req->template_attribute = ta;
rbi->operation = KMIP_OP_CREATE;
what = "create";
break;
case RGWKMIPTransceiver::GET:
if (element.unique_id)
u->get_req->unique_identifier = uvalue;
rbi->operation = KMIP_OP_GET;
what = "get";
break;
case RGWKMIPTransceiver::LOCATE:
if (ap > a) {
u->locate_req->attributes = a;
u->locate_req->attribute_count = ap - a;
}
rbi->operation = KMIP_OP_LOCATE;
what = "locate";
break;
case RGWKMIPTransceiver::GET_ATTRIBUTES:
case RGWKMIPTransceiver::GET_ATTRIBUTE_LIST:
case RGWKMIPTransceiver::DESTROY:
default:
lderr(cct) << "Missing operation logic op=" << element.operation << dendl;
element.ret = -EINVAL;
goto Done;
}
rm->request_header = rh;
rm->batch_items = rbi;
rm->batch_count = 1;
if (h->kmip_ctx->credential_list) {
LinkedListItem *item = h->kmip_ctx->credential_list->head;
if (item) {
auth->credential = (Credential *)item->data;
rh->authentication = auth;
}
}
for (;;) {
i = kmip_encode_request_message(h->kmip_ctx, rm);
if (i != KMIP_ERROR_BUFFER_FULL) break;
h->kmip_ctx->free_func(h->kmip_ctx->state, h->encoding);
h->encoding = 0;
++h->buffer_blocks;
h->encoding = static_cast<uint8*>(h->kmip_ctx->calloc_func(h->kmip_ctx->state, h->buffer_blocks, h->buffer_block_size));
if (!h->encoding) {
lderr(cct) << "kmip buffer alloc failed: "
<< h->buffer_blocks
<< " * " << h->buffer_block_size << dendl;
element.ret = -ENOMEM;
goto Done;
}
ns = h->buffer_blocks * h->buffer_block_size;
kmip_set_buffer(h->kmip_ctx, h->encoding, ns);
h->buffer_total_size = ns;
}
if (i != KMIP_OK) {
lderr(cct) << " Failed to encode " << what
<< " request; err=" << i
<< " ctx error message " << h->kmip_ctx->error_message
<< dendl;
element.ret = -EINVAL;
goto Done;
}
i = kmip_bio_send_request_encoding(h->kmip_ctx, h->bio,
(char*)h->encoding,
h->kmip_ctx->index - h->kmip_ctx->buffer,
&response, &response_size);
if (i < 0) {
lderr(cct) << "Problem sending request to " << what << " " << i << " context error message " << h->kmip_ctx->error_message << dendl;
element.ret = -EINVAL;
goto Done;
}
kmip_free_buffer(h->kmip_ctx, h->encoding,
h->buffer_total_size);
h->encoding = 0;
kmip_set_buffer(h->kmip_ctx, response, response_size);
need_to_free_response = 1;
i = kmip_decode_response_message(h->kmip_ctx, resp_m);
if (i != KMIP_OK) {
lderr(cct) << "Failed to decode " << what << " " << i << " context error message " << h->kmip_ctx->error_message << dendl;
element.ret = -EINVAL;
goto Done;
}
if (resp_m->batch_count != 1) {
lderr(cct) << "Failed; weird response count doing " << what << " " << resp_m->batch_count << dendl;
element.ret = -EINVAL;
goto Done;
}
req = resp_m->batch_items;
rs = req->result_status;
if (rs != KMIP_STATUS_SUCCESS) {
lderr(cct) << "Failed; result status not success " << rs << dendl;
element.ret = -EINVAL;
goto Done;
}
if (req->operation != rbi->operation) {
lderr(cct) << "Failed; response operation mismatch, got " << req->operation << " expected " << rbi->operation << dendl;
element.ret = -EINVAL;
goto Done;
}
switch(req->operation)
{
case KMIP_OP_CREATE: {
CreateResponsePayload *pld = (CreateResponsePayload *)req->response_payload;
element.out = static_cast<char *>(malloc(pld->unique_identifier->size+1));
memcpy(element.out, pld->unique_identifier->value, pld->unique_identifier->size);
element.out[pld->unique_identifier->size] = 0;
} break;
case KMIP_OP_LOCATE: {
LocateResponsePayload *pld = (LocateResponsePayload *)req->response_payload;
char **list = static_cast<char **>(malloc(sizeof (char*) * (1 + pld->unique_identifiers_count)));
for (i = 0; i < pld->unique_identifiers_count; ++i) {
list[i] = static_cast<char *>(malloc(pld->unique_identifiers[i].size+1));
memcpy(list[i], pld->unique_identifiers[i].value, pld->unique_identifiers[i].size);
list[i][pld->unique_identifiers[i].size] = 0;
}
list[i] = 0;
element.outlist->strings = list;
element.outlist->string_count = pld->unique_identifiers_count;
} break;
case KMIP_OP_GET: {
GetResponsePayload *pld = (GetResponsePayload *)req->response_payload;
element.out = static_cast<char *>(malloc(pld->unique_identifier->size+1));
memcpy(element.out, pld->unique_identifier->value, pld->unique_identifier->size);
element.out[pld->unique_identifier->size] = 0;
if (pld->object_type != KMIP_OBJTYPE_SYMMETRIC_KEY) {
lderr(cct) << "get: expected symmetric key got " << pld->object_type << dendl;
element.ret = -EINVAL;
goto Done;
}
KeyBlock *kp = static_cast<SymmetricKey *>(pld->object)->key_block;
ByteString *bp;
if (kp->key_format_type != KMIP_KEYFORMAT_RAW) {
lderr(cct) << "get: expected raw key fromat got " << kp->key_format_type << dendl;
element.ret = -EINVAL;
goto Done;
}
KeyValue *kv = static_cast<KeyValue *>(kp->key_value);
bp = static_cast<ByteString*>(kv->key_material);
element.outkey->data = static_cast<unsigned char *>(malloc(bp->size));
element.outkey->keylen = bp->size;
memcpy(element.outkey->data, bp->value, bp->size);
} break;
case KMIP_OP_GET_ATTRIBUTES: {
GetAttributesResponsePayload *pld = (GetAttributesResponsePayload *)req->response_payload;
element.out = static_cast<char *>(malloc(pld->unique_identifier->size+1));
memcpy(element.out, pld->unique_identifier->value, pld->unique_identifier->size);
element.out[pld->unique_identifier->size] = 0;
} break;
case KMIP_OP_GET_ATTRIBUTE_LIST: {
GetAttributeListResponsePayload *pld = (GetAttributeListResponsePayload *)req->response_payload;
element.out = static_cast<char *>(malloc(pld->unique_identifier->size+1));
memcpy(element.out, pld->unique_identifier->value, pld->unique_identifier->size);
element.out[pld->unique_identifier->size] = 0;
} break;
case KMIP_OP_DESTROY: {
DestroyResponsePayload *pld = (DestroyResponsePayload *)req->response_payload;
element.out = static_cast<char *>(malloc(pld->unique_identifier->size+1));
memcpy(element.out, pld->unique_identifier->value, pld->unique_identifier->size);
element.out[pld->unique_identifier->size] = 0;
} break;
default:
lderr(cct) << "Missing response logic op=" << element.operation << dendl;
element.ret = -EINVAL;
goto Done;
}
element.ret = 0;
Done:
if (need_to_free_response)
kmip_free_response_message(h->kmip_ctx, resp_m);
element.done = true;
element.cond.notify_all();
release_kmip_handle(h);
return element.ret;
}
void *
RGWKmipWorker::entry()
{
std::unique_lock entry_lock{m.lock};
ldout(m.cct, 10) << __func__ << " start" << dendl;
RGWKmipHandles handles{m.cct};
handles.start();
while (!m.going_down) {
if (m.requests.empty()) {
m.cond.wait_for(entry_lock, std::chrono::seconds(MAXIDLE));
continue;
}
auto iter = m.requests.begin();
auto element = *iter;
m.requests.erase(iter);
entry_lock.unlock();
(void) handles.do_one_entry(element.details);
entry_lock.lock();
}
for (;;) {
if (m.requests.empty()) break;
auto iter = m.requests.begin();
auto element = std::move(*iter);
m.requests.erase(iter);
element.details.ret = -666;
element.details.done = true;
element.details.cond.notify_all();
}
handles.stop();
ldout(m.cct, 10) << __func__ << " finish" << dendl;
return nullptr;
}
| 20,379 | 26.879617 | 136 |
cc
|
null |
ceph-main/src/rgw/rgw_kmip_client_impl.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
struct RGWKmipWorker;
class RGWKMIPManagerImpl: public RGWKMIPManager {
protected:
ceph::mutex lock = ceph::make_mutex("RGWKMIPManager");
ceph::condition_variable cond;
struct Request : boost::intrusive::list_base_hook<> {
boost::intrusive::list_member_hook<> req_hook;
RGWKMIPTransceiver &details;
Request(RGWKMIPTransceiver &details) : details(details) {}
};
boost::intrusive::list<Request, boost::intrusive::member_hook< Request,
boost::intrusive::list_member_hook<>, &Request::req_hook>> requests;
bool going_down = false;
RGWKmipWorker *worker = 0;
public:
RGWKMIPManagerImpl(CephContext *cct) : RGWKMIPManager(cct) {};
int add_request(RGWKMIPTransceiver *);
int start();
void stop();
friend RGWKmipWorker;
};
| 874 | 30.25 | 73 |
h
|
null |
ceph-main/src/rgw/rgw_kms.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/**
* Server-side encryption integrations with Key Management Systems (SSE-KMS)
*/
#include <sys/stat.h>
#include "include/str_map.h"
#include "common/safe_io.h"
#include "rgw/rgw_crypt.h"
#include "rgw/rgw_keystone.h"
#include "rgw/rgw_b64.h"
#include "rgw/rgw_kms.h"
#include "rgw/rgw_kmip_client.h"
#include <rapidjson/allocators.h>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include "rapidjson/error/error.h"
#include "rapidjson/error/en.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
using namespace rgw;
#ifndef FORTEST_VIRTUAL
#define FORTEST_VIRTUAL /**/
#endif
/**
* Memory pool for use with rapidjson. This version
* carefully zeros out all memory before returning it to
* the system.
*/
#define ALIGNTYPE double
#define MINCHUNKSIZE 4096
class ZeroPoolAllocator {
private:
struct element {
struct element *next;
int size;
char data[4];
} *b;
size_t left;
public:
static const bool kNeedFree { false };
ZeroPoolAllocator(){
b = 0;
left = 0;
}
~ZeroPoolAllocator(){
element *p;
while ((p = b)) {
b = p->next;
memset(p->data, 0, p->size);
free(p);
}
}
void * Malloc(size_t size) {
void *r;
if (!size) return 0;
size = (size + sizeof(ALIGNTYPE)-1)&(-sizeof(ALIGNTYPE));
if (size > left) {
size_t ns { size };
if (ns < MINCHUNKSIZE) ns = MINCHUNKSIZE;
element *nw { (element *) malloc(sizeof *b + ns) };
if (!nw) {
// std::cerr << "out of memory" << std::endl;
return 0;
}
left = ns - sizeof *b;
nw->size = ns;
nw->next = b;
b = nw;
}
left -= size;
r = static_cast<void*>(b->data + left);
return r;
}
void* Realloc(void* p, size_t old, size_t nw) {
void *r = nullptr;
if (nw) r = malloc(nw);
if (nw > old) nw = old;
if (r && old) memcpy(r, p, nw);
return r;
}
static void Free(void *p) {
ceph_assert(0 == "Free should not be called");
}
private:
//! Copy constructor is not permitted.
ZeroPoolAllocator(const ZeroPoolAllocator& rhs) /* = delete */;
//! Copy assignment operator is not permitted.
ZeroPoolAllocator& operator=(const ZeroPoolAllocator& rhs) /* = delete */;
};
typedef rapidjson::GenericDocument<rapidjson::UTF8<>,
ZeroPoolAllocator,
rapidjson::CrtAllocator
> ZeroPoolDocument;
typedef rapidjson::GenericValue<rapidjson::UTF8<>, ZeroPoolAllocator> ZeroPoolValue;
/**
* Construct a full URL string by concatenating a "base" URL with another path,
* ensuring there is one and only one forward slash between them. If path is
* empty, the URL is not changed.
*/
static void concat_url(std::string &url, std::string path) {
bool url_has_slash = !url.empty() && url.back() == '/';
if (!path.empty()) {
if (url_has_slash && path.front() == '/') {
url.pop_back();
} else if (!url_has_slash && path.front() != '/') {
url.push_back('/');
}
url.append(path);
}
}
/**
* Determine if a string (url) ends with a given suffix.
* Must deal with (ignore) trailing slashes.
*/
static bool string_ends_maybe_slash(std::string_view hay,
std::string_view needle)
{
auto hay_len { hay.size() };
auto needle_len { needle.size() };
if (hay_len < needle_len) return false;
auto hay_suffix_start { hay.data() + (hay_len - needle_len) };
while (hay_len > needle_len && hay[hay_len-1] == '/') {
--hay_len;
--hay_suffix_start;
}
std::string_view hay_suffix { hay_suffix_start, needle_len };
return hay_suffix == needle;
}
template<typename E, typename A = ZeroPoolAllocator>
static inline void
add_name_val_to_obj(std::string &n, std::string &v, rapidjson::GenericValue<E,A> &d,
A &allocator)
{
rapidjson::GenericValue<E,A> name, val;
name.SetString(n.c_str(), n.length(), allocator);
val.SetString(v.c_str(), v.length(), allocator);
d.AddMember(name, val, allocator);
}
template<typename E, typename A = ZeroPoolAllocator>
static inline void
add_name_val_to_obj(std::string &n, bool v, rapidjson::GenericValue<E,A> &d,
A &allocator)
{
rapidjson::GenericValue<E,A> name, val;
name.SetString(n.c_str(), n.length(), allocator);
val.SetBool(v);
d.AddMember(name, val, allocator);
}
template<typename E, typename A = ZeroPoolAllocator>
static inline void
add_name_val_to_obj(const char *n, std::string &v, rapidjson::GenericValue<E,A> &d,
A &allocator)
{
std::string ns{n, strlen(n) };
add_name_val_to_obj(ns, v, d, allocator);
}
template<typename E, typename A = ZeroPoolAllocator>
static inline void
add_name_val_to_obj(const char *n, bool v, rapidjson::GenericValue<E,A> &d,
A &allocator)
{
std::string ns{n, strlen(n) };
add_name_val_to_obj(ns, v, d, allocator);
}
typedef std::map<std::string, std::string> EngineParmMap;
class SSEContext {
protected:
virtual ~SSEContext(){};
public:
virtual const std::string & backend() = 0;
virtual const std::string & addr() = 0;
virtual const std::string & auth() = 0;
virtual const std::string & k_namespace() = 0;
virtual const std::string & prefix() = 0;
virtual const std::string & secret_engine() = 0;
virtual const std::string & ssl_cacert() = 0;
virtual const std::string & ssl_clientcert() = 0;
virtual const std::string & ssl_clientkey() = 0;
virtual const std::string & token_file() = 0;
virtual const bool verify_ssl() = 0;
};
class VaultSecretEngine: public SecretEngine {
protected:
CephContext *cct;
SSEContext & kctx;
int load_token_from_file(const DoutPrefixProvider *dpp, std::string *vault_token)
{
int res = 0;
std::string token_file = kctx.token_file();
if (token_file.empty()) {
ldpp_dout(dpp, 0) << "ERROR: Vault token file not set in rgw_crypt_vault_token_file" << dendl;
return -EINVAL;
}
ldpp_dout(dpp, 20) << "Vault token file: " << token_file << dendl;
struct stat token_st;
if (stat(token_file.c_str(), &token_st) != 0) {
ldpp_dout(dpp, 0) << "ERROR: Vault token file '" << token_file << "' not found " << dendl;
return -ENOENT;
}
if (token_st.st_mode & (S_IRWXG | S_IRWXO)) {
ldpp_dout(dpp, 0) << "ERROR: Vault token file '" << token_file << "' permissions are "
<< "too open, it must not be accessible by other users" << dendl;
return -EACCES;
}
char buf[2048];
res = safe_read_file("", token_file.c_str(), buf, sizeof(buf));
if (res < 0) {
if (-EACCES == res) {
ldpp_dout(dpp, 0) << "ERROR: Permission denied reading Vault token file" << dendl;
} else {
ldpp_dout(dpp, 0) << "ERROR: Failed to read Vault token file with error " << res << dendl;
}
return res;
}
// drop trailing newlines
while (res && isspace(buf[res-1])) {
--res;
}
vault_token->assign(std::string{buf, static_cast<size_t>(res)});
memset(buf, 0, sizeof(buf));
::ceph::crypto::zeroize_for_security(buf, sizeof(buf));
return res;
}
FORTEST_VIRTUAL
int send_request(const DoutPrefixProvider *dpp, const char *method, std::string_view infix,
std::string_view key_id,
const std::string& postdata,
bufferlist &secret_bl)
{
int res;
string vault_token = "";
if (RGW_SSE_KMS_VAULT_AUTH_TOKEN == kctx.auth()){
ldpp_dout(dpp, 0) << "Loading Vault Token from filesystem" << dendl;
res = load_token_from_file(dpp, &vault_token);
if (res < 0){
return res;
}
}
std::string secret_url = kctx.addr();
if (secret_url.empty()) {
ldpp_dout(dpp, 0) << "ERROR: Vault address not set in rgw_crypt_vault_addr" << dendl;
return -EINVAL;
}
concat_url(secret_url, kctx.prefix());
concat_url(secret_url, std::string(infix));
concat_url(secret_url, std::string(key_id));
RGWHTTPTransceiver secret_req(cct, method, secret_url, &secret_bl);
if (postdata.length()) {
secret_req.set_post_data(postdata);
secret_req.set_send_length(postdata.length());
}
secret_req.append_header("X-Vault-Token", vault_token);
if (!vault_token.empty()){
secret_req.append_header("X-Vault-Token", vault_token);
vault_token.replace(0, vault_token.length(), vault_token.length(), '\000');
}
string vault_namespace = kctx.k_namespace();
if (!vault_namespace.empty()){
ldpp_dout(dpp, 20) << "Vault Namespace: " << vault_namespace << dendl;
secret_req.append_header("X-Vault-Namespace", vault_namespace);
}
secret_req.set_verify_ssl(kctx.verify_ssl());
if (!kctx.ssl_cacert().empty()) {
secret_req.set_ca_path(kctx.ssl_cacert());
}
if (!kctx.ssl_clientcert().empty()) {
secret_req.set_client_cert(kctx.ssl_clientcert());
}
if (!kctx.ssl_clientkey().empty()) {
secret_req.set_client_key(kctx.ssl_clientkey());
}
res = secret_req.process(null_yield);
if (res < 0) {
ldpp_dout(dpp, 0) << "ERROR: Request to Vault failed with error " << res << dendl;
return res;
}
if (secret_req.get_http_status() ==
RGWHTTPTransceiver::HTTP_STATUS_UNAUTHORIZED) {
ldpp_dout(dpp, 0) << "ERROR: Vault request failed authorization" << dendl;
return -EACCES;
}
ldpp_dout(dpp, 20) << "Request to Vault returned " << res << " and HTTP status "
<< secret_req.get_http_status() << dendl;
return res;
}
int send_request(const DoutPrefixProvider *dpp, std::string_view key_id, bufferlist &secret_bl)
{
return send_request(dpp, "GET", "", key_id, string{}, secret_bl);
}
int decode_secret(const DoutPrefixProvider *dpp, std::string encoded, std::string& actual_key){
try {
actual_key = from_base64(encoded);
} catch (std::exception&) {
ldpp_dout(dpp, 0) << "ERROR: Failed to base64 decode key retrieved from Vault" << dendl;
return -EINVAL;
}
memset(encoded.data(), 0, encoded.length());
return 0;
}
public:
VaultSecretEngine(CephContext *_c, SSEContext & _k) : cct(_c), kctx(_k) {
}
};
class TransitSecretEngine: public VaultSecretEngine {
public:
int compat;
static const int COMPAT_NEW_ONLY = 0;
static const int COMPAT_OLD_AND_NEW = 1;
static const int COMPAT_ONLY_OLD = 2;
static const int COMPAT_UNSET = -1;
private:
EngineParmMap parms;
int get_key_version(std::string_view key_id, string& version)
{
size_t pos = 0;
pos = key_id.rfind("/");
if (pos != std::string_view::npos){
std::string_view token = key_id.substr(pos+1, key_id.length()-pos);
if (!token.empty() && token.find_first_not_of("0123456789") == std::string_view::npos){
version.assign(std::string(token));
return 0;
}
}
return -1;
}
public:
TransitSecretEngine(CephContext *cct, SSEContext & kctx, EngineParmMap parms): VaultSecretEngine(cct, kctx), parms(parms) {
compat = COMPAT_UNSET;
for (auto& e: parms) {
if (e.first == "compat") {
if (e.second.empty()) {
compat = COMPAT_OLD_AND_NEW;
} else {
size_t ep;
compat = std::stoi(e.second, &ep);
if (ep != e.second.length()) {
lderr(cct) << "warning: vault transit secrets engine : compat="
<< e.second << " trailing junk? (ignored)" << dendl;
}
}
continue;
}
lderr(cct) << "ERROR: vault transit secrets engine : parameter "
<< e.first << "=" << e.second << " ignored" << dendl;
}
if (compat == COMPAT_UNSET) {
std::string_view v { kctx.prefix() };
if (string_ends_maybe_slash(v,"/export/encryption-key")) {
compat = COMPAT_ONLY_OLD;
} else {
compat = COMPAT_NEW_ONLY;
}
}
}
int get_key(const DoutPrefixProvider *dpp, std::string_view key_id, std::string& actual_key)
{
ZeroPoolDocument d;
ZeroPoolValue *v;
string version;
bufferlist secret_bl;
if (get_key_version(key_id, version) < 0){
ldpp_dout(dpp, 20) << "Missing or invalid key version" << dendl;
return -EINVAL;
}
int res = send_request(dpp, "GET", compat == COMPAT_ONLY_OLD ? "" : "/export/encryption-key",
key_id, string{}, secret_bl);
if (res < 0) {
return res;
}
ldpp_dout(dpp, 20) << "Parse response into JSON Object" << dendl;
secret_bl.append('\0');
rapidjson::StringStream isw(secret_bl.c_str());
d.ParseStream<>(isw);
if (d.HasParseError()) {
ldpp_dout(dpp, 0) << "ERROR: Failed to parse JSON response from Vault: "
<< rapidjson::GetParseError_En(d.GetParseError()) << dendl;
return -EINVAL;
}
secret_bl.zero();
const char *elements[] = {"data", "keys", version.c_str()};
v = &d;
for (auto &elem: elements) {
if (!v->IsObject()) {
v = nullptr;
break;
}
auto endr { v->MemberEnd() };
auto itr { v->FindMember(elem) };
if (itr == endr) {
v = nullptr;
break;
}
v = &itr->value;
}
if (!v || !v->IsString()) {
ldpp_dout(dpp, 0) << "ERROR: Key not found in JSON response from Vault using Transit Engine" << dendl;
return -EINVAL;
}
return decode_secret(dpp, v->GetString(), actual_key);
}
int make_actual_key(const DoutPrefixProvider *dpp, map<string, bufferlist>& attrs, std::string& actual_key)
{
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
if (compat == COMPAT_ONLY_OLD) return get_key(dpp, key_id, actual_key);
if (key_id.find("/") != std::string::npos) {
ldpp_dout(dpp, 0) << "sorry, can't allow / in keyid" << dendl;
return -EINVAL;
}
/*
data: {context }
post to prefix + /datakey/plaintext/ + key_id
jq: .data.plaintext -> key
jq: .data.ciphertext -> (to-be) named attribute
return decode_secret(json_obj, actual_key)
*/
std::string context = get_str_attribute(attrs, RGW_ATTR_CRYPT_CONTEXT);
ZeroPoolDocument d { rapidjson::kObjectType };
auto &allocator { d.GetAllocator() };
bufferlist secret_bl;
add_name_val_to_obj("context", context, d, allocator);
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> writer(buf);
if (!d.Accept(writer)) {
ldpp_dout(dpp, 0) << "ERROR: can't make json for vault" << dendl;
return -EINVAL;
}
std::string post_data { buf.GetString() };
int res = send_request(dpp, "POST", "/datakey/plaintext/", key_id,
post_data, secret_bl);
if (res < 0) {
return res;
}
ldpp_dout(dpp, 20) << "Parse response into JSON Object" << dendl;
secret_bl.append('\0');
rapidjson::StringStream isw(secret_bl.c_str());
d.SetNull();
d.ParseStream<>(isw);
if (d.HasParseError()) {
ldpp_dout(dpp, 0) << "ERROR: Failed to parse JSON response from Vault: "
<< rapidjson::GetParseError_En(d.GetParseError()) << dendl;
return -EINVAL;
}
secret_bl.zero();
if (!d.IsObject()) {
ldpp_dout(dpp, 0) << "ERROR: response from Vault is not an object" << dendl;
return -EINVAL;
}
{
auto data_itr { d.FindMember("data") };
if (data_itr == d.MemberEnd()) {
ldpp_dout(dpp, 0) << "ERROR: no .data in response from Vault" << dendl;
return -EINVAL;
}
auto ciphertext_itr { data_itr->value.FindMember("ciphertext") };
auto plaintext_itr { data_itr->value.FindMember("plaintext") };
if (ciphertext_itr == data_itr->value.MemberEnd()) {
ldpp_dout(dpp, 0) << "ERROR: no .data.ciphertext in response from Vault" << dendl;
return -EINVAL;
}
if (plaintext_itr == data_itr->value.MemberEnd()) {
ldpp_dout(dpp, 0) << "ERROR: no .data.plaintext in response from Vault" << dendl;
return -EINVAL;
}
auto &ciphertext_v { ciphertext_itr->value };
auto &plaintext_v { plaintext_itr->value };
if (!ciphertext_v.IsString()) {
ldpp_dout(dpp, 0) << "ERROR: .data.ciphertext not a string in response from Vault" << dendl;
return -EINVAL;
}
if (!plaintext_v.IsString()) {
ldpp_dout(dpp, 0) << "ERROR: .data.plaintext not a string in response from Vault" << dendl;
return -EINVAL;
}
set_attr(attrs, RGW_ATTR_CRYPT_DATAKEY, ciphertext_v.GetString());
return decode_secret(dpp, plaintext_v.GetString(), actual_key);
}
}
int reconstitute_actual_key(const DoutPrefixProvider *dpp, map<string, bufferlist>& attrs, std::string& actual_key)
{
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
std::string wrapped_key = get_str_attribute(attrs, RGW_ATTR_CRYPT_DATAKEY);
if (compat == COMPAT_ONLY_OLD || key_id.rfind("/") != std::string::npos) {
return get_key(dpp, key_id, actual_key);
}
/*
.data.ciphertext <- (to-be) named attribute
data: {context ciphertext}
post to prefix + /decrypt/ + key_id
jq: .data.plaintext
return decode_secret(json_obj, actual_key)
*/
std::string context = get_str_attribute(attrs, RGW_ATTR_CRYPT_CONTEXT);
ZeroPoolDocument d { rapidjson::kObjectType };
auto &allocator { d.GetAllocator() };
bufferlist secret_bl;
add_name_val_to_obj("context", context, d, allocator);
add_name_val_to_obj("ciphertext", wrapped_key, d, allocator);
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> writer(buf);
if (!d.Accept(writer)) {
ldpp_dout(dpp, 0) << "ERROR: can't make json for vault" << dendl;
return -EINVAL;
}
std::string post_data { buf.GetString() };
int res = send_request(dpp, "POST", "/decrypt/", key_id,
post_data, secret_bl);
if (res < 0) {
return res;
}
ldpp_dout(dpp, 20) << "Parse response into JSON Object" << dendl;
secret_bl.append('\0');
rapidjson::StringStream isw(secret_bl.c_str());
d.SetNull();
d.ParseStream<>(isw);
if (d.HasParseError()) {
ldpp_dout(dpp, 0) << "ERROR: Failed to parse JSON response from Vault: "
<< rapidjson::GetParseError_En(d.GetParseError()) << dendl;
return -EINVAL;
}
secret_bl.zero();
if (!d.IsObject()) {
ldpp_dout(dpp, 0) << "ERROR: response from Vault is not an object" << dendl;
return -EINVAL;
}
{
auto data_itr { d.FindMember("data") };
if (data_itr == d.MemberEnd()) {
ldpp_dout(dpp, 0) << "ERROR: no .data in response from Vault" << dendl;
return -EINVAL;
}
auto plaintext_itr { data_itr->value.FindMember("plaintext") };
if (plaintext_itr == data_itr->value.MemberEnd()) {
ldpp_dout(dpp, 0) << "ERROR: no .data.plaintext in response from Vault" << dendl;
return -EINVAL;
}
auto &plaintext_v { plaintext_itr->value };
if (!plaintext_v.IsString()) {
ldpp_dout(dpp, 0) << "ERROR: .data.plaintext not a string in response from Vault" << dendl;
return -EINVAL;
}
return decode_secret(dpp, plaintext_v.GetString(), actual_key);
}
}
int create_bucket_key(const DoutPrefixProvider *dpp, const std::string& key_name)
{
/*
.data.ciphertext <- (to-be) named attribute
data: {"type": "chacha20-poly1305", "derived": true}
post to prefix + key_name
empty output.
*/
ZeroPoolDocument d { rapidjson::kObjectType };
auto &allocator { d.GetAllocator() };
bufferlist dummy_bl;
std::string chacha20_poly1305 { "chacha20-poly1305" };
add_name_val_to_obj("type", chacha20_poly1305, d, allocator);
add_name_val_to_obj("derived", true, d, allocator);
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> writer(buf);
if (!d.Accept(writer)) {
ldpp_dout(dpp, 0) << "ERROR: can't make json for vault" << dendl;
return -EINVAL;
}
std::string post_data { buf.GetString() };
int res = send_request(dpp, "POST", "/keys/", key_name,
post_data, dummy_bl);
if (res < 0) {
return res;
}
if (dummy_bl.length() != 0) {
ldpp_dout(dpp, 0) << "ERROR: unexpected response from Vault making a key: "
<< dummy_bl
<< dendl;
}
return 0;
}
int delete_bucket_key(const DoutPrefixProvider *dpp, const std::string& key_name)
{
/*
/keys/<keyname>/config
data: {"deletion_allowed": true}
post to prefix + key_name
empty output.
*/
ZeroPoolDocument d { rapidjson::kObjectType };
auto &allocator { d.GetAllocator() };
bufferlist dummy_bl;
std::ostringstream path_temp;
path_temp << "/keys/";
path_temp << key_name;
std::string delete_path { path_temp.str() };
path_temp << "/config";
std::string config_path { path_temp.str() };
add_name_val_to_obj("deletion_allowed", true, d, allocator);
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> writer(buf);
if (!d.Accept(writer)) {
ldpp_dout(dpp, 0) << "ERROR: can't make json for vault" << dendl;
return -EINVAL;
}
std::string post_data { buf.GetString() };
int res = send_request(dpp, "POST", "", config_path,
post_data, dummy_bl);
if (res < 0) {
return res;
}
if (dummy_bl.length() != 0) {
ldpp_dout(dpp, 0) << "ERROR: unexpected response from Vault marking key to delete: "
<< dummy_bl
<< dendl;
return -EINVAL;
}
res = send_request(dpp, "DELETE", "", delete_path,
string{}, dummy_bl);
if (res < 0) {
return res;
}
if (dummy_bl.length() != 0) {
ldpp_dout(dpp, 0) << "ERROR: unexpected response from Vault deleting key: "
<< dummy_bl
<< dendl;
return -EINVAL;
}
return 0;
}
};
class KvSecretEngine: public VaultSecretEngine {
public:
KvSecretEngine(CephContext *cct, SSEContext & kctx, EngineParmMap parms): VaultSecretEngine(cct, kctx){
if (!parms.empty()) {
lderr(cct) << "ERROR: vault kv secrets engine takes no parameters (ignoring them)" << dendl;
}
}
virtual ~KvSecretEngine(){}
int get_key(const DoutPrefixProvider *dpp, std::string_view key_id, std::string& actual_key){
ZeroPoolDocument d;
ZeroPoolValue *v;
bufferlist secret_bl;
int res = send_request(dpp, key_id, secret_bl);
if (res < 0) {
return res;
}
ldpp_dout(dpp, 20) << "Parse response into JSON Object" << dendl;
secret_bl.append('\0');
rapidjson::StringStream isw(secret_bl.c_str());
d.ParseStream<>(isw);
if (d.HasParseError()) {
ldpp_dout(dpp, 0) << "ERROR: Failed to parse JSON response from Vault: "
<< rapidjson::GetParseError_En(d.GetParseError()) << dendl;
return -EINVAL;
}
secret_bl.zero();
static const char *elements[] = {"data", "data", "key"};
v = &d;
for (auto &elem: elements) {
if (!v->IsObject()) {
v = nullptr;
break;
}
auto endr { v->MemberEnd() };
auto itr { v->FindMember(elem) };
if (itr == endr) {
v = nullptr;
break;
}
v = &itr->value;
}
if (!v || !v->IsString()) {
ldpp_dout(dpp, 0) << "ERROR: Key not found in JSON response from Vault using KV Engine" << dendl;
return -EINVAL;
}
return decode_secret(dpp, v->GetString(), actual_key);
}
};
class KmipSecretEngine;
class KmipGetTheKey {
private:
CephContext *cct;
std::string work;
bool failed = false;
int ret;
protected:
KmipGetTheKey(CephContext *cct) : cct(cct) {}
KmipGetTheKey& keyid_to_keyname(std::string_view key_id);
KmipGetTheKey& get_uniqueid_for_keyname();
int get_key_for_uniqueid(std::string &);
friend KmipSecretEngine;
};
KmipGetTheKey&
KmipGetTheKey::keyid_to_keyname(std::string_view key_id)
{
work = cct->_conf->rgw_crypt_kmip_kms_key_template;
std::string keyword = "$keyid";
std::string replacement = std::string(key_id);
size_t pos = 0;
if (work.length() == 0) {
work = std::move(replacement);
} else {
while (pos < work.length()) {
pos = work.find(keyword, pos);
if (pos == std::string::npos) break;
work.replace(pos, keyword.length(), replacement);
pos += key_id.length();
}
}
return *this;
}
KmipGetTheKey&
KmipGetTheKey::get_uniqueid_for_keyname()
{
RGWKMIPTransceiver secret_req(cct, RGWKMIPTransceiver::LOCATE);
secret_req.name = work.data();
ret = secret_req.process(null_yield);
if (ret < 0) {
failed = true;
} else if (!secret_req.outlist->string_count) {
ret = -ENOENT;
lderr(cct) << "error: locate returned no results for "
<< secret_req.name << dendl;
failed = true;
} else if (secret_req.outlist->string_count != 1) {
ret = -EINVAL;
lderr(cct) << "error: locate found "
<< secret_req.outlist->string_count
<< " results for " << secret_req.name << dendl;
failed = true;
} else {
work = std::string(secret_req.outlist->strings[0]);
}
return *this;
}
int
KmipGetTheKey::get_key_for_uniqueid(std::string& actual_key)
{
if (failed) return ret;
RGWKMIPTransceiver secret_req(cct, RGWKMIPTransceiver::GET);
secret_req.unique_id = work.data();
ret = secret_req.process(null_yield);
if (ret < 0) {
failed = true;
} else {
actual_key = std::string((char*)(secret_req.outkey->data),
secret_req.outkey->keylen);
}
return ret;
}
class KmipSecretEngine: public SecretEngine {
protected:
CephContext *cct;
public:
KmipSecretEngine(CephContext *cct) {
this->cct = cct;
}
int get_key(const DoutPrefixProvider *dpp, std::string_view key_id, std::string& actual_key)
{
int r;
r = KmipGetTheKey{cct}
.keyid_to_keyname(key_id)
.get_uniqueid_for_keyname()
.get_key_for_uniqueid(actual_key);
return r;
}
};
static int get_actual_key_from_conf(const DoutPrefixProvider* dpp,
CephContext *cct,
std::string_view key_id,
std::string_view key_selector,
std::string& actual_key)
{
int res = 0;
static map<string,string> str_map = get_str_map(
cct->_conf->rgw_crypt_s3_kms_encryption_keys);
map<string, string>::iterator it = str_map.find(std::string(key_id));
if (it == str_map.end())
return -EINVAL;
std::string master_key;
try {
master_key = from_base64((*it).second);
} catch (std::exception&) {
ldpp_dout(dpp, 5) << "ERROR: get_actual_key_from_conf invalid encryption key id "
<< "which contains character that is not base64 encoded."
<< dendl;
return -EINVAL;
}
if (master_key.length() == AES_256_KEYSIZE) {
uint8_t _actual_key[AES_256_KEYSIZE];
if (AES_256_ECB_encrypt(dpp, cct,
reinterpret_cast<const uint8_t*>(master_key.c_str()), AES_256_KEYSIZE,
reinterpret_cast<const uint8_t*>(key_selector.data()),
_actual_key, AES_256_KEYSIZE)) {
actual_key = std::string((char*)&_actual_key[0], AES_256_KEYSIZE);
} else {
res = -EIO;
}
::ceph::crypto::zeroize_for_security(_actual_key, sizeof(_actual_key));
} else {
ldpp_dout(dpp, 20) << "Wrong size for key=" << key_id << dendl;
res = -EIO;
}
return res;
}
static int request_key_from_barbican(const DoutPrefixProvider *dpp,
CephContext *cct,
std::string_view key_id,
const std::string& barbican_token,
std::string& actual_key) {
int res;
std::string secret_url = cct->_conf->rgw_barbican_url;
if (secret_url.empty()) {
ldpp_dout(dpp, 0) << "ERROR: conf rgw_barbican_url is not set" << dendl;
return -EINVAL;
}
concat_url(secret_url, "/v1/secrets/");
concat_url(secret_url, std::string(key_id));
bufferlist secret_bl;
RGWHTTPTransceiver secret_req(cct, "GET", secret_url, &secret_bl);
secret_req.append_header("Accept", "application/octet-stream");
secret_req.append_header("X-Auth-Token", barbican_token);
res = secret_req.process(null_yield);
if (res < 0) {
return res;
}
if (secret_req.get_http_status() ==
RGWHTTPTransceiver::HTTP_STATUS_UNAUTHORIZED) {
return -EACCES;
}
if (secret_req.get_http_status() >=200 &&
secret_req.get_http_status() < 300 &&
secret_bl.length() == AES_256_KEYSIZE) {
actual_key.assign(secret_bl.c_str(), secret_bl.length());
secret_bl.zero();
} else {
res = -EACCES;
}
return res;
}
static int get_actual_key_from_barbican(const DoutPrefixProvider *dpp,
CephContext *cct,
std::string_view key_id,
std::string& actual_key)
{
int res = 0;
std::string token;
if (rgw::keystone::Service::get_keystone_barbican_token(dpp, cct, token) < 0) {
ldpp_dout(dpp, 5) << "Failed to retrieve token for Barbican" << dendl;
return -EINVAL;
}
res = request_key_from_barbican(dpp, cct, key_id, token, actual_key);
if (res != 0) {
ldpp_dout(dpp, 5) << "Failed to retrieve secret from Barbican:" << key_id << dendl;
}
return res;
}
std::string config_to_engine_and_parms(CephContext *cct,
const char* which,
std::string& secret_engine_str,
EngineParmMap& secret_engine_parms)
{
std::ostringstream oss;
std::vector<std::string> secret_engine_v;
std::string secret_engine;
get_str_vec(secret_engine_str, " ", secret_engine_v);
cct->_conf.early_expand_meta(secret_engine_str, &oss);
auto meta_errors {oss.str()};
if (meta_errors.length()) {
meta_errors.erase(meta_errors.find_last_not_of("\n")+1);
lderr(cct) << "ERROR: while expanding " << which << ": "
<< meta_errors << dendl;
}
for (auto& e: secret_engine_v) {
if (!secret_engine.length()) {
secret_engine = std::move(e);
continue;
}
auto p { e.find('=') };
if (p == std::string::npos) {
secret_engine_parms.emplace(std::move(e), "");
continue;
}
std::string key{ e.substr(0,p) };
std::string val{ e.substr(p+1) };
secret_engine_parms.emplace(std::move(key), std::move(val));
}
return secret_engine;
}
static int get_actual_key_from_vault(const DoutPrefixProvider *dpp,
CephContext *cct,
SSEContext & kctx,
map<string, bufferlist>& attrs,
std::string& actual_key, bool make_it)
{
std::string secret_engine_str = kctx.secret_engine();
EngineParmMap secret_engine_parms;
auto secret_engine { config_to_engine_and_parms(
cct, "rgw_crypt_vault_secret_engine",
secret_engine_str, secret_engine_parms) };
ldpp_dout(dpp, 20) << "Vault authentication method: " << kctx.auth() << dendl;
ldpp_dout(dpp, 20) << "Vault Secrets Engine: " << secret_engine << dendl;
if (RGW_SSE_KMS_VAULT_SE_KV == secret_engine){
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
KvSecretEngine engine(cct, kctx, std::move(secret_engine_parms));
return engine.get_key(dpp, key_id, actual_key);
}
else if (RGW_SSE_KMS_VAULT_SE_TRANSIT == secret_engine){
TransitSecretEngine engine(cct, kctx, std::move(secret_engine_parms));
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
return make_it
? engine.make_actual_key(dpp, attrs, actual_key)
: engine.reconstitute_actual_key(dpp, attrs, actual_key);
}
else {
ldpp_dout(dpp, 0) << "Missing or invalid secret engine" << dendl;
return -EINVAL;
}
}
static int make_actual_key_from_vault(const DoutPrefixProvider *dpp,
CephContext *cct,
SSEContext & kctx,
map<string, bufferlist>& attrs,
std::string& actual_key)
{
return get_actual_key_from_vault(dpp, cct, kctx, attrs, actual_key, true);
}
static int reconstitute_actual_key_from_vault(const DoutPrefixProvider *dpp,
CephContext *cct,
SSEContext & kctx,
map<string, bufferlist>& attrs,
std::string& actual_key)
{
return get_actual_key_from_vault(dpp, cct, kctx, attrs, actual_key, false);
}
static int get_actual_key_from_kmip(const DoutPrefixProvider *dpp,
CephContext *cct,
std::string_view key_id,
std::string& actual_key)
{
std::string secret_engine = RGW_SSE_KMS_KMIP_SE_KV;
if (RGW_SSE_KMS_KMIP_SE_KV == secret_engine){
KmipSecretEngine engine(cct);
return engine.get_key(dpp, key_id, actual_key);
}
else{
ldpp_dout(dpp, 0) << "Missing or invalid secret engine" << dendl;
return -EINVAL;
}
}
class KMSContext : public SSEContext {
CephContext *cct;
public:
KMSContext(CephContext*_cct) : cct{_cct} {};
~KMSContext() override {};
const std::string & backend() override {
return cct->_conf->rgw_crypt_s3_kms_backend;
};
const std::string & addr() override {
return cct->_conf->rgw_crypt_vault_addr;
};
const std::string & auth() override {
return cct->_conf->rgw_crypt_vault_auth;
};
const std::string & k_namespace() override {
return cct->_conf->rgw_crypt_vault_namespace;
};
const std::string & prefix() override {
return cct->_conf->rgw_crypt_vault_prefix;
};
const std::string & secret_engine() override {
return cct->_conf->rgw_crypt_vault_secret_engine;
};
const std::string & ssl_cacert() override {
return cct->_conf->rgw_crypt_vault_ssl_cacert;
};
const std::string & ssl_clientcert() override {
return cct->_conf->rgw_crypt_vault_ssl_clientcert;
};
const std::string & ssl_clientkey() override {
return cct->_conf->rgw_crypt_vault_ssl_clientkey;
};
const std::string & token_file() override {
return cct->_conf->rgw_crypt_vault_token_file;
};
const bool verify_ssl() override {
return cct->_conf->rgw_crypt_vault_verify_ssl;
};
};
class SseS3Context : public SSEContext {
CephContext *cct;
public:
static const std::string sse_s3_secret_engine;
SseS3Context(CephContext*_cct) : cct{_cct} {};
~SseS3Context(){};
const std::string & backend() override {
return cct->_conf->rgw_crypt_sse_s3_backend;
};
const std::string & addr() override {
return cct->_conf->rgw_crypt_sse_s3_vault_addr;
};
const std::string & auth() override {
return cct->_conf->rgw_crypt_sse_s3_vault_auth;
};
const std::string & k_namespace() override {
return cct->_conf->rgw_crypt_sse_s3_vault_namespace;
};
const std::string & prefix() override {
return cct->_conf->rgw_crypt_sse_s3_vault_prefix;
};
const std::string & secret_engine() override {
return cct->_conf->rgw_crypt_sse_s3_vault_secret_engine;
};
const std::string & ssl_cacert() override {
return cct->_conf->rgw_crypt_sse_s3_vault_ssl_cacert;
};
const std::string & ssl_clientcert() override {
return cct->_conf->rgw_crypt_sse_s3_vault_ssl_clientcert;
};
const std::string & ssl_clientkey() override {
return cct->_conf->rgw_crypt_sse_s3_vault_ssl_clientkey;
};
const std::string & token_file() override {
return cct->_conf->rgw_crypt_sse_s3_vault_token_file;
};
const bool verify_ssl() override {
return cct->_conf->rgw_crypt_sse_s3_vault_verify_ssl;
};
};
int reconstitute_actual_key_from_kms(const DoutPrefixProvider *dpp, CephContext *cct,
map<string, bufferlist>& attrs,
std::string& actual_key)
{
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
KMSContext kctx { cct };
const std::string &kms_backend { kctx.backend() };
ldpp_dout(dpp, 20) << "Getting KMS encryption key for key " << key_id << dendl;
ldpp_dout(dpp, 20) << "SSE-KMS backend is " << kms_backend << dendl;
if (RGW_SSE_KMS_BACKEND_BARBICAN == kms_backend) {
return get_actual_key_from_barbican(dpp, cct, key_id, actual_key);
}
if (RGW_SSE_KMS_BACKEND_VAULT == kms_backend) {
return reconstitute_actual_key_from_vault(dpp, cct, kctx, attrs, actual_key);
}
if (RGW_SSE_KMS_BACKEND_KMIP == kms_backend) {
return get_actual_key_from_kmip(dpp, cct, key_id, actual_key);
}
if (RGW_SSE_KMS_BACKEND_TESTING == kms_backend) {
std::string key_selector = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYSEL);
return get_actual_key_from_conf(dpp, cct, key_id, key_selector, actual_key);
}
ldpp_dout(dpp, 0) << "ERROR: Invalid rgw_crypt_s3_kms_backend: " << kms_backend << dendl;
return -EINVAL;
}
int make_actual_key_from_kms(const DoutPrefixProvider *dpp, CephContext *cct,
map<string, bufferlist>& attrs,
std::string& actual_key)
{
KMSContext kctx { cct };
const std::string &kms_backend { kctx.backend() };
if (RGW_SSE_KMS_BACKEND_VAULT == kms_backend)
return make_actual_key_from_vault(dpp, cct, kctx, attrs, actual_key);
return reconstitute_actual_key_from_kms(dpp, cct, attrs, actual_key);
}
int reconstitute_actual_key_from_sse_s3(const DoutPrefixProvider *dpp,
CephContext *cct,
map<string, bufferlist>& attrs,
std::string& actual_key)
{
std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID);
SseS3Context kctx { cct };
const std::string &kms_backend { kctx.backend() };
ldpp_dout(dpp, 20) << "Getting SSE-S3 encryption key for key " << key_id << dendl;
ldpp_dout(dpp, 20) << "SSE-KMS backend is " << kms_backend << dendl;
if (RGW_SSE_KMS_BACKEND_VAULT == kms_backend) {
return reconstitute_actual_key_from_vault(dpp, cct, kctx, attrs, actual_key);
}
ldpp_dout(dpp, 0) << "ERROR: Invalid rgw_crypt_sse_s3_backend: " << kms_backend << dendl;
return -EINVAL;
}
int make_actual_key_from_sse_s3(const DoutPrefixProvider *dpp,
CephContext *cct,
map<string, bufferlist>& attrs,
std::string& actual_key)
{
SseS3Context kctx { cct };
const std::string kms_backend { kctx.backend() };
if (RGW_SSE_KMS_BACKEND_VAULT != kms_backend) {
ldpp_dout(dpp, 0) << "ERROR: Unsupported rgw_crypt_sse_s3_backend: " << kms_backend << dendl;
return -EINVAL;
}
return make_actual_key_from_vault(dpp, cct, kctx, attrs, actual_key);
}
int create_sse_s3_bucket_key(const DoutPrefixProvider *dpp,
CephContext *cct,
const std::string& bucket_key)
{
SseS3Context kctx { cct };
const std::string kms_backend { kctx.backend() };
if (RGW_SSE_KMS_BACKEND_VAULT != kms_backend) {
ldpp_dout(dpp, 0) << "ERROR: Unsupported rgw_crypt_sse_s3_backend: " << kms_backend << dendl;
return -EINVAL;
}
std::string secret_engine_str = kctx.secret_engine();
EngineParmMap secret_engine_parms;
auto secret_engine { config_to_engine_and_parms(
cct, "rgw_crypt_sse_s3_vault_secret_engine",
secret_engine_str, secret_engine_parms) };
if (RGW_SSE_KMS_VAULT_SE_TRANSIT == secret_engine){
TransitSecretEngine engine(cct, kctx, std::move(secret_engine_parms));
return engine.create_bucket_key(dpp, bucket_key);
}
else {
ldpp_dout(dpp, 0) << "Missing or invalid secret engine" << dendl;
return -EINVAL;
}
}
int remove_sse_s3_bucket_key(const DoutPrefixProvider *dpp,
CephContext *cct,
const std::string& bucket_key)
{
SseS3Context kctx { cct };
std::string secret_engine_str = kctx.secret_engine();
EngineParmMap secret_engine_parms;
auto secret_engine { config_to_engine_and_parms(
cct, "rgw_crypt_sse_s3_vault_secret_engine",
secret_engine_str, secret_engine_parms) };
if (RGW_SSE_KMS_VAULT_SE_TRANSIT == secret_engine){
TransitSecretEngine engine(cct, kctx, std::move(secret_engine_parms));
return engine.delete_bucket_key(dpp, bucket_key);
}
else {
ldpp_dout(dpp, 0) << "Missing or invalid secret engine" << dendl;
return -EINVAL;
}
}
| 39,828 | 30.165102 | 125 |
cc
|
null |
ceph-main/src/rgw/rgw_kms.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/**
* Server-side encryption integrations with Key Management Systems (SSE-KMS)
*/
#pragma once
#include <string>
static const std::string RGW_SSE_KMS_BACKEND_TESTING = "testing";
static const std::string RGW_SSE_KMS_BACKEND_BARBICAN = "barbican";
static const std::string RGW_SSE_KMS_BACKEND_VAULT = "vault";
static const std::string RGW_SSE_KMS_BACKEND_KMIP = "kmip";
static const std::string RGW_SSE_KMS_VAULT_AUTH_TOKEN = "token";
static const std::string RGW_SSE_KMS_VAULT_AUTH_AGENT = "agent";
static const std::string RGW_SSE_KMS_VAULT_SE_TRANSIT = "transit";
static const std::string RGW_SSE_KMS_VAULT_SE_KV = "kv";
static const std::string RGW_SSE_KMS_KMIP_SE_KV = "kv";
/**
* Retrieves the actual server-side encryption key from a KMS system given a
* key ID. Currently supported KMS systems are OpenStack Barbican and HashiCorp
* Vault, but keys can also be retrieved from Ceph configuration file (if
* kms is set to 'local').
*
* \params
* TODO
* \return
*/
int make_actual_key_from_kms(const DoutPrefixProvider *dpp, CephContext *cct,
std::map<std::string, bufferlist>& attrs,
std::string& actual_key);
int reconstitute_actual_key_from_kms(const DoutPrefixProvider *dpp, CephContext *cct,
std::map<std::string, bufferlist>& attrs,
std::string& actual_key);
int make_actual_key_from_sse_s3(const DoutPrefixProvider *dpp, CephContext *cct,
std::map<std::string, bufferlist>& attrs,
std::string& actual_key);
int reconstitute_actual_key_from_sse_s3(const DoutPrefixProvider *dpp, CephContext *cct,
std::map<std::string, bufferlist>& attrs,
std::string& actual_key);
int create_sse_s3_bucket_key(const DoutPrefixProvider *dpp, CephContext *cct,
const std::string& actual_key);
int remove_sse_s3_bucket_key(const DoutPrefixProvider *dpp, CephContext *cct,
const std::string& actual_key);
/**
* SecretEngine Interface
* Defining interface here such that we can use both a real implementation
* of this interface, and a mock implementation in tests.
**/
class SecretEngine {
public:
virtual int get_key(const DoutPrefixProvider *dpp, std::string_view key_id, std::string& actual_key) = 0;
virtual ~SecretEngine(){};
};
| 2,533 | 37.984615 | 107 |
h
|
null |
ceph-main/src/rgw/rgw_lc.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include <map>
#include <algorithm>
#include <tuple>
#include <functional>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/variant.hpp>
#include "include/scope_guard.h"
#include "include/function2.hpp"
#include "common/Formatter.h"
#include "common/containers.h"
#include "common/split.h"
#include <common/errno.h>
#include "include/random.h"
#include "cls/lock/cls_lock_client.h"
#include "rgw_perf_counters.h"
#include "rgw_common.h"
#include "rgw_bucket.h"
#include "rgw_lc.h"
#include "rgw_zone.h"
#include "rgw_string.h"
#include "rgw_multi.h"
#include "rgw_sal.h"
#include "rgw_lc_tier.h"
#include "rgw_notify.h"
#include "fmt/format.h"
#include "services/svc_sys_obj.h"
#include "services/svc_zone.h"
#include "services/svc_tier_rados.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
const char* LC_STATUS[] = {
"UNINITIAL",
"PROCESSING",
"FAILED",
"COMPLETE"
};
using namespace librados;
bool LCRule::valid() const
{
if (id.length() > MAX_ID_LEN) {
return false;
}
else if(expiration.empty() && noncur_expiration.empty() &&
mp_expiration.empty() && !dm_expiration &&
transitions.empty() && noncur_transitions.empty()) {
return false;
}
else if (!expiration.valid() || !noncur_expiration.valid() ||
!mp_expiration.valid()) {
return false;
}
if (!transitions.empty()) {
bool using_days = expiration.has_days();
bool using_date = expiration.has_date();
for (const auto& elem : transitions) {
if (!elem.second.valid()) {
return false;
}
using_days = using_days || elem.second.has_days();
using_date = using_date || elem.second.has_date();
if (using_days && using_date) {
return false;
}
}
}
for (const auto& elem : noncur_transitions) {
if (!elem.second.valid()) {
return false;
}
}
return true;
}
void LCRule::init_simple_days_rule(std::string_view _id,
std::string_view _prefix, int num_days)
{
id = _id;
prefix = _prefix;
char buf[32];
snprintf(buf, sizeof(buf), "%d", num_days);
expiration.set_days(buf);
set_enabled(true);
}
void RGWLifecycleConfiguration::add_rule(const LCRule& rule)
{
auto& id = rule.get_id(); // note that this will return false for groups, but that's ok, we won't search groups
rule_map.insert(pair<string, LCRule>(id, rule));
}
bool RGWLifecycleConfiguration::_add_rule(const LCRule& rule)
{
lc_op op(rule.get_id());
op.status = rule.is_enabled();
if (rule.get_expiration().has_days()) {
op.expiration = rule.get_expiration().get_days();
}
if (rule.get_expiration().has_date()) {
op.expiration_date = ceph::from_iso_8601(rule.get_expiration().get_date());
}
if (rule.get_noncur_expiration().has_days()) {
op.noncur_expiration = rule.get_noncur_expiration().get_days();
}
if (rule.get_mp_expiration().has_days()) {
op.mp_expiration = rule.get_mp_expiration().get_days();
}
op.dm_expiration = rule.get_dm_expiration();
for (const auto &elem : rule.get_transitions()) {
transition_action action;
if (elem.second.has_days()) {
action.days = elem.second.get_days();
} else {
action.date = ceph::from_iso_8601(elem.second.get_date());
}
action.storage_class
= rgw_placement_rule::get_canonical_storage_class(elem.first);
op.transitions.emplace(elem.first, std::move(action));
}
for (const auto &elem : rule.get_noncur_transitions()) {
transition_action action;
action.days = elem.second.get_days();
action.date = ceph::from_iso_8601(elem.second.get_date());
action.storage_class
= rgw_placement_rule::get_canonical_storage_class(elem.first);
op.noncur_transitions.emplace(elem.first, std::move(action));
}
std::string prefix;
if (rule.get_filter().has_prefix()){
prefix = rule.get_filter().get_prefix();
} else {
prefix = rule.get_prefix();
}
if (rule.get_filter().has_tags()){
op.obj_tags = rule.get_filter().get_tags();
}
op.rule_flags = rule.get_filter().get_flags();
prefix_map.emplace(std::move(prefix), std::move(op));
return true;
}
int RGWLifecycleConfiguration::check_and_add_rule(const LCRule& rule)
{
if (!rule.valid()) {
return -EINVAL;
}
auto& id = rule.get_id();
if (rule_map.find(id) != rule_map.end()) { //id shouldn't be the same
return -EINVAL;
}
if (rule.get_filter().has_tags() && (rule.get_dm_expiration() ||
!rule.get_mp_expiration().empty())) {
return -ERR_INVALID_REQUEST;
}
rule_map.insert(pair<string, LCRule>(id, rule));
if (!_add_rule(rule)) {
return -ERR_INVALID_REQUEST;
}
return 0;
}
bool RGWLifecycleConfiguration::has_same_action(const lc_op& first,
const lc_op& second) {
if ((first.expiration > 0 || first.expiration_date != boost::none) &&
(second.expiration > 0 || second.expiration_date != boost::none)) {
return true;
} else if (first.noncur_expiration > 0 && second.noncur_expiration > 0) {
return true;
} else if (first.mp_expiration > 0 && second.mp_expiration > 0) {
return true;
} else if (!first.transitions.empty() && !second.transitions.empty()) {
for (auto &elem : first.transitions) {
if (second.transitions.find(elem.first) != second.transitions.end()) {
return true;
}
}
} else if (!first.noncur_transitions.empty() &&
!second.noncur_transitions.empty()) {
for (auto &elem : first.noncur_transitions) {
if (second.noncur_transitions.find(elem.first) !=
second.noncur_transitions.end()) {
return true;
}
}
}
return false;
}
/* Formerly, this method checked for duplicate rules using an invalid
* method (prefix uniqueness). */
bool RGWLifecycleConfiguration::valid()
{
return true;
}
void *RGWLC::LCWorker::entry() {
do {
std::unique_ptr<rgw::sal::Bucket> all_buckets; // empty restriction
utime_t start = ceph_clock_now();
if (should_work(start)) {
ldpp_dout(dpp, 2) << "life cycle: start" << dendl;
int r = lc->process(this, all_buckets, false /* once */);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: do life cycle process() returned error r="
<< r << dendl;
}
ldpp_dout(dpp, 2) << "life cycle: stop" << dendl;
cloud_targets.clear(); // clear cloud targets
}
if (lc->going_down())
break;
utime_t end = ceph_clock_now();
int secs = schedule_next_start_time(start, end);
utime_t next;
next.set_from_double(end + secs);
ldpp_dout(dpp, 5) << "schedule life cycle next start time: "
<< rgw_to_asctime(next) << dendl;
std::unique_lock l{lock};
cond.wait_for(l, std::chrono::seconds(secs));
} while (!lc->going_down());
return NULL;
}
void RGWLC::initialize(CephContext *_cct, rgw::sal::Driver* _driver) {
cct = _cct;
driver = _driver;
sal_lc = driver->get_lifecycle();
max_objs = cct->_conf->rgw_lc_max_objs;
if (max_objs > HASH_PRIME)
max_objs = HASH_PRIME;
obj_names = new string[max_objs];
for (int i = 0; i < max_objs; i++) {
obj_names[i] = lc_oid_prefix;
char buf[32];
snprintf(buf, 32, ".%d", i);
obj_names[i].append(buf);
}
#define COOKIE_LEN 16
char cookie_buf[COOKIE_LEN + 1];
gen_rand_alphanumeric(cct, cookie_buf, sizeof(cookie_buf) - 1);
cookie = cookie_buf;
}
void RGWLC::finalize()
{
delete[] obj_names;
}
static inline std::ostream& operator<<(std::ostream &os, rgw::sal::Lifecycle::LCEntry& ent) {
os << "<ent: bucket=";
os << ent.get_bucket();
os << "; start_time=";
os << rgw_to_asctime(utime_t(time_t(ent.get_start_time()), 0));
os << "; status=";
os << LC_STATUS[ent.get_status()];
os << ">";
return os;
}
static bool obj_has_expired(const DoutPrefixProvider *dpp, CephContext *cct, ceph::real_time mtime, int days,
ceph::real_time *expire_time = nullptr)
{
double timediff, cmp;
utime_t base_time;
if (cct->_conf->rgw_lc_debug_interval <= 0) {
/* Normal case, run properly */
cmp = double(days)*24*60*60;
base_time = ceph_clock_now().round_to_day();
} else {
/* We're in debug mode; Treat each rgw_lc_debug_interval seconds as a day */
cmp = double(days)*cct->_conf->rgw_lc_debug_interval;
base_time = ceph_clock_now();
}
auto tt_mtime = ceph::real_clock::to_time_t(mtime);
timediff = base_time - tt_mtime;
if (expire_time) {
*expire_time = mtime + make_timespan(cmp);
}
ldpp_dout(dpp, 20) << __func__
<< "(): mtime=" << mtime << " days=" << days
<< " base_time=" << base_time << " timediff=" << timediff
<< " cmp=" << cmp
<< " is_expired=" << (timediff >= cmp)
<< dendl;
return (timediff >= cmp);
}
static bool pass_object_lock_check(rgw::sal::Driver* driver, rgw::sal::Object* obj, const DoutPrefixProvider *dpp)
{
if (!obj->get_bucket()->get_info().obj_lock_enabled()) {
return true;
}
std::unique_ptr<rgw::sal::Object::ReadOp> read_op = obj->get_read_op();
int ret = read_op->prepare(null_yield, dpp);
if (ret < 0) {
if (ret == -ENOENT) {
return true;
} else {
return false;
}
} else {
auto iter = obj->get_attrs().find(RGW_ATTR_OBJECT_RETENTION);
if (iter != obj->get_attrs().end()) {
RGWObjectRetention retention;
try {
decode(retention, iter->second);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: failed to decode RGWObjectRetention"
<< dendl;
return false;
}
if (ceph::real_clock::to_time_t(retention.get_retain_until_date()) >
ceph_clock_now()) {
return false;
}
}
iter = obj->get_attrs().find(RGW_ATTR_OBJECT_LEGAL_HOLD);
if (iter != obj->get_attrs().end()) {
RGWObjectLegalHold obj_legal_hold;
try {
decode(obj_legal_hold, iter->second);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: failed to decode RGWObjectLegalHold"
<< dendl;
return false;
}
if (obj_legal_hold.is_enabled()) {
return false;
}
}
return true;
}
}
class LCObjsLister {
rgw::sal::Driver* driver;
rgw::sal::Bucket* bucket;
rgw::sal::Bucket::ListParams list_params;
rgw::sal::Bucket::ListResults list_results;
string prefix;
vector<rgw_bucket_dir_entry>::iterator obj_iter;
rgw_bucket_dir_entry pre_obj;
int64_t delay_ms;
public:
LCObjsLister(rgw::sal::Driver* _driver, rgw::sal::Bucket* _bucket) :
driver(_driver), bucket(_bucket) {
list_params.list_versions = bucket->versioned();
list_params.allow_unordered = true;
delay_ms = driver->ctx()->_conf.get_val<int64_t>("rgw_lc_thread_delay");
}
void set_prefix(const string& p) {
prefix = p;
list_params.prefix = prefix;
}
int init(const DoutPrefixProvider *dpp) {
return fetch(dpp);
}
int fetch(const DoutPrefixProvider *dpp) {
int ret = bucket->list(dpp, list_params, 1000, list_results, null_yield);
if (ret < 0) {
return ret;
}
obj_iter = list_results.objs.begin();
return 0;
}
void delay() {
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
}
bool get_obj(const DoutPrefixProvider *dpp, rgw_bucket_dir_entry **obj,
std::function<void(void)> fetch_barrier
= []() { /* nada */}) {
if (obj_iter == list_results.objs.end()) {
if (!list_results.is_truncated) {
delay();
return false;
} else {
fetch_barrier();
list_params.marker = pre_obj.key;
int ret = fetch(dpp);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: list_op returned ret=" << ret
<< dendl;
return false;
}
}
delay();
}
/* returning address of entry in objs */
*obj = &(*obj_iter);
return obj_iter != list_results.objs.end();
}
rgw_bucket_dir_entry get_prev_obj() {
return pre_obj;
}
void next() {
pre_obj = *obj_iter;
++obj_iter;
}
boost::optional<std::string> next_key_name() {
if (obj_iter == list_results.objs.end() ||
(obj_iter + 1) == list_results.objs.end()) {
/* this should have been called after get_obj() was called, so this should
* only happen if is_truncated is false */
return boost::none;
}
return ((obj_iter + 1)->key.name);
}
}; /* LCObjsLister */
struct op_env {
using LCWorker = RGWLC::LCWorker;
lc_op op;
rgw::sal::Driver* driver;
LCWorker* worker;
rgw::sal::Bucket* bucket;
LCObjsLister& ol;
op_env(lc_op& _op, rgw::sal::Driver* _driver, LCWorker* _worker,
rgw::sal::Bucket* _bucket, LCObjsLister& _ol)
: op(_op), driver(_driver), worker(_worker), bucket(_bucket),
ol(_ol) {}
}; /* op_env */
class LCRuleOp;
class WorkQ;
struct lc_op_ctx {
CephContext *cct;
op_env env;
rgw_bucket_dir_entry o;
boost::optional<std::string> next_key_name;
ceph::real_time effective_mtime;
rgw::sal::Driver* driver;
rgw::sal::Bucket* bucket;
lc_op& op; // ok--refers to expanded env.op
LCObjsLister& ol;
std::unique_ptr<rgw::sal::Object> obj;
RGWObjectCtx rctx;
const DoutPrefixProvider *dpp;
WorkQ* wq;
std::unique_ptr<rgw::sal::PlacementTier> tier;
lc_op_ctx(op_env& env, rgw_bucket_dir_entry& o,
boost::optional<std::string> next_key_name,
ceph::real_time effective_mtime,
const DoutPrefixProvider *dpp, WorkQ* wq)
: cct(env.driver->ctx()), env(env), o(o), next_key_name(next_key_name),
effective_mtime(effective_mtime),
driver(env.driver), bucket(env.bucket), op(env.op), ol(env.ol),
rctx(env.driver), dpp(dpp), wq(wq)
{
obj = bucket->get_object(o.key);
}
bool next_has_same_name(const std::string& key_name) {
return (next_key_name && key_name.compare(
boost::get<std::string>(next_key_name)) == 0);
}
}; /* lc_op_ctx */
static std::string lc_id = "rgw lifecycle";
static std::string lc_req_id = "0";
static int remove_expired_obj(
const DoutPrefixProvider *dpp, lc_op_ctx& oc, bool remove_indeed,
rgw::notify::EventType event_type)
{
auto& driver = oc.driver;
auto& bucket_info = oc.bucket->get_info();
auto& o = oc.o;
auto obj_key = o.key;
auto& meta = o.meta;
int ret;
std::string version_id;
std::unique_ptr<rgw::sal::Notification> notify;
if (!remove_indeed) {
obj_key.instance.clear();
} else if (obj_key.instance.empty()) {
obj_key.instance = "null";
}
std::unique_ptr<rgw::sal::User> user;
std::unique_ptr<rgw::sal::Bucket> bucket;
std::unique_ptr<rgw::sal::Object> obj;
user = driver->get_user(bucket_info.owner);
ret = driver->get_bucket(user.get(), bucket_info, &bucket);
if (ret < 0) {
return ret;
}
obj = bucket->get_object(obj_key);
RGWObjState* obj_state{nullptr};
ret = obj->get_obj_state(dpp, &obj_state, null_yield, true);
if (ret < 0) {
return ret;
}
std::unique_ptr<rgw::sal::Object::DeleteOp> del_op
= obj->get_delete_op();
del_op->params.versioning_status
= obj->get_bucket()->get_info().versioning_status();
del_op->params.obj_owner.set_id(rgw_user {meta.owner});
del_op->params.obj_owner.set_name(meta.owner_display_name);
del_op->params.bucket_owner.set_id(bucket_info.owner);
del_op->params.unmod_since = meta.mtime;
del_op->params.marker_version_id = version_id;
// notification supported only for RADOS driver for now
notify = driver->get_notification(dpp, obj.get(), nullptr, event_type,
bucket.get(), lc_id,
const_cast<std::string&>(oc.bucket->get_tenant()),
lc_req_id, null_yield);
ret = notify->publish_reserve(dpp, nullptr);
if ( ret < 0) {
ldpp_dout(dpp, 1)
<< "ERROR: notify reservation failed, deferring delete of object k="
<< o.key
<< dendl;
return ret;
}
ret = del_op->delete_obj(dpp, null_yield);
if (ret < 0) {
ldpp_dout(dpp, 1) <<
"ERROR: publishing notification failed, with error: " << ret << dendl;
} else {
// send request to notification manager
(void) notify->publish_commit(dpp, obj_state->size,
ceph::real_clock::now(),
obj_state->attrset[RGW_ATTR_ETAG].to_str(),
version_id);
}
return ret;
} /* remove_expired_obj */
class LCOpAction {
public:
virtual ~LCOpAction() {}
virtual bool check(lc_op_ctx& oc, ceph::real_time *exp_time, const DoutPrefixProvider *dpp) {
return false;
}
/* called after check(). Check should tell us whether this action
* is applicable. If there are multiple actions, we'll end up executing
* the latest applicable action
* For example:
* one action after 10 days, another after 20, third after 40.
* After 10 days, the latest applicable action would be the first one,
* after 20 days it will be the second one. After 21 days it will still be the
* second one. So check() should return true for the second action at that point,
* but should_process() if the action has already been applied. In object removal
* it doesn't matter, but in object transition it does.
*/
virtual bool should_process() {
return true;
}
virtual int process(lc_op_ctx& oc) {
return 0;
}
friend class LCOpRule;
}; /* LCOpAction */
class LCOpFilter {
public:
virtual ~LCOpFilter() {}
virtual bool check(const DoutPrefixProvider *dpp, lc_op_ctx& oc) {
return false;
}
}; /* LCOpFilter */
class LCOpRule {
friend class LCOpAction;
op_env env;
boost::optional<std::string> next_key_name;
ceph::real_time effective_mtime;
std::vector<shared_ptr<LCOpFilter> > filters; // n.b., sharing ovhd
std::vector<shared_ptr<LCOpAction> > actions;
public:
LCOpRule(op_env& _env) : env(_env) {}
boost::optional<std::string> get_next_key_name() {
return next_key_name;
}
std::vector<shared_ptr<LCOpAction>>& get_actions() {
return actions;
}
void build();
void update();
int process(rgw_bucket_dir_entry& o, const DoutPrefixProvider *dpp,
WorkQ* wq);
}; /* LCOpRule */
using WorkItem =
boost::variant<void*,
/* out-of-line delete */
std::tuple<LCOpRule, rgw_bucket_dir_entry>,
/* uncompleted MPU expiration */
std::tuple<lc_op, rgw_bucket_dir_entry>,
rgw_bucket_dir_entry>;
class WorkQ : public Thread
{
public:
using unique_lock = std::unique_lock<std::mutex>;
using work_f = std::function<void(RGWLC::LCWorker*, WorkQ*, WorkItem&)>;
using dequeue_result = boost::variant<void*, WorkItem>;
static constexpr uint32_t FLAG_NONE = 0x0000;
static constexpr uint32_t FLAG_EWAIT_SYNC = 0x0001;
static constexpr uint32_t FLAG_DWAIT_SYNC = 0x0002;
static constexpr uint32_t FLAG_EDRAIN_SYNC = 0x0004;
private:
const work_f bsf = [](RGWLC::LCWorker* wk, WorkQ* wq, WorkItem& wi) {};
RGWLC::LCWorker* wk;
uint32_t qmax;
int ix;
std::mutex mtx;
std::condition_variable cv;
uint32_t flags;
vector<WorkItem> items;
work_f f;
public:
WorkQ(RGWLC::LCWorker* wk, uint32_t ix, uint32_t qmax)
: wk(wk), qmax(qmax), ix(ix), flags(FLAG_NONE), f(bsf)
{
create(thr_name().c_str());
}
std::string thr_name() {
return std::string{"wp_thrd: "}
+ std::to_string(wk->ix) + ", " + std::to_string(ix);
}
void setf(work_f _f) {
f = _f;
}
void enqueue(WorkItem&& item) {
unique_lock uniq(mtx);
while ((!wk->get_lc()->going_down()) &&
(items.size() > qmax)) {
flags |= FLAG_EWAIT_SYNC;
cv.wait_for(uniq, 200ms);
}
items.push_back(item);
if (flags & FLAG_DWAIT_SYNC) {
flags &= ~FLAG_DWAIT_SYNC;
cv.notify_one();
}
}
void drain() {
unique_lock uniq(mtx);
flags |= FLAG_EDRAIN_SYNC;
while (flags & FLAG_EDRAIN_SYNC) {
cv.wait_for(uniq, 200ms);
}
}
private:
dequeue_result dequeue() {
unique_lock uniq(mtx);
while ((!wk->get_lc()->going_down()) &&
(items.size() == 0)) {
/* clear drain state, as we are NOT doing work and qlen==0 */
if (flags & FLAG_EDRAIN_SYNC) {
flags &= ~FLAG_EDRAIN_SYNC;
}
flags |= FLAG_DWAIT_SYNC;
cv.wait_for(uniq, 200ms);
}
if (items.size() > 0) {
auto item = items.back();
items.pop_back();
if (flags & FLAG_EWAIT_SYNC) {
flags &= ~FLAG_EWAIT_SYNC;
cv.notify_one();
}
return {item};
}
return nullptr;
}
void* entry() override {
while (!wk->get_lc()->going_down()) {
auto item = dequeue();
if (item.which() == 0) {
/* going down */
break;
}
f(wk, this, boost::get<WorkItem>(item));
}
return nullptr;
}
}; /* WorkQ */
class RGWLC::WorkPool
{
using TVector = ceph::containers::tiny_vector<WorkQ, 3>;
TVector wqs;
uint64_t ix;
public:
WorkPool(RGWLC::LCWorker* wk, uint16_t n_threads, uint32_t qmax)
: wqs(TVector{
n_threads,
[&](const size_t ix, auto emplacer) {
emplacer.emplace(wk, ix, qmax);
}}),
ix(0)
{}
~WorkPool() {
for (auto& wq : wqs) {
wq.join();
}
}
void setf(WorkQ::work_f _f) {
for (auto& wq : wqs) {
wq.setf(_f);
}
}
void enqueue(WorkItem item) {
const auto tix = ix;
ix = (ix+1) % wqs.size();
(wqs[tix]).enqueue(std::move(item));
}
void drain() {
for (auto& wq : wqs) {
wq.drain();
}
}
}; /* WorkPool */
RGWLC::LCWorker::LCWorker(const DoutPrefixProvider* dpp, CephContext *cct,
RGWLC *lc, int ix)
: dpp(dpp), cct(cct), lc(lc), ix(ix)
{
auto wpw = cct->_conf.get_val<int64_t>("rgw_lc_max_wp_worker");
workpool = new WorkPool(this, wpw, 512);
}
static inline bool worker_should_stop(time_t stop_at, bool once)
{
return !once && stop_at < time(nullptr);
}
int RGWLC::handle_multipart_expiration(rgw::sal::Bucket* target,
const multimap<string, lc_op>& prefix_map,
LCWorker* worker, time_t stop_at, bool once)
{
MultipartMetaFilter mp_filter;
int ret;
rgw::sal::Bucket::ListParams params;
rgw::sal::Bucket::ListResults results;
auto delay_ms = cct->_conf.get_val<int64_t>("rgw_lc_thread_delay");
params.list_versions = false;
/* lifecycle processing does not depend on total order, so can
* take advantage of unordered listing optimizations--such as
* operating on one shard at a time */
params.allow_unordered = true;
params.ns = RGW_OBJ_NS_MULTIPART;
params.access_list_filter = &mp_filter;
auto pf = [&](RGWLC::LCWorker* wk, WorkQ* wq, WorkItem& wi) {
auto wt = boost::get<std::tuple<lc_op, rgw_bucket_dir_entry>>(wi);
auto& [rule, obj] = wt;
if (obj_has_expired(this, cct, obj.meta.mtime, rule.mp_expiration)) {
rgw_obj_key key(obj.key);
std::unique_ptr<rgw::sal::MultipartUpload> mpu = target->get_multipart_upload(key.name);
int ret = mpu->abort(this, cct, null_yield);
if (ret == 0) {
if (perfcounter) {
perfcounter->inc(l_rgw_lc_abort_mpu, 1);
}
} else {
if (ret == -ERR_NO_SUCH_UPLOAD) {
ldpp_dout(wk->get_lc(), 5)
<< "ERROR: abort_multipart_upload failed, ret=" << ret
<< ", thread:" << wq->thr_name()
<< ", meta:" << obj.key
<< dendl;
} else {
ldpp_dout(wk->get_lc(), 0)
<< "ERROR: abort_multipart_upload failed, ret=" << ret
<< ", thread:" << wq->thr_name()
<< ", meta:" << obj.key
<< dendl;
}
} /* abort failed */
} /* expired */
};
worker->workpool->setf(pf);
for (auto prefix_iter = prefix_map.begin(); prefix_iter != prefix_map.end();
++prefix_iter) {
if (worker_should_stop(stop_at, once)) {
ldpp_dout(this, 5) << __func__ << " interval budget EXPIRED worker "
<< worker->ix
<< dendl;
return 0;
}
if (!prefix_iter->second.status || prefix_iter->second.mp_expiration <= 0) {
continue;
}
params.prefix = prefix_iter->first;
do {
auto offset = 0;
results.objs.clear();
ret = target->list(this, params, 1000, results, null_yield);
if (ret < 0) {
if (ret == (-ENOENT))
return 0;
ldpp_dout(this, 0) << "ERROR: driver->list_objects():" <<dendl;
return ret;
}
for (auto obj_iter = results.objs.begin(); obj_iter != results.objs.end(); ++obj_iter, ++offset) {
std::tuple<lc_op, rgw_bucket_dir_entry> t1 =
{prefix_iter->second, *obj_iter};
worker->workpool->enqueue(WorkItem{t1});
if (going_down()) {
return 0;
}
} /* for objs */
if ((offset % 100) == 0) {
if (worker_should_stop(stop_at, once)) {
ldpp_dout(this, 5) << __func__ << " interval budget EXPIRED worker "
<< worker->ix
<< dendl;
return 0;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
} while(results.is_truncated);
} /* for prefix_map */
worker->workpool->drain();
return 0;
} /* RGWLC::handle_multipart_expiration */
static int read_obj_tags(const DoutPrefixProvider *dpp, rgw::sal::Object* obj, bufferlist& tags_bl)
{
std::unique_ptr<rgw::sal::Object::ReadOp> rop = obj->get_read_op();
return rop->get_attr(dpp, RGW_ATTR_TAGS, tags_bl, null_yield);
}
static bool is_valid_op(const lc_op& op)
{
return (op.status &&
(op.expiration > 0
|| op.expiration_date != boost::none
|| op.noncur_expiration > 0
|| op.dm_expiration
|| !op.transitions.empty()
|| !op.noncur_transitions.empty()));
}
static bool zone_check(const lc_op& op, rgw::sal::Zone* zone)
{
if (zone->get_tier_type() == "archive") {
return (op.rule_flags & uint32_t(LCFlagType::ArchiveZone));
} else {
return (! (op.rule_flags & uint32_t(LCFlagType::ArchiveZone)));
}
}
static inline bool has_all_tags(const lc_op& rule_action,
const RGWObjTags& object_tags)
{
if(! rule_action.obj_tags)
return false;
if(object_tags.count() < rule_action.obj_tags->count())
return false;
size_t tag_count = 0;
for (const auto& tag : object_tags.get_tags()) {
const auto& rule_tags = rule_action.obj_tags->get_tags();
const auto& iter = rule_tags.find(tag.first);
if(iter == rule_tags.end())
continue;
if(iter->second == tag.second)
{
tag_count++;
}
/* all tags in the rule appear in obj tags */
}
return tag_count == rule_action.obj_tags->count();
}
static int check_tags(const DoutPrefixProvider *dpp, lc_op_ctx& oc, bool *skip)
{
auto& op = oc.op;
if (op.obj_tags != boost::none) {
*skip = true;
bufferlist tags_bl;
int ret = read_obj_tags(dpp, oc.obj.get(), tags_bl);
if (ret < 0) {
if (ret != -ENODATA) {
ldpp_dout(oc.dpp, 5) << "ERROR: read_obj_tags returned r="
<< ret << " " << oc.wq->thr_name() << dendl;
}
return 0;
}
RGWObjTags dest_obj_tags;
try {
auto iter = tags_bl.cbegin();
dest_obj_tags.decode(iter);
} catch (buffer::error& err) {
ldpp_dout(oc.dpp,0) << "ERROR: caught buffer::error, couldn't decode TagSet "
<< oc.wq->thr_name() << dendl;
return -EIO;
}
if (! has_all_tags(op, dest_obj_tags)) {
ldpp_dout(oc.dpp, 20) << __func__ << "() skipping obj " << oc.obj
<< " as tags do not match in rule: "
<< op.id << " "
<< oc.wq->thr_name() << dendl;
return 0;
}
}
*skip = false;
return 0;
}
class LCOpFilter_Tags : public LCOpFilter {
public:
bool check(const DoutPrefixProvider *dpp, lc_op_ctx& oc) override {
auto& o = oc.o;
if (o.is_delete_marker()) {
return true;
}
bool skip;
int ret = check_tags(dpp, oc, &skip);
if (ret < 0) {
if (ret == -ENOENT) {
return false;
}
ldpp_dout(oc.dpp, 0) << "ERROR: check_tags on obj=" << oc.obj
<< " returned ret=" << ret << " "
<< oc.wq->thr_name() << dendl;
return false;
}
return !skip;
};
};
class LCOpAction_CurrentExpiration : public LCOpAction {
public:
LCOpAction_CurrentExpiration(op_env& env) {}
bool check(lc_op_ctx& oc, ceph::real_time *exp_time, const DoutPrefixProvider *dpp) override {
auto& o = oc.o;
if (!o.is_current()) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": not current, skipping "
<< oc.wq->thr_name() << dendl;
return false;
}
if (o.is_delete_marker()) {
if (oc.next_key_name) {
std::string nkn = *oc.next_key_name;
if (oc.next_has_same_name(o.key.name)) {
ldpp_dout(dpp, 7) << __func__ << "(): dm-check SAME: key=" << o.key
<< " next_key_name: %%" << nkn << "%% "
<< oc.wq->thr_name() << dendl;
return false;
} else {
ldpp_dout(dpp, 7) << __func__ << "(): dm-check DELE: key=" << o.key
<< " next_key_name: %%" << nkn << "%% "
<< oc.wq->thr_name() << dendl;
*exp_time = real_clock::now();
return true;
}
}
return false;
}
auto& mtime = o.meta.mtime;
bool is_expired;
auto& op = oc.op;
if (op.expiration <= 0) {
if (op.expiration_date == boost::none) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": no expiration set in rule, skipping "
<< oc.wq->thr_name() << dendl;
return false;
}
is_expired = ceph_clock_now() >=
ceph::real_clock::to_time_t(*op.expiration_date);
*exp_time = *op.expiration_date;
} else {
is_expired = obj_has_expired(dpp, oc.cct, mtime, op.expiration, exp_time);
}
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key << ": is_expired="
<< (int)is_expired << " "
<< oc.wq->thr_name() << dendl;
return is_expired;
}
int process(lc_op_ctx& oc) {
auto& o = oc.o;
int r;
if (o.is_delete_marker()) {
r = remove_expired_obj(oc.dpp, oc, true,
rgw::notify::ObjectExpirationDeleteMarker);
if (r < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: current is-dm remove_expired_obj "
<< oc.bucket << ":" << o.key
<< " " << cpp_strerror(r) << " "
<< oc.wq->thr_name() << dendl;
return r;
}
ldpp_dout(oc.dpp, 2) << "DELETED: current is-dm "
<< oc.bucket << ":" << o.key
<< " " << oc.wq->thr_name() << dendl;
} else {
/* ! o.is_delete_marker() */
r = remove_expired_obj(oc.dpp, oc, !oc.bucket->versioned(),
rgw::notify::ObjectExpirationCurrent);
if (r < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: remove_expired_obj "
<< oc.bucket << ":" << o.key
<< " " << cpp_strerror(r) << " "
<< oc.wq->thr_name() << dendl;
return r;
}
if (perfcounter) {
perfcounter->inc(l_rgw_lc_expire_current, 1);
}
ldpp_dout(oc.dpp, 2) << "DELETED:" << oc.bucket << ":" << o.key
<< " " << oc.wq->thr_name() << dendl;
}
return 0;
}
};
class LCOpAction_NonCurrentExpiration : public LCOpAction {
protected:
public:
LCOpAction_NonCurrentExpiration(op_env& env)
{}
bool check(lc_op_ctx& oc, ceph::real_time *exp_time, const DoutPrefixProvider *dpp) override {
auto& o = oc.o;
if (o.is_current()) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": current version, skipping "
<< oc.wq->thr_name() << dendl;
return false;
}
int expiration = oc.op.noncur_expiration;
bool is_expired = obj_has_expired(dpp, oc.cct, oc.effective_mtime, expiration,
exp_time);
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key << ": is_expired="
<< is_expired << " "
<< oc.wq->thr_name() << dendl;
return is_expired &&
pass_object_lock_check(oc.driver, oc.obj.get(), dpp);
}
int process(lc_op_ctx& oc) {
auto& o = oc.o;
int r = remove_expired_obj(oc.dpp, oc, true,
rgw::notify::ObjectExpirationNoncurrent);
if (r < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: remove_expired_obj (non-current expiration) "
<< oc.bucket << ":" << o.key
<< " " << cpp_strerror(r)
<< " " << oc.wq->thr_name() << dendl;
return r;
}
if (perfcounter) {
perfcounter->inc(l_rgw_lc_expire_noncurrent, 1);
}
ldpp_dout(oc.dpp, 2) << "DELETED:" << oc.bucket << ":" << o.key
<< " (non-current expiration) "
<< oc.wq->thr_name() << dendl;
return 0;
}
};
class LCOpAction_DMExpiration : public LCOpAction {
public:
LCOpAction_DMExpiration(op_env& env) {}
bool check(lc_op_ctx& oc, ceph::real_time *exp_time, const DoutPrefixProvider *dpp) override {
auto& o = oc.o;
if (!o.is_delete_marker()) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": not a delete marker, skipping "
<< oc.wq->thr_name() << dendl;
return false;
}
if (oc.next_has_same_name(o.key.name)) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": next is same object, skipping "
<< oc.wq->thr_name() << dendl;
return false;
}
*exp_time = real_clock::now();
return true;
}
int process(lc_op_ctx& oc) {
auto& o = oc.o;
int r = remove_expired_obj(oc.dpp, oc, true,
rgw::notify::ObjectExpirationDeleteMarker);
if (r < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: remove_expired_obj (delete marker expiration) "
<< oc.bucket << ":" << o.key
<< " " << cpp_strerror(r)
<< " " << oc.wq->thr_name()
<< dendl;
return r;
}
if (perfcounter) {
perfcounter->inc(l_rgw_lc_expire_dm, 1);
}
ldpp_dout(oc.dpp, 2) << "DELETED:" << oc.bucket << ":" << o.key
<< " (delete marker expiration) "
<< oc.wq->thr_name() << dendl;
return 0;
}
};
class LCOpAction_Transition : public LCOpAction {
const transition_action& transition;
bool need_to_process{false};
protected:
virtual bool check_current_state(bool is_current) = 0;
virtual ceph::real_time get_effective_mtime(lc_op_ctx& oc) = 0;
public:
LCOpAction_Transition(const transition_action& _transition)
: transition(_transition) {}
bool check(lc_op_ctx& oc, ceph::real_time *exp_time, const DoutPrefixProvider *dpp) override {
auto& o = oc.o;
if (o.is_delete_marker()) {
return false;
}
if (!check_current_state(o.is_current())) {
return false;
}
auto mtime = get_effective_mtime(oc);
bool is_expired;
if (transition.days < 0) {
if (transition.date == boost::none) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": no transition day/date set in rule, skipping "
<< oc.wq->thr_name() << dendl;
return false;
}
is_expired = ceph_clock_now() >=
ceph::real_clock::to_time_t(*transition.date);
*exp_time = *transition.date;
} else {
is_expired = obj_has_expired(dpp, oc.cct, mtime, transition.days, exp_time);
}
ldpp_dout(oc.dpp, 20) << __func__ << "(): key=" << o.key << ": is_expired="
<< is_expired << " "
<< oc.wq->thr_name() << dendl;
need_to_process =
(rgw_placement_rule::get_canonical_storage_class(o.meta.storage_class) !=
transition.storage_class);
return is_expired;
}
bool should_process() override {
return need_to_process;
}
int delete_tier_obj(lc_op_ctx& oc) {
int ret = 0;
/* If bucket is versioned, create delete_marker for current version
*/
if (oc.bucket->versioned() && oc.o.is_current() && !oc.o.is_delete_marker()) {
ret = remove_expired_obj(oc.dpp, oc, false, rgw::notify::ObjectExpiration);
ldpp_dout(oc.dpp, 20) << "delete_tier_obj Object(key:" << oc.o.key << ") current & not delete_marker" << " versioned_epoch: " << oc.o.versioned_epoch << "flags: " << oc.o.flags << dendl;
} else {
ret = remove_expired_obj(oc.dpp, oc, true, rgw::notify::ObjectExpiration);
ldpp_dout(oc.dpp, 20) << "delete_tier_obj Object(key:" << oc.o.key << ") not current " << "versioned_epoch: " << oc.o.versioned_epoch << "flags: " << oc.o.flags << dendl;
}
return ret;
}
int transition_obj_to_cloud(lc_op_ctx& oc) {
/* If CurrentVersion object, remove it & create delete marker */
bool delete_object = (!oc.tier->retain_head_object() ||
(oc.o.is_current() && oc.bucket->versioned()));
int ret = oc.obj->transition_to_cloud(oc.bucket, oc.tier.get(), oc.o,
oc.env.worker->get_cloud_targets(), oc.cct,
!delete_object, oc.dpp, null_yield);
if (ret < 0) {
return ret;
}
if (delete_object) {
ret = delete_tier_obj(oc);
if (ret < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: Deleting tier object(" << oc.o.key << ") failed ret=" << ret << dendl;
return ret;
}
}
return 0;
}
int process(lc_op_ctx& oc) {
auto& o = oc.o;
int r;
if (oc.o.meta.category == RGWObjCategory::CloudTiered) {
/* Skip objects which are already cloud tiered. */
ldpp_dout(oc.dpp, 30) << "Object(key:" << oc.o.key << ") is already cloud tiered to cloud-s3 tier: " << oc.o.meta.storage_class << dendl;
return 0;
}
std::string tier_type = "";
rgw::sal::ZoneGroup& zonegroup = oc.driver->get_zone()->get_zonegroup();
rgw_placement_rule target_placement;
target_placement.inherit_from(oc.bucket->get_placement_rule());
target_placement.storage_class = transition.storage_class;
r = zonegroup.get_placement_tier(target_placement, &oc.tier);
if (!r && oc.tier->get_tier_type() == "cloud-s3") {
ldpp_dout(oc.dpp, 30) << "Found cloud s3 tier: " << target_placement.storage_class << dendl;
if (!oc.o.is_current() &&
!pass_object_lock_check(oc.driver, oc.obj.get(), oc.dpp)) {
/* Skip objects which has object lock enabled. */
ldpp_dout(oc.dpp, 10) << "Object(key:" << oc.o.key << ") is locked. Skipping transition to cloud-s3 tier: " << target_placement.storage_class << dendl;
return 0;
}
r = transition_obj_to_cloud(oc);
if (r < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: failed to transition obj(key:" << oc.o.key << ") to cloud (r=" << r << ")"
<< dendl;
return r;
}
} else {
if (!oc.driver->valid_placement(target_placement)) {
ldpp_dout(oc.dpp, 0) << "ERROR: non existent dest placement: "
<< target_placement
<< " bucket="<< oc.bucket
<< " rule_id=" << oc.op.id
<< " " << oc.wq->thr_name() << dendl;
return -EINVAL;
}
int r = oc.obj->transition(oc.bucket, target_placement, o.meta.mtime,
o.versioned_epoch, oc.dpp, null_yield);
if (r < 0) {
ldpp_dout(oc.dpp, 0) << "ERROR: failed to transition obj "
<< oc.bucket << ":" << o.key
<< " -> " << transition.storage_class
<< " " << cpp_strerror(r)
<< " " << oc.wq->thr_name() << dendl;
return r;
}
}
ldpp_dout(oc.dpp, 2) << "TRANSITIONED:" << oc.bucket
<< ":" << o.key << " -> "
<< transition.storage_class
<< " " << oc.wq->thr_name() << dendl;
return 0;
}
};
class LCOpAction_CurrentTransition : public LCOpAction_Transition {
protected:
bool check_current_state(bool is_current) override {
return is_current;
}
ceph::real_time get_effective_mtime(lc_op_ctx& oc) override {
return oc.o.meta.mtime;
}
public:
LCOpAction_CurrentTransition(const transition_action& _transition)
: LCOpAction_Transition(_transition) {}
int process(lc_op_ctx& oc) {
int r = LCOpAction_Transition::process(oc);
if (r == 0) {
if (perfcounter) {
perfcounter->inc(l_rgw_lc_transition_current, 1);
}
}
return r;
}
};
class LCOpAction_NonCurrentTransition : public LCOpAction_Transition {
protected:
bool check_current_state(bool is_current) override {
return !is_current;
}
ceph::real_time get_effective_mtime(lc_op_ctx& oc) override {
return oc.effective_mtime;
}
public:
LCOpAction_NonCurrentTransition(op_env& env,
const transition_action& _transition)
: LCOpAction_Transition(_transition)
{}
int process(lc_op_ctx& oc) {
int r = LCOpAction_Transition::process(oc);
if (r == 0) {
if (perfcounter) {
perfcounter->inc(l_rgw_lc_transition_noncurrent, 1);
}
}
return r;
}
};
void LCOpRule::build()
{
filters.emplace_back(new LCOpFilter_Tags);
auto& op = env.op;
if (op.expiration > 0 ||
op.expiration_date != boost::none) {
actions.emplace_back(new LCOpAction_CurrentExpiration(env));
}
if (op.dm_expiration) {
actions.emplace_back(new LCOpAction_DMExpiration(env));
}
if (op.noncur_expiration > 0) {
actions.emplace_back(new LCOpAction_NonCurrentExpiration(env));
}
for (auto& iter : op.transitions) {
actions.emplace_back(new LCOpAction_CurrentTransition(iter.second));
}
for (auto& iter : op.noncur_transitions) {
actions.emplace_back(new LCOpAction_NonCurrentTransition(env, iter.second));
}
}
void LCOpRule::update()
{
next_key_name = env.ol.next_key_name();
effective_mtime = env.ol.get_prev_obj().meta.mtime;
}
int LCOpRule::process(rgw_bucket_dir_entry& o,
const DoutPrefixProvider *dpp,
WorkQ* wq)
{
lc_op_ctx ctx(env, o, next_key_name, effective_mtime, dpp, wq);
shared_ptr<LCOpAction> *selected = nullptr; // n.b., req'd by sharing
real_time exp;
for (auto& a : actions) {
real_time action_exp;
if (a->check(ctx, &action_exp, dpp)) {
if (action_exp > exp) {
exp = action_exp;
selected = &a;
}
}
}
if (selected &&
(*selected)->should_process()) {
/*
* Calling filter checks after action checks because
* all action checks (as they are implemented now) do
* not access the objects themselves, but return result
* from info from bucket index listing. The current tags filter
* check does access the objects, so we avoid unnecessary rados calls
* having filters check later in the process.
*/
bool cont = false;
for (auto& f : filters) {
if (f->check(dpp, ctx)) {
cont = true;
break;
}
}
if (!cont) {
ldpp_dout(dpp, 20) << __func__ << "(): key=" << o.key
<< ": no rule match, skipping "
<< wq->thr_name() << dendl;
return 0;
}
int r = (*selected)->process(ctx);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: remove_expired_obj "
<< env.bucket << ":" << o.key
<< " " << cpp_strerror(r)
<< " " << wq->thr_name() << dendl;
return r;
}
ldpp_dout(dpp, 20) << "processed:" << env.bucket << ":"
<< o.key << " " << wq->thr_name() << dendl;
}
return 0;
}
int RGWLC::bucket_lc_process(string& shard_id, LCWorker* worker,
time_t stop_at, bool once)
{
RGWLifecycleConfiguration config(cct);
std::unique_ptr<rgw::sal::Bucket> bucket;
string no_ns, list_versions;
vector<rgw_bucket_dir_entry> objs;
vector<std::string> result;
boost::split(result, shard_id, boost::is_any_of(":"));
string bucket_tenant = result[0];
string bucket_name = result[1];
string bucket_marker = result[2];
ldpp_dout(this, 5) << "RGWLC::bucket_lc_process ENTER " << bucket_name << dendl;
if (unlikely(cct->_conf->rgwlc_skip_bucket_step)) {
return 0;
}
int ret = driver->get_bucket(this, nullptr, bucket_tenant, bucket_name, &bucket, null_yield);
if (ret < 0) {
ldpp_dout(this, 0) << "LC:get_bucket for " << bucket_name
<< " failed" << dendl;
return ret;
}
ret = bucket->load_bucket(this, null_yield);
if (ret < 0) {
ldpp_dout(this, 0) << "LC:load_bucket for " << bucket_name
<< " failed" << dendl;
return ret;
}
auto stack_guard = make_scope_guard(
[&worker]
{
worker->workpool->drain();
}
);
if (bucket->get_marker() != bucket_marker) {
ldpp_dout(this, 1) << "LC: deleting stale entry found for bucket="
<< bucket_tenant << ":" << bucket_name
<< " cur_marker=" << bucket->get_marker()
<< " orig_marker=" << bucket_marker << dendl;
return -ENOENT;
}
map<string, bufferlist>::iterator aiter
= bucket->get_attrs().find(RGW_ATTR_LC);
if (aiter == bucket->get_attrs().end()) {
ldpp_dout(this, 0) << "WARNING: bucket_attrs.find(RGW_ATTR_LC) failed for "
<< bucket_name << " (terminates bucket_lc_process(...))"
<< dendl;
return 0;
}
bufferlist::const_iterator iter{&aiter->second};
try {
config.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(this, 0) << __func__ << "() decode life cycle config failed"
<< dendl;
return -1;
}
/* fetch information for zone checks */
rgw::sal::Zone* zone = driver->get_zone();
auto pf = [](RGWLC::LCWorker* wk, WorkQ* wq, WorkItem& wi) {
auto wt =
boost::get<std::tuple<LCOpRule, rgw_bucket_dir_entry>>(wi);
auto& [op_rule, o] = wt;
ldpp_dout(wk->get_lc(), 20)
<< __func__ << "(): key=" << o.key << wq->thr_name()
<< dendl;
int ret = op_rule.process(o, wk->dpp, wq);
if (ret < 0) {
ldpp_dout(wk->get_lc(), 20)
<< "ERROR: orule.process() returned ret=" << ret
<< "thread:" << wq->thr_name()
<< dendl;
}
};
worker->workpool->setf(pf);
multimap<string, lc_op>& prefix_map = config.get_prefix_map();
ldpp_dout(this, 10) << __func__ << "() prefix_map size="
<< prefix_map.size()
<< dendl;
rgw_obj_key pre_marker;
rgw_obj_key next_marker;
for(auto prefix_iter = prefix_map.begin(); prefix_iter != prefix_map.end();
++prefix_iter) {
if (worker_should_stop(stop_at, once)) {
ldpp_dout(this, 5) << __func__ << " interval budget EXPIRED worker "
<< worker->ix
<< dendl;
return 0;
}
auto& op = prefix_iter->second;
if (!is_valid_op(op)) {
continue;
}
ldpp_dout(this, 20) << __func__ << "(): prefix=" << prefix_iter->first
<< dendl;
if (prefix_iter != prefix_map.begin() &&
(prefix_iter->first.compare(0, prev(prefix_iter)->first.length(),
prev(prefix_iter)->first) == 0)) {
next_marker = pre_marker;
} else {
pre_marker = next_marker;
}
LCObjsLister ol(driver, bucket.get());
ol.set_prefix(prefix_iter->first);
if (! zone_check(op, zone)) {
ldpp_dout(this, 7) << "LC rule not executable in " << zone->get_tier_type()
<< " zone, skipping" << dendl;
continue;
}
ret = ol.init(this);
if (ret < 0) {
if (ret == (-ENOENT))
return 0;
ldpp_dout(this, 0) << "ERROR: driver->list_objects():" << dendl;
return ret;
}
op_env oenv(op, driver, worker, bucket.get(), ol);
LCOpRule orule(oenv);
orule.build(); // why can't ctor do it?
rgw_bucket_dir_entry* o{nullptr};
for (auto offset = 0; ol.get_obj(this, &o /* , fetch_barrier */); ++offset, ol.next()) {
orule.update();
std::tuple<LCOpRule, rgw_bucket_dir_entry> t1 = {orule, *o};
worker->workpool->enqueue(WorkItem{t1});
if ((offset % 100) == 0) {
if (worker_should_stop(stop_at, once)) {
ldpp_dout(this, 5) << __func__ << " interval budget EXPIRED worker "
<< worker->ix
<< dendl;
return 0;
}
}
}
worker->workpool->drain();
}
ret = handle_multipart_expiration(bucket.get(), prefix_map, worker, stop_at, once);
return ret;
}
class SimpleBackoff
{
const int max_retries;
std::chrono::milliseconds sleep_ms;
int retries{0};
public:
SimpleBackoff(int max_retries, std::chrono::milliseconds initial_sleep_ms)
: max_retries(max_retries), sleep_ms(initial_sleep_ms)
{}
SimpleBackoff(const SimpleBackoff&) = delete;
SimpleBackoff& operator=(const SimpleBackoff&) = delete;
int get_retries() const {
return retries;
}
void reset() {
retries = 0;
}
bool wait_backoff(const fu2::unique_function<bool(void) const>& barrier) {
reset();
while (retries < max_retries) {
auto r = barrier();
if (r) {
return r;
}
std::this_thread::sleep_for(sleep_ms * 2 * retries++);
}
return false;
}
};
int RGWLC::bucket_lc_post(int index, int max_lock_sec,
rgw::sal::Lifecycle::LCEntry& entry, int& result,
LCWorker* worker)
{
utime_t lock_duration(cct->_conf->rgw_lc_lock_max_time, 0);
std::unique_ptr<rgw::sal::LCSerializer> lock =
sal_lc->get_serializer(lc_index_lock_name, obj_names[index], cookie);
ldpp_dout(this, 5) << "RGWLC::bucket_lc_post(): POST " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< dendl;
do {
int ret = lock->try_lock(this, lock_duration, null_yield);
if (ret == -EBUSY || ret == -EEXIST) {
/* already locked by another lc processor */
ldpp_dout(this, 0) << "RGWLC::bucket_lc_post() failed to acquire lock on "
<< obj_names[index] << ", sleep 5, try again " << dendl;
sleep(5);
continue;
}
if (ret < 0)
return 0;
ldpp_dout(this, 20) << "RGWLC::bucket_lc_post() lock " << obj_names[index]
<< dendl;
if (result == -ENOENT) {
/* XXXX are we SURE the only way result could == ENOENT is when
* there is no such bucket? It is currently the value returned
* from bucket_lc_process(...) */
ret = sal_lc->rm_entry(obj_names[index], entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::bucket_lc_post() failed to remove entry "
<< obj_names[index] << dendl;
}
goto clean;
} else if (result < 0) {
entry.set_status(lc_failed);
} else {
entry.set_status(lc_complete);
}
ret = sal_lc->set_entry(obj_names[index], entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to set entry on "
<< obj_names[index] << dendl;
}
clean:
lock->unlock();
ldpp_dout(this, 20) << "RGWLC::bucket_lc_post() unlock "
<< obj_names[index] << dendl;
return 0;
} while (true);
} /* RGWLC::bucket_lc_post */
int RGWLC::list_lc_progress(string& marker, uint32_t max_entries,
vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>>& progress_map,
int& index)
{
progress_map.clear();
for(; index < max_objs; index++, marker="") {
vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>> entries;
int ret = sal_lc->list_entries(obj_names[index], marker, max_entries, entries);
if (ret < 0) {
if (ret == -ENOENT) {
ldpp_dout(this, 10) << __func__ << "() ignoring unfound lc object="
<< obj_names[index] << dendl;
continue;
} else {
return ret;
}
}
progress_map.reserve(progress_map.size() + entries.size());
std::move(begin(entries), end(entries), std::back_inserter(progress_map));
//progress_map.insert(progress_map.end(), entries.begin(), entries.end());
/* update index, marker tuple */
if (progress_map.size() > 0)
marker = progress_map.back()->get_bucket();
if (progress_map.size() >= max_entries)
break;
}
return 0;
}
static inline vector<int> random_sequence(uint32_t n)
{
vector<int> v(n, 0);
std::generate(v.begin(), v.end(),
[ix = 0]() mutable {
return ix++;
});
std::random_device rd;
std::default_random_engine rng{rd()};
std::shuffle(v.begin(), v.end(), rng);
return v;
}
static inline int get_lc_index(CephContext *cct,
const std::string& shard_id)
{
int max_objs =
(cct->_conf->rgw_lc_max_objs > HASH_PRIME ? HASH_PRIME :
cct->_conf->rgw_lc_max_objs);
/* n.b. review hash algo */
int index = ceph_str_hash_linux(shard_id.c_str(),
shard_id.size()) % HASH_PRIME % max_objs;
return index;
}
static inline void get_lc_oid(CephContext *cct,
const std::string& shard_id, string *oid)
{
/* n.b. review hash algo */
int index = get_lc_index(cct, shard_id);
*oid = lc_oid_prefix;
char buf[32];
snprintf(buf, 32, ".%d", index);
oid->append(buf);
return;
}
static std::string get_bucket_lc_key(const rgw_bucket& bucket){
return string_join_reserve(':', bucket.tenant, bucket.name, bucket.marker);
}
int RGWLC::process(LCWorker* worker,
const std::unique_ptr<rgw::sal::Bucket>& optional_bucket,
bool once = false)
{
int ret = 0;
int max_secs = cct->_conf->rgw_lc_lock_max_time;
if (optional_bucket) {
/* if a bucket is provided, this is a single-bucket run, and
* can be processed without traversing any state entries (we
* do need the entry {pro,epi}logue which update the state entry
* for this bucket) */
auto bucket_lc_key = get_bucket_lc_key(optional_bucket->get_key());
auto index = get_lc_index(driver->ctx(), bucket_lc_key);
ret = process_bucket(index, max_secs, worker, bucket_lc_key, once);
return ret;
} else {
/* generate an index-shard sequence unrelated to any other
* that might be running in parallel */
std::string all_buckets{""};
vector<int> shard_seq = random_sequence(max_objs);
for (auto index : shard_seq) {
ret = process(index, max_secs, worker, once);
if (ret < 0)
return ret;
}
}
return 0;
}
bool RGWLC::expired_session(time_t started)
{
if (! cct->_conf->rgwlc_auto_session_clear) {
return false;
}
time_t interval = (cct->_conf->rgw_lc_debug_interval > 0)
? cct->_conf->rgw_lc_debug_interval
: 24*60*60;
auto now = time(nullptr);
ldpp_dout(this, 16) << "RGWLC::expired_session"
<< " started: " << started
<< " interval: " << interval << "(*2==" << 2*interval << ")"
<< " now: " << now
<< dendl;
return (started + 2*interval < now);
}
time_t RGWLC::thread_stop_at()
{
uint64_t interval = (cct->_conf->rgw_lc_debug_interval > 0)
? cct->_conf->rgw_lc_debug_interval
: 24*60*60;
return time(nullptr) + interval;
}
int RGWLC::process_bucket(int index, int max_lock_secs, LCWorker* worker,
const std::string& bucket_entry_marker,
bool once = false)
{
ldpp_dout(this, 5) << "RGWLC::process_bucket(): ENTER: "
<< "index: " << index << " worker ix: " << worker->ix
<< dendl;
int ret = 0;
std::unique_ptr<rgw::sal::LCSerializer> serializer =
sal_lc->get_serializer(lc_index_lock_name, obj_names[index],
worker->thr_name());
std::unique_ptr<rgw::sal::Lifecycle::LCEntry> entry;
if (max_lock_secs <= 0) {
return -EAGAIN;
}
utime_t time(max_lock_secs, 0);
ret = serializer->try_lock(this, time, null_yield);
if (ret == -EBUSY || ret == -EEXIST) {
/* already locked by another lc processor */
ldpp_dout(this, 0) << "RGWLC::process() failed to acquire lock on "
<< obj_names[index] << dendl;
return -EBUSY;
}
if (ret < 0)
return 0;
std::unique_lock<rgw::sal::LCSerializer> lock(
*(serializer.get()), std::adopt_lock);
ret = sal_lc->get_entry(obj_names[index], bucket_entry_marker, &entry);
if (ret >= 0) {
if (entry->get_status() == lc_processing) {
if (expired_session(entry->get_start_time())) {
ldpp_dout(this, 5) << "RGWLC::process_bucket(): STALE lc session found for: " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< " (clearing)"
<< dendl;
} else {
ldpp_dout(this, 5) << "RGWLC::process_bucket(): ACTIVE entry: "
<< entry
<< " index: " << index
<< " worker ix: " << worker->ix
<< dendl;
return ret;
}
}
}
/* do nothing if no bucket */
if (entry->get_bucket().empty()) {
return ret;
}
ldpp_dout(this, 5) << "RGWLC::process_bucket(): START entry 1: " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< dendl;
entry->set_status(lc_processing);
ret = sal_lc->set_entry(obj_names[index], *entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process_bucket() failed to set obj entry "
<< obj_names[index] << entry->get_bucket() << entry->get_status()
<< dendl;
return ret;
}
ldpp_dout(this, 5) << "RGWLC::process_bucket(): START entry 2: " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< dendl;
lock.unlock();
ret = bucket_lc_process(entry->get_bucket(), worker, thread_stop_at(), once);
bucket_lc_post(index, max_lock_secs, *entry, ret, worker);
return ret;
} /* RGWLC::process_bucket */
static inline bool allow_shard_rollover(CephContext* cct, time_t now, time_t shard_rollover_date)
{
/* return true iff:
* - non-debug scheduling is in effect, and
* - the current shard has not rolled over in the last 24 hours
*/
if (((shard_rollover_date < now) &&
(now - shard_rollover_date > 24*60*60)) ||
(! shard_rollover_date /* no rollover date stored */) ||
(cct->_conf->rgw_lc_debug_interval > 0 /* defaults to -1 == disabled */)) {
return true;
}
return false;
} /* allow_shard_rollover */
static inline bool already_run_today(CephContext* cct, time_t start_date)
{
struct tm bdt;
time_t begin_of_day;
utime_t now = ceph_clock_now();
localtime_r(&start_date, &bdt);
if (cct->_conf->rgw_lc_debug_interval > 0) {
if (now - start_date < cct->_conf->rgw_lc_debug_interval)
return true;
else
return false;
}
bdt.tm_hour = 0;
bdt.tm_min = 0;
bdt.tm_sec = 0;
begin_of_day = mktime(&bdt);
if (now - begin_of_day < 24*60*60)
return true;
else
return false;
} /* already_run_today */
inline int RGWLC::advance_head(const std::string& lc_shard,
rgw::sal::Lifecycle::LCHead& head,
rgw::sal::Lifecycle::LCEntry& entry,
time_t start_date)
{
int ret{0};
std::unique_ptr<rgw::sal::Lifecycle::LCEntry> next_entry;
ret = sal_lc->get_next_entry(lc_shard, entry.get_bucket(), &next_entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to get obj entry "
<< lc_shard << dendl;
goto exit;
}
/* save the next position */
head.set_marker(next_entry->get_bucket());
head.set_start_date(start_date);
ret = sal_lc->put_head(lc_shard, head);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to put head "
<< lc_shard
<< dendl;
goto exit;
}
exit:
return ret;
} /* advance head */
int RGWLC::process(int index, int max_lock_secs, LCWorker* worker,
bool once = false)
{
int ret{0};
const auto& lc_shard = obj_names[index];
std::unique_ptr<rgw::sal::Lifecycle::LCHead> head;
std::unique_ptr<rgw::sal::Lifecycle::LCEntry> entry; //string = bucket_name:bucket_id, start_time, int = LC_BUCKET_STATUS
ldpp_dout(this, 5) << "RGWLC::process(): ENTER: "
<< "index: " << index << " worker ix: " << worker->ix
<< dendl;
std::unique_ptr<rgw::sal::LCSerializer> lock =
sal_lc->get_serializer(lc_index_lock_name, lc_shard, worker->thr_name());
utime_t lock_for_s(max_lock_secs, 0);
const auto& lock_lambda = [&]() {
ret = lock->try_lock(this, lock_for_s, null_yield);
if (ret == 0) {
return true;
}
if (ret == -EBUSY || ret == -EEXIST) {
/* already locked by another lc processor */
return false;
}
return false;
};
SimpleBackoff shard_lock(5 /* max retries */, 50ms);
if (! shard_lock.wait_backoff(lock_lambda)) {
ldpp_dout(this, 0) << "RGWLC::process(): failed to aquire lock on "
<< lc_shard << " after " << shard_lock.get_retries()
<< dendl;
return 0;
}
do {
utime_t now = ceph_clock_now();
/* preamble: find an inital bucket/marker */
ret = sal_lc->get_head(lc_shard, &head);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to get obj head "
<< lc_shard << ", ret=" << ret << dendl;
goto exit;
}
/* if there is nothing at head, try to reinitialize head.marker with the
* first entry in the queue */
if (head->get_marker().empty() &&
allow_shard_rollover(cct, now, head->get_shard_rollover_date()) /* prevent multiple passes by diff.
* rgws,in same cycle */) {
ldpp_dout(this, 5) << "RGWLC::process() process shard rollover lc_shard=" << lc_shard
<< " head.marker=" << head->get_marker()
<< " head.shard_rollover_date=" << head->get_shard_rollover_date()
<< dendl;
vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>> entries;
int ret = sal_lc->list_entries(lc_shard, head->get_marker(), 1, entries);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() sal_lc->list_entries(lc_shard, head.marker, 1, "
<< "entries) returned error ret==" << ret << dendl;
goto exit;
}
if (entries.size() > 0) {
entry = std::move(entries.front());
head->set_marker(entry->get_bucket());
head->set_start_date(now);
head->set_shard_rollover_date(0);
}
} else {
ldpp_dout(this, 0) << "RGWLC::process() head.marker !empty() at START for shard=="
<< lc_shard << " head last stored at "
<< rgw_to_asctime(utime_t(time_t(head->get_start_date()), 0))
<< dendl;
/* fetches the entry pointed to by head.bucket */
ret = sal_lc->get_entry(lc_shard, head->get_marker(), &entry);
if (ret == -ENOENT) {
ret = sal_lc->get_next_entry(lc_shard, head->get_marker(), &entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() sal_lc->get_next_entry(lc_shard, "
<< "head.marker, entry) returned error ret==" << ret
<< dendl;
goto exit;
}
}
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() sal_lc->get_entry(lc_shard, head.marker, entry) "
<< "returned error ret==" << ret << dendl;
goto exit;
}
}
if (entry && !entry->get_bucket().empty()) {
if (entry->get_status() == lc_processing) {
if (expired_session(entry->get_start_time())) {
ldpp_dout(this, 5)
<< "RGWLC::process(): STALE lc session found for: " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< " (clearing)" << dendl;
} else {
ldpp_dout(this, 5)
<< "RGWLC::process(): ACTIVE entry: " << entry
<< " index: " << index << " worker ix: " << worker->ix << dendl;
/* skip to next entry */
if (advance_head(lc_shard, *head.get(), *entry.get(), now) < 0) {
goto exit;
}
/* done with this shard */
if (head->get_marker().empty()) {
ldpp_dout(this, 5) <<
"RGWLC::process() cycle finished lc_shard="
<< lc_shard
<< dendl;
head->set_shard_rollover_date(ceph_clock_now());
ret = sal_lc->put_head(lc_shard, *head.get());
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to put head "
<< lc_shard
<< dendl;
}
goto exit;
}
continue;
}
} else {
if ((entry->get_status() == lc_complete) &&
already_run_today(cct, entry->get_start_time())) {
/* skip to next entry */
if (advance_head(lc_shard, *head.get(), *entry.get(), now) < 0) {
goto exit;
}
ldpp_dout(this, 5) << "RGWLC::process() worker ix; " << worker->ix
<< " SKIP processing for already-processed bucket " << entry->get_bucket()
<< dendl;
/* done with this shard */
if (head->get_marker().empty()) {
ldpp_dout(this, 5) <<
"RGWLC::process() cycle finished lc_shard="
<< lc_shard
<< dendl;
head->set_shard_rollover_date(ceph_clock_now());
ret = sal_lc->put_head(lc_shard, *head.get());
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to put head "
<< lc_shard
<< dendl;
}
goto exit;
}
continue;
}
}
} else {
ldpp_dout(this, 5) << "RGWLC::process() entry.bucket.empty() == true at START 1"
<< " (this is possible mainly before any lc policy has been stored"
<< " or after removal of an lc_shard object)"
<< dendl;
goto exit;
}
/* When there are no more entries to process, entry will be
* equivalent to an empty marker and so the following resets the
* processing for the shard automatically when processing is
* finished for the shard */
ldpp_dout(this, 5) << "RGWLC::process(): START entry 1: " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< dendl;
entry->set_status(lc_processing);
entry->set_start_time(now);
ret = sal_lc->set_entry(lc_shard, *entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to set obj entry "
<< lc_shard << entry->get_bucket() << entry->get_status() << dendl;
goto exit;
}
/* advance head for next waiter, then process */
if (advance_head(lc_shard, *head.get(), *entry.get(), now) < 0) {
goto exit;
}
ldpp_dout(this, 5) << "RGWLC::process(): START entry 2: " << entry
<< " index: " << index << " worker ix: " << worker->ix
<< dendl;
/* drop lock so other instances can make progress while this
* bucket is being processed */
lock->unlock();
ret = bucket_lc_process(entry->get_bucket(), worker, thread_stop_at(), once);
/* postamble */
//bucket_lc_post(index, max_lock_secs, entry, ret, worker);
if (! shard_lock.wait_backoff(lock_lambda)) {
ldpp_dout(this, 0) << "RGWLC::process(): failed to aquire lock on "
<< lc_shard << " after " << shard_lock.get_retries()
<< dendl;
return 0;
}
if (ret == -ENOENT) {
/* XXXX are we SURE the only way result could == ENOENT is when
* there is no such bucket? It is currently the value returned
* from bucket_lc_process(...) */
ret = sal_lc->rm_entry(lc_shard, *entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to remove entry "
<< lc_shard << " (nonfatal)"
<< dendl;
/* not fatal, could result from a race */
}
} else {
if (ret < 0) {
entry->set_status(lc_failed);
} else {
entry->set_status(lc_complete);
}
ret = sal_lc->set_entry(lc_shard, *entry);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to set entry on "
<< lc_shard
<< dendl;
/* fatal, locked */
goto exit;
}
}
/* done with this shard */
if (head->get_marker().empty()) {
ldpp_dout(this, 5) <<
"RGWLC::process() cycle finished lc_shard="
<< lc_shard
<< dendl;
head->set_shard_rollover_date(ceph_clock_now());
ret = sal_lc->put_head(lc_shard, *head.get());
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::process() failed to put head "
<< lc_shard
<< dendl;
}
goto exit;
}
} while(1 && !once && !going_down());
exit:
lock->unlock();
return 0;
}
void RGWLC::start_processor()
{
auto maxw = cct->_conf->rgw_lc_max_worker;
workers.reserve(maxw);
for (int ix = 0; ix < maxw; ++ix) {
auto worker =
std::make_unique<RGWLC::LCWorker>(this /* dpp */, cct, this, ix);
worker->create((string{"lifecycle_thr_"} + to_string(ix)).c_str());
workers.emplace_back(std::move(worker));
}
}
void RGWLC::stop_processor()
{
down_flag = true;
for (auto& worker : workers) {
worker->stop();
worker->join();
}
workers.clear();
}
unsigned RGWLC::get_subsys() const
{
return dout_subsys;
}
std::ostream& RGWLC::gen_prefix(std::ostream& out) const
{
return out << "lifecycle: ";
}
void RGWLC::LCWorker::stop()
{
std::lock_guard l{lock};
cond.notify_all();
}
bool RGWLC::going_down()
{
return down_flag;
}
bool RGWLC::LCWorker::should_work(utime_t& now)
{
int start_hour;
int start_minute;
int end_hour;
int end_minute;
string worktime = cct->_conf->rgw_lifecycle_work_time;
sscanf(worktime.c_str(),"%d:%d-%d:%d",&start_hour, &start_minute,
&end_hour, &end_minute);
struct tm bdt;
time_t tt = now.sec();
localtime_r(&tt, &bdt);
if (cct->_conf->rgw_lc_debug_interval > 0) {
/* We're debugging, so say we can run */
return true;
} else if ((bdt.tm_hour*60 + bdt.tm_min >= start_hour*60 + start_minute) &&
(bdt.tm_hour*60 + bdt.tm_min <= end_hour*60 + end_minute)) {
return true;
} else {
return false;
}
}
int RGWLC::LCWorker::schedule_next_start_time(utime_t &start, utime_t& now)
{
int secs;
if (cct->_conf->rgw_lc_debug_interval > 0) {
secs = start + cct->_conf->rgw_lc_debug_interval - now;
if (secs < 0)
secs = 0;
return (secs);
}
int start_hour;
int start_minute;
int end_hour;
int end_minute;
string worktime = cct->_conf->rgw_lifecycle_work_time;
sscanf(worktime.c_str(),"%d:%d-%d:%d",&start_hour, &start_minute, &end_hour,
&end_minute);
struct tm bdt;
time_t tt = now.sec();
time_t nt;
localtime_r(&tt, &bdt);
bdt.tm_hour = start_hour;
bdt.tm_min = start_minute;
bdt.tm_sec = 0;
nt = mktime(&bdt);
secs = nt - tt;
return secs>0 ? secs : secs+24*60*60;
}
RGWLC::LCWorker::~LCWorker()
{
delete workpool;
} /* ~LCWorker */
void RGWLifecycleConfiguration::generate_test_instances(
list<RGWLifecycleConfiguration*>& o)
{
o.push_back(new RGWLifecycleConfiguration);
}
template<typename F>
static int guard_lc_modify(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
rgw::sal::Lifecycle* sal_lc,
const rgw_bucket& bucket, const string& cookie,
const F& f) {
CephContext *cct = driver->ctx();
auto bucket_lc_key = get_bucket_lc_key(bucket);
string oid;
get_lc_oid(cct, bucket_lc_key, &oid);
/* XXX it makes sense to take shard_id for a bucket_id? */
std::unique_ptr<rgw::sal::Lifecycle::LCEntry> entry = sal_lc->get_entry();
entry->set_bucket(bucket_lc_key);
entry->set_status(lc_uninitial);
int max_lock_secs = cct->_conf->rgw_lc_lock_max_time;
std::unique_ptr<rgw::sal::LCSerializer> lock =
sal_lc->get_serializer(lc_index_lock_name, oid, cookie);
utime_t time(max_lock_secs, 0);
int ret;
uint16_t retries{0};
// due to reports of starvation trying to save lifecycle policy, try hard
do {
ret = lock->try_lock(dpp, time, null_yield);
if (ret == -EBUSY || ret == -EEXIST) {
ldpp_dout(dpp, 0) << "RGWLC::RGWPutLC() failed to acquire lock on "
<< oid << ", retry in 100ms, ret=" << ret << dendl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// the typical S3 client will time out in 60s
if(retries++ < 500) {
continue;
}
}
if (ret < 0) {
ldpp_dout(dpp, 0) << "RGWLC::RGWPutLC() failed to acquire lock on "
<< oid << ", ret=" << ret << dendl;
break;
}
ret = f(sal_lc, oid, *entry.get());
if (ret < 0) {
ldpp_dout(dpp, 0) << "RGWLC::RGWPutLC() failed to set entry on "
<< oid << ", ret=" << ret << dendl;
}
break;
} while(true);
lock->unlock();
return ret;
}
int RGWLC::set_bucket_config(rgw::sal::Bucket* bucket,
const rgw::sal::Attrs& bucket_attrs,
RGWLifecycleConfiguration *config)
{
int ret{0};
rgw::sal::Attrs attrs = bucket_attrs;
if (config) {
/* if no RGWLifecycleconfiguration provided, it means
* RGW_ATTR_LC is already valid and present */
bufferlist lc_bl;
config->encode(lc_bl);
attrs[RGW_ATTR_LC] = std::move(lc_bl);
ret =
bucket->merge_and_store_attrs(this, attrs, null_yield);
if (ret < 0) {
return ret;
}
}
rgw_bucket& b = bucket->get_key();
ret = guard_lc_modify(this, driver, sal_lc.get(), b, cookie,
[&](rgw::sal::Lifecycle* sal_lc, const string& oid,
rgw::sal::Lifecycle::LCEntry& entry) {
return sal_lc->set_entry(oid, entry);
});
return ret;
}
int RGWLC::remove_bucket_config(rgw::sal::Bucket* bucket,
const rgw::sal::Attrs& bucket_attrs,
bool merge_attrs)
{
rgw::sal::Attrs attrs = bucket_attrs;
rgw_bucket& b = bucket->get_key();
int ret{0};
if (merge_attrs) {
attrs.erase(RGW_ATTR_LC);
ret = bucket->merge_and_store_attrs(this, attrs, null_yield);
if (ret < 0) {
ldpp_dout(this, 0) << "RGWLC::RGWDeleteLC() failed to set attrs on bucket="
<< b.name << " returned err=" << ret << dendl;
return ret;
}
}
ret = guard_lc_modify(this, driver, sal_lc.get(), b, cookie,
[&](rgw::sal::Lifecycle* sal_lc, const string& oid,
rgw::sal::Lifecycle::LCEntry& entry) {
return sal_lc->rm_entry(oid, entry);
});
return ret;
} /* RGWLC::remove_bucket_config */
RGWLC::~RGWLC()
{
stop_processor();
finalize();
} /* ~RGWLC() */
namespace rgw::lc {
int fix_lc_shard_entry(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
rgw::sal::Lifecycle* sal_lc,
rgw::sal::Bucket* bucket)
{
if (auto aiter = bucket->get_attrs().find(RGW_ATTR_LC);
aiter == bucket->get_attrs().end()) {
return 0; // No entry, nothing to fix
}
auto bucket_lc_key = get_bucket_lc_key(bucket->get_key());
std::string lc_oid;
get_lc_oid(driver->ctx(), bucket_lc_key, &lc_oid);
std::unique_ptr<rgw::sal::Lifecycle::LCEntry> entry;
// There are multiple cases we need to encounter here
// 1. entry exists and is already set to marker, happens in plain buckets & newly resharded buckets
// 2. entry doesn't exist, which usually happens when reshard has happened prior to update and next LC process has already dropped the update
// 3. entry exists matching the current bucket id which was after a reshard (needs to be updated to the marker)
// We are not dropping the old marker here as that would be caught by the next LC process update
int ret = sal_lc->get_entry(lc_oid, bucket_lc_key, &entry);
if (ret == 0) {
ldpp_dout(dpp, 5) << "Entry already exists, nothing to do" << dendl;
return ret; // entry is already existing correctly set to marker
}
ldpp_dout(dpp, 5) << "lc_get_entry errored ret code=" << ret << dendl;
if (ret == -ENOENT) {
ldpp_dout(dpp, 1) << "No entry for bucket=" << bucket
<< " creating " << dendl;
// TODO: we have too many ppl making cookies like this!
char cookie_buf[COOKIE_LEN + 1];
gen_rand_alphanumeric(driver->ctx(), cookie_buf, sizeof(cookie_buf) - 1);
std::string cookie = cookie_buf;
ret = guard_lc_modify(dpp,
driver, sal_lc, bucket->get_key(), cookie,
[&lc_oid](rgw::sal::Lifecycle* slc,
const string& oid,
rgw::sal::Lifecycle::LCEntry& entry) {
return slc->set_entry(lc_oid, entry);
});
}
return ret;
}
std::string s3_expiration_header(
DoutPrefixProvider* dpp,
const rgw_obj_key& obj_key,
const RGWObjTags& obj_tagset,
const ceph::real_time& mtime,
const std::map<std::string, buffer::list>& bucket_attrs)
{
CephContext* cct = dpp->get_cct();
RGWLifecycleConfiguration config(cct);
std::string hdr{""};
const auto& aiter = bucket_attrs.find(RGW_ATTR_LC);
if (aiter == bucket_attrs.end())
return hdr;
bufferlist::const_iterator iter{&aiter->second};
try {
config.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(dpp, 0) << __func__
<< "() decode life cycle config failed"
<< dendl;
return hdr;
} /* catch */
/* dump tags at debug level 16 */
RGWObjTags::tag_map_t obj_tag_map = obj_tagset.get_tags();
if (cct->_conf->subsys.should_gather(ceph_subsys_rgw, 16)) {
for (const auto& elt : obj_tag_map) {
ldpp_dout(dpp, 16) << __func__
<< "() key=" << elt.first << " val=" << elt.second
<< dendl;
}
}
boost::optional<ceph::real_time> expiration_date;
boost::optional<std::string> rule_id;
const auto& rule_map = config.get_rule_map();
for (const auto& ri : rule_map) {
const auto& rule = ri.second;
auto& id = rule.get_id();
auto& filter = rule.get_filter();
auto& prefix = filter.has_prefix() ? filter.get_prefix(): rule.get_prefix();
auto& expiration = rule.get_expiration();
auto& noncur_expiration = rule.get_noncur_expiration();
ldpp_dout(dpp, 10) << "rule: " << ri.first
<< " prefix: " << prefix
<< " expiration: "
<< " date: " << expiration.get_date()
<< " days: " << expiration.get_days()
<< " noncur_expiration: "
<< " date: " << noncur_expiration.get_date()
<< " days: " << noncur_expiration.get_days()
<< dendl;
/* skip if rule !enabled
* if rule has prefix, skip iff object !match prefix
* if rule has tags, skip iff object !match tags
* note if object is current or non-current, compare accordingly
* if rule has days, construct date expression and save iff older
* than last saved
* if rule has date, convert date expression and save iff older
* than last saved
* if the date accum has a value, format it into hdr
*/
if (! rule.is_enabled())
continue;
if(! prefix.empty()) {
if (! boost::starts_with(obj_key.name, prefix))
continue;
}
if (filter.has_tags()) {
bool tag_match = false;
const RGWObjTags& rule_tagset = filter.get_tags();
for (auto& tag : rule_tagset.get_tags()) {
/* remember, S3 tags are {key,value} tuples */
tag_match = true;
auto obj_tag = obj_tag_map.find(tag.first);
if (obj_tag == obj_tag_map.end() || obj_tag->second != tag.second) {
ldpp_dout(dpp, 10) << "tag does not match obj_key=" << obj_key
<< " rule_id=" << id
<< " tag=" << tag
<< dendl;
tag_match = false;
break;
}
}
if (! tag_match)
continue;
}
// compute a uniform expiration date
boost::optional<ceph::real_time> rule_expiration_date;
const LCExpiration& rule_expiration =
(obj_key.instance.empty()) ? expiration : noncur_expiration;
if (rule_expiration.has_date()) {
rule_expiration_date =
boost::optional<ceph::real_time>(
ceph::from_iso_8601(rule.get_expiration().get_date()));
} else {
if (rule_expiration.has_days()) {
rule_expiration_date =
boost::optional<ceph::real_time>(
mtime + make_timespan(double(rule_expiration.get_days())*24*60*60 - ceph::real_clock::to_time_t(mtime)%(24*60*60) + 24*60*60));
}
}
// update earliest expiration
if (rule_expiration_date) {
if ((! expiration_date) ||
(*expiration_date > *rule_expiration_date)) {
expiration_date =
boost::optional<ceph::real_time>(rule_expiration_date);
rule_id = boost::optional<std::string>(id);
}
}
}
// cond format header
if (expiration_date && rule_id) {
// Fri, 23 Dec 2012 00:00:00 GMT
char exp_buf[100];
time_t exp = ceph::real_clock::to_time_t(*expiration_date);
if (std::strftime(exp_buf, sizeof(exp_buf),
"%a, %d %b %Y %T %Z", std::gmtime(&exp))) {
hdr = fmt::format("expiry-date=\"{0}\", rule-id=\"{1}\"", exp_buf,
*rule_id);
} else {
ldpp_dout(dpp, 0) << __func__ <<
"() strftime of life cycle expiration header failed"
<< dendl;
}
}
return hdr;
} /* rgwlc_s3_expiration_header */
bool s3_multipart_abort_header(
DoutPrefixProvider* dpp,
const rgw_obj_key& obj_key,
const ceph::real_time& mtime,
const std::map<std::string, buffer::list>& bucket_attrs,
ceph::real_time& abort_date,
std::string& rule_id)
{
CephContext* cct = dpp->get_cct();
RGWLifecycleConfiguration config(cct);
const auto& aiter = bucket_attrs.find(RGW_ATTR_LC);
if (aiter == bucket_attrs.end())
return false;
bufferlist::const_iterator iter{&aiter->second};
try {
config.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(dpp, 0) << __func__
<< "() decode life cycle config failed"
<< dendl;
return false;
} /* catch */
std::optional<ceph::real_time> abort_date_tmp;
std::optional<std::string_view> rule_id_tmp;
const auto& rule_map = config.get_rule_map();
for (const auto& ri : rule_map) {
const auto& rule = ri.second;
const auto& id = rule.get_id();
const auto& filter = rule.get_filter();
const auto& prefix = filter.has_prefix()?filter.get_prefix():rule.get_prefix();
const auto& mp_expiration = rule.get_mp_expiration();
if (!rule.is_enabled()) {
continue;
}
if(!prefix.empty() && !boost::starts_with(obj_key.name, prefix)) {
continue;
}
std::optional<ceph::real_time> rule_abort_date;
if (mp_expiration.has_days()) {
rule_abort_date = std::optional<ceph::real_time>(
mtime + make_timespan(mp_expiration.get_days()*24*60*60 - ceph::real_clock::to_time_t(mtime)%(24*60*60) + 24*60*60));
}
// update earliest abort date
if (rule_abort_date) {
if ((! abort_date_tmp) ||
(*abort_date_tmp > *rule_abort_date)) {
abort_date_tmp =
std::optional<ceph::real_time>(rule_abort_date);
rule_id_tmp = std::optional<std::string_view>(id);
}
}
}
if (abort_date_tmp && rule_id_tmp) {
abort_date = *abort_date_tmp;
rule_id = *rule_id_tmp;
return true;
} else {
return false;
}
}
} /* namespace rgw::lc */
void lc_op::dump(Formatter *f) const
{
f->dump_bool("status", status);
f->dump_bool("dm_expiration", dm_expiration);
f->dump_int("expiration", expiration);
f->dump_int("noncur_expiration", noncur_expiration);
f->dump_int("mp_expiration", mp_expiration);
if (expiration_date) {
utime_t ut(*expiration_date);
f->dump_stream("expiration_date") << ut;
}
if (obj_tags) {
f->dump_object("obj_tags", *obj_tags);
}
f->open_object_section("transitions");
for(auto& [storage_class, transition] : transitions) {
f->dump_object(storage_class, transition);
}
f->close_section();
f->open_object_section("noncur_transitions");
for (auto& [storage_class, transition] : noncur_transitions) {
f->dump_object(storage_class, transition);
}
f->close_section();
}
void LCFilter::dump(Formatter *f) const
{
f->dump_string("prefix", prefix);
f->dump_object("obj_tags", obj_tags);
if (have_flag(LCFlagType::ArchiveZone)) {
f->dump_string("archivezone", "");
}
}
void LCExpiration::dump(Formatter *f) const
{
f->dump_string("days", days);
f->dump_string("date", date);
}
void LCRule::dump(Formatter *f) const
{
f->dump_string("id", id);
f->dump_string("prefix", prefix);
f->dump_string("status", status);
f->dump_object("expiration", expiration);
f->dump_object("noncur_expiration", noncur_expiration);
f->dump_object("mp_expiration", mp_expiration);
f->dump_object("filter", filter);
f->open_object_section("transitions");
for (auto& [storage_class, transition] : transitions) {
f->dump_object(storage_class, transition);
}
f->close_section();
f->open_object_section("noncur_transitions");
for (auto& [storage_class, transition] : noncur_transitions) {
f->dump_object(storage_class, transition);
}
f->close_section();
f->dump_bool("dm_expiration", dm_expiration);
}
void RGWLifecycleConfiguration::dump(Formatter *f) const
{
f->open_object_section("prefix_map");
for (auto& prefix : prefix_map) {
f->dump_object(prefix.first.c_str(), prefix.second);
}
f->close_section();
f->open_array_section("rule_map");
for (auto& rule : rule_map) {
f->open_object_section("entry");
f->dump_string("id", rule.first);
f->open_object_section("rule");
rule.second.dump(f);
f->close_section();
f->close_section();
}
f->close_section();
}
| 83,523 | 28.102439 | 193 |
cc
|
null |
ceph-main/src/rgw/rgw_lc.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <array>
#include <string>
#include <iostream>
#include "common/debug.h"
#include "include/types.h"
#include "include/rados/librados.hpp"
#include "common/ceph_mutex.h"
#include "common/Cond.h"
#include "common/iso_8601.h"
#include "common/Thread.h"
#include "rgw_common.h"
#include "cls/rgw/cls_rgw_types.h"
#include "rgw_tag.h"
#include "rgw_sal.h"
#include <atomic>
#include <tuple>
#define HASH_PRIME 7877
#define MAX_ID_LEN 255
static std::string lc_oid_prefix = "lc";
static std::string lc_index_lock_name = "lc_process";
extern const char* LC_STATUS[];
typedef enum {
lc_uninitial = 0,
lc_processing,
lc_failed,
lc_complete,
} LC_BUCKET_STATUS;
class LCExpiration
{
protected:
std::string days;
//At present only current object has expiration date
std::string date;
public:
LCExpiration() {}
LCExpiration(const std::string& _days, const std::string& _date) : days(_days), date(_date) {}
void encode(bufferlist& bl) const {
ENCODE_START(3, 2, bl);
encode(days, bl);
encode(date, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(3, 2, 2, bl);
decode(days, bl);
if (struct_v >= 3) {
decode(date, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
// static void generate_test_instances(list<ACLOwner*>& o);
void set_days(const std::string& _days) { days = _days; }
std::string get_days_str() const {
return days;
}
int get_days() const {return atoi(days.c_str()); }
bool has_days() const {
return !days.empty();
}
void set_date(const std::string& _date) { date = _date; }
std::string get_date() const {
return date;
}
bool has_date() const {
return !date.empty();
}
bool empty() const {
return days.empty() && date.empty();
}
bool valid() const {
if (!days.empty() && !date.empty()) {
return false;
} else if (!days.empty() && get_days() <= 0) {
return false;
}
//We've checked date in xml parsing
return true;
}
};
WRITE_CLASS_ENCODER(LCExpiration)
class LCTransition
{
protected:
std::string days;
std::string date;
std::string storage_class;
public:
int get_days() const {
return atoi(days.c_str());
}
std::string get_date() const {
return date;
}
std::string get_storage_class() const {
return storage_class;
}
bool has_days() const {
return !days.empty();
}
bool has_date() const {
return !date.empty();
}
bool empty() const {
return days.empty() && date.empty();
}
bool valid() const {
if (!days.empty() && !date.empty()) {
return false;
} else if (!days.empty() && get_days() < 0) {
return false;
}
//We've checked date in xml parsing
return true;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(days, bl);
encode(date, bl);
encode(storage_class, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(days, bl);
decode(date, bl);
decode(storage_class, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const {
f->dump_string("days", days);
f->dump_string("date", date);
f->dump_string("storage_class", storage_class);
}
};
WRITE_CLASS_ENCODER(LCTransition)
enum class LCFlagType : uint16_t
{
none = 0,
ArchiveZone,
};
class LCFlag {
public:
LCFlagType bit;
const char* name;
constexpr LCFlag(LCFlagType ord, const char* name) : bit(ord), name(name)
{}
};
class LCFilter
{
public:
static constexpr uint32_t make_flag(LCFlagType type) {
switch (type) {
case LCFlagType::none:
return 0;
break;
default:
return 1 << (uint32_t(type) - 1);
}
}
static constexpr std::array<LCFlag, 2> filter_flags =
{
LCFlag(LCFlagType::none, "none"),
LCFlag(LCFlagType::ArchiveZone, "ArchiveZone"),
};
protected:
std::string prefix;
RGWObjTags obj_tags;
uint32_t flags;
public:
LCFilter() : flags(make_flag(LCFlagType::none))
{}
const std::string& get_prefix() const {
return prefix;
}
const RGWObjTags& get_tags() const {
return obj_tags;
}
const uint32_t get_flags() const {
return flags;
}
bool empty() const {
return !(has_prefix() || has_tags() || has_flags());
}
// Determine if we need AND tag when creating xml
bool has_multi_condition() const {
if (obj_tags.count() + int(has_prefix()) + int(has_flags()) > 1) // Prefix is a member of Filter
return true;
return false;
}
bool has_prefix() const {
return !prefix.empty();
}
bool has_tags() const {
return !obj_tags.empty();
}
bool has_flags() const {
return !(flags == uint32_t(LCFlagType::none));
}
bool have_flag(LCFlagType flag) const {
return flags & make_flag(flag);
}
void encode(bufferlist& bl) const {
ENCODE_START(3, 1, bl);
encode(prefix, bl);
encode(obj_tags, bl);
encode(flags, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(3, bl);
decode(prefix, bl);
if (struct_v >= 2) {
decode(obj_tags, bl);
if (struct_v >= 3) {
decode(flags, bl);
}
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(LCFilter)
class LCRule
{
protected:
std::string id;
std::string prefix;
std::string status;
LCExpiration expiration;
LCExpiration noncur_expiration;
LCExpiration mp_expiration;
LCFilter filter;
std::map<std::string, LCTransition> transitions;
std::map<std::string, LCTransition> noncur_transitions;
bool dm_expiration = false;
public:
LCRule(){};
virtual ~LCRule() {}
const std::string& get_id() const {
return id;
}
const std::string& get_status() const {
return status;
}
bool is_enabled() const {
return status == "Enabled";
}
void set_enabled(bool flag) {
status = (flag ? "Enabled" : "Disabled");
}
const std::string& get_prefix() const {
return prefix;
}
const LCFilter& get_filter() const {
return filter;
}
const LCExpiration& get_expiration() const {
return expiration;
}
const LCExpiration& get_noncur_expiration() const {
return noncur_expiration;
}
const LCExpiration& get_mp_expiration() const {
return mp_expiration;
}
bool get_dm_expiration() const {
return dm_expiration;
}
const std::map<std::string, LCTransition>& get_transitions() const {
return transitions;
}
const std::map<std::string, LCTransition>& get_noncur_transitions() const {
return noncur_transitions;
}
void set_id(const std::string& _id) {
id = _id;
}
void set_prefix(const std::string& _prefix) {
prefix = _prefix;
}
void set_status(const std::string& _status) {
status = _status;
}
void set_expiration(const LCExpiration& _expiration) {
expiration = _expiration;
}
void set_noncur_expiration(const LCExpiration& _noncur_expiration) {
noncur_expiration = _noncur_expiration;
}
void set_mp_expiration(const LCExpiration& _mp_expiration) {
mp_expiration = _mp_expiration;
}
void set_dm_expiration(bool _dm_expiration) {
dm_expiration = _dm_expiration;
}
bool add_transition(const LCTransition& _transition) {
auto ret = transitions.emplace(_transition.get_storage_class(), _transition);
return ret.second;
}
bool add_noncur_transition(const LCTransition& _noncur_transition) {
auto ret = noncur_transitions.emplace(_noncur_transition.get_storage_class(), _noncur_transition);
return ret.second;
}
bool valid() const;
void encode(bufferlist& bl) const {
ENCODE_START(6, 1, bl);
encode(id, bl);
encode(prefix, bl);
encode(status, bl);
encode(expiration, bl);
encode(noncur_expiration, bl);
encode(mp_expiration, bl);
encode(dm_expiration, bl);
encode(filter, bl);
encode(transitions, bl);
encode(noncur_transitions, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(6, 1, 1, bl);
decode(id, bl);
decode(prefix, bl);
decode(status, bl);
decode(expiration, bl);
if (struct_v >=2) {
decode(noncur_expiration, bl);
}
if (struct_v >= 3) {
decode(mp_expiration, bl);
}
if (struct_v >= 4) {
decode(dm_expiration, bl);
}
if (struct_v >= 5) {
decode(filter, bl);
}
if (struct_v >= 6) {
decode(transitions, bl);
decode(noncur_transitions, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void init_simple_days_rule(std::string_view _id, std::string_view _prefix, int num_days);
};
WRITE_CLASS_ENCODER(LCRule)
struct transition_action
{
int days;
boost::optional<ceph::real_time> date;
std::string storage_class;
transition_action() : days(0) {}
void dump(Formatter *f) const {
if (!date) {
f->dump_int("days", days);
} else {
utime_t ut(*date);
f->dump_stream("date") << ut;
}
}
};
/* XXX why not LCRule? */
struct lc_op
{
std::string id;
bool status{false};
bool dm_expiration{false};
int expiration{0};
int noncur_expiration{0};
int mp_expiration{0};
boost::optional<ceph::real_time> expiration_date;
boost::optional<RGWObjTags> obj_tags;
std::map<std::string, transition_action> transitions;
std::map<std::string, transition_action> noncur_transitions;
uint32_t rule_flags;
/* ctors are nice */
lc_op() = delete;
lc_op(const std::string id) : id(id)
{}
void dump(Formatter *f) const;
};
class RGWLifecycleConfiguration
{
protected:
CephContext *cct;
std::multimap<std::string, lc_op> prefix_map;
std::multimap<std::string, LCRule> rule_map;
bool _add_rule(const LCRule& rule);
bool has_same_action(const lc_op& first, const lc_op& second);
public:
explicit RGWLifecycleConfiguration(CephContext *_cct) : cct(_cct) {}
RGWLifecycleConfiguration() : cct(NULL) {}
void set_ctx(CephContext *ctx) {
cct = ctx;
}
virtual ~RGWLifecycleConfiguration() {}
// int get_perm(std::string& id, int perm_mask);
// int get_group_perm(ACLGroupTypeEnum group, int perm_mask);
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(rule_map, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl);
decode(rule_map, bl);
std::multimap<std::string, LCRule>::iterator iter;
for (iter = rule_map.begin(); iter != rule_map.end(); ++iter) {
LCRule& rule = iter->second;
_add_rule(rule);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWLifecycleConfiguration*>& o);
void add_rule(const LCRule& rule);
int check_and_add_rule(const LCRule& rule);
bool valid();
std::multimap<std::string, LCRule>& get_rule_map() { return rule_map; }
std::multimap<std::string, lc_op>& get_prefix_map() { return prefix_map; }
/*
void create_default(std::string id, std::string name) {
ACLGrant grant;
grant.set_canon(id, name, RGW_PERM_FULL_CONTROL);
add_grant(&grant);
}
*/
};
WRITE_CLASS_ENCODER(RGWLifecycleConfiguration)
class RGWLC : public DoutPrefixProvider {
CephContext *cct;
rgw::sal::Driver* driver;
std::unique_ptr<rgw::sal::Lifecycle> sal_lc;
int max_objs{0};
std::string *obj_names{nullptr};
std::atomic<bool> down_flag = { false };
std::string cookie;
public:
class WorkPool;
class LCWorker : public Thread
{
const DoutPrefixProvider *dpp;
CephContext *cct;
RGWLC *lc;
int ix;
std::mutex lock;
std::condition_variable cond;
WorkPool* workpool{nullptr};
/* save the target bucket names created as part of object transition
* to cloud. This list is maintained for the duration of each RGWLC::process()
* post which it is discarded. */
std::set<std::string> cloud_targets;
public:
using lock_guard = std::lock_guard<std::mutex>;
using unique_lock = std::unique_lock<std::mutex>;
LCWorker(const DoutPrefixProvider* dpp, CephContext *_cct, RGWLC *_lc,
int ix);
RGWLC* get_lc() { return lc; }
std::string thr_name() {
return std::string{"lc_thrd: "} + std::to_string(ix);
}
void *entry() override;
void stop();
bool should_work(utime_t& now);
int schedule_next_start_time(utime_t& start, utime_t& now);
std::set<std::string>& get_cloud_targets() { return cloud_targets; }
virtual ~LCWorker() override;
friend class RGWRados;
friend class RGWLC;
friend class WorkQ;
}; /* LCWorker */
friend class RGWRados;
std::vector<std::unique_ptr<RGWLC::LCWorker>> workers;
RGWLC() : cct(nullptr), driver(nullptr) {}
virtual ~RGWLC() override;
void initialize(CephContext *_cct, rgw::sal::Driver* _driver);
void finalize();
int process(LCWorker* worker,
const std::unique_ptr<rgw::sal::Bucket>& optional_bucket,
bool once);
int advance_head(const std::string& lc_shard,
rgw::sal::Lifecycle::LCHead& head,
rgw::sal::Lifecycle::LCEntry& entry,
time_t start_date);
int process(int index, int max_lock_secs, LCWorker* worker, bool once);
int process_bucket(int index, int max_lock_secs, LCWorker* worker,
const std::string& bucket_entry_marker, bool once);
bool expired_session(time_t started);
time_t thread_stop_at();
int list_lc_progress(std::string& marker, uint32_t max_entries,
std::vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>>&,
int& index);
int bucket_lc_process(std::string& shard_id, LCWorker* worker, time_t stop_at,
bool once);
int bucket_lc_post(int index, int max_lock_sec,
rgw::sal::Lifecycle::LCEntry& entry, int& result, LCWorker* worker);
bool going_down();
void start_processor();
void stop_processor();
int set_bucket_config(rgw::sal::Bucket* bucket,
const rgw::sal::Attrs& bucket_attrs,
RGWLifecycleConfiguration *config);
int remove_bucket_config(rgw::sal::Bucket* bucket,
const rgw::sal::Attrs& bucket_attrs,
bool merge_attrs = true);
CephContext *get_cct() const override { return cct; }
rgw::sal::Lifecycle* get_lc() const { return sal_lc.get(); }
unsigned get_subsys() const;
std::ostream& gen_prefix(std::ostream& out) const;
private:
int handle_multipart_expiration(rgw::sal::Bucket* target,
const std::multimap<std::string, lc_op>& prefix_map,
LCWorker* worker, time_t stop_at, bool once);
};
namespace rgw::lc {
int fix_lc_shard_entry(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
rgw::sal::Lifecycle* sal_lc,
rgw::sal::Bucket* bucket);
std::string s3_expiration_header(
DoutPrefixProvider* dpp,
const rgw_obj_key& obj_key,
const RGWObjTags& obj_tagset,
const ceph::real_time& mtime,
const std::map<std::string, buffer::list>& bucket_attrs);
bool s3_multipart_abort_header(
DoutPrefixProvider* dpp,
const rgw_obj_key& obj_key,
const ceph::real_time& mtime,
const std::map<std::string, buffer::list>& bucket_attrs,
ceph::real_time& abort_date,
std::string& rule_id);
} // namespace rgw::lc
| 15,484 | 23.157566 | 102 |
h
|
null |
ceph-main/src/rgw/rgw_lc_s3.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "rgw_user.h"
#include "rgw_lc_s3.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
static bool check_date(const string& _date)
{
boost::optional<ceph::real_time> date = ceph::from_iso_8601(_date);
if (boost::none == date) {
return false;
}
struct timespec time = ceph::real_clock::to_timespec(*date);
if (time.tv_sec % (24*60*60) || time.tv_nsec) {
return false;
}
return true;
}
void LCExpiration_S3::dump_xml(Formatter *f) const {
if (dm_expiration) {
encode_xml("ExpiredObjectDeleteMarker", "true", f);
} else if (!days.empty()) {
encode_xml("Days", days, f);
} else {
encode_xml("Date", date, f);
}
}
void LCExpiration_S3::decode_xml(XMLObj *obj)
{
bool has_days = RGWXMLDecoder::decode_xml("Days", days, obj);
bool has_date = RGWXMLDecoder::decode_xml("Date", date, obj);
string dm;
bool has_dm = RGWXMLDecoder::decode_xml("ExpiredObjectDeleteMarker", dm, obj);
int num = !!has_days + !!has_date + !!has_dm;
if (num != 1) {
throw RGWXMLDecoder::err("bad Expiration section");
}
if (has_date && !check_date(date)) {
//We need return xml error according to S3
throw RGWXMLDecoder::err("bad date in Date section");
}
if (has_dm) {
dm_expiration = (dm == "true");
}
}
void LCNoncurExpiration_S3::decode_xml(XMLObj *obj)
{
RGWXMLDecoder::decode_xml("NoncurrentDays", days, obj, true);
}
void LCNoncurExpiration_S3::dump_xml(Formatter *f) const
{
encode_xml("NoncurrentDays", days, f);
}
void LCMPExpiration_S3::decode_xml(XMLObj *obj)
{
RGWXMLDecoder::decode_xml("DaysAfterInitiation", days, obj, true);
}
void LCMPExpiration_S3::dump_xml(Formatter *f) const
{
encode_xml("DaysAfterInitiation", days, f);
}
void RGWLifecycleConfiguration_S3::decode_xml(XMLObj *obj)
{
if (!cct) {
throw RGWXMLDecoder::err("ERROR: RGWLifecycleConfiguration_S3 can't be decoded without cct initialized");
}
vector<LCRule_S3> rules;
RGWXMLDecoder::decode_xml("Rule", rules, obj, true);
for (auto& rule : rules) {
if (rule.get_id().empty()) {
// S3 generates a 48 bit random ID, maybe we could generate shorter IDs
static constexpr auto LC_ID_LENGTH = 48;
string id = gen_rand_alphanumeric_lower(cct, LC_ID_LENGTH);
rule.set_id(id);
}
add_rule(rule);
}
if (cct->_conf->rgw_lc_max_rules < rule_map.size()) {
stringstream ss;
ss << "Warn: The lifecycle config has too many rules, rule number is:"
<< rule_map.size() << ", max number is:" << cct->_conf->rgw_lc_max_rules;
throw RGWXMLDecoder::err(ss.str());
}
}
void LCFilter_S3::dump_xml(Formatter *f) const
{
bool multi = has_multi_condition();
if (multi) {
f->open_array_section("And");
}
if (has_prefix()) {
encode_xml("Prefix", prefix, f);
}
if (has_tags()) {
const auto& tagset_s3 = static_cast<const RGWObjTagSet_S3 &>(obj_tags);
tagset_s3.dump_xml(f);
}
if (has_flags()) {
if (have_flag(LCFlagType::ArchiveZone)) {
encode_xml("ArchiveZone", "", f);
}
}
if (multi) {
f->close_section(); // And
}
}
void LCFilter_S3::decode_xml(XMLObj *obj)
{
/*
* The prior logic here looked for an And element, but did not
* structurally parse the Filter clause (and incorrectly rejected
* the base case where a Prefix and one Tag were supplied). It
* could not reject generally malformed Filter syntax.
*
* Empty filters are allowed:
* https://docs.aws.amazon.com/AmazonS3/latest/dev/intro-lifecycle-rules.html
*/
XMLObj* o = obj->find_first("And");
if (o == nullptr){
o = obj;
}
RGWXMLDecoder::decode_xml("Prefix", prefix, o);
/* parse optional ArchiveZone flag (extension) */
if (o->find_first("ArchiveZone")) {
flags |= make_flag(LCFlagType::ArchiveZone);
}
obj_tags.clear(); // why is this needed?
auto tags_iter = o->find("Tag");
while (auto tag_xml = tags_iter.get_next()){
std::string _key,_val;
RGWXMLDecoder::decode_xml("Key", _key, tag_xml);
RGWXMLDecoder::decode_xml("Value", _val, tag_xml);
obj_tags.emplace_tag(std::move(_key), std::move(_val));
}
}
void LCTransition_S3::decode_xml(XMLObj *obj)
{
bool has_days = RGWXMLDecoder::decode_xml("Days", days, obj);
bool has_date = RGWXMLDecoder::decode_xml("Date", date, obj);
if ((has_days && has_date) || (!has_days && !has_date)) {
throw RGWXMLDecoder::err("bad Transition section");
}
if (has_date && !check_date(date)) {
//We need return xml error according to S3
throw RGWXMLDecoder::err("bad Date in Transition section");
}
if (!RGWXMLDecoder::decode_xml("StorageClass", storage_class, obj)) {
throw RGWXMLDecoder::err("missing StorageClass in Transition section");
}
}
void LCTransition_S3::dump_xml(Formatter *f) const {
if (!days.empty()) {
encode_xml("Days", days, f);
} else {
encode_xml("Date", date, f);
}
encode_xml("StorageClass", storage_class, f);
}
void LCNoncurTransition_S3::decode_xml(XMLObj *obj)
{
if (!RGWXMLDecoder::decode_xml("NoncurrentDays", days, obj)) {
throw RGWXMLDecoder::err("missing NoncurrentDays in NoncurrentVersionTransition section");
}
if (!RGWXMLDecoder::decode_xml("StorageClass", storage_class, obj)) {
throw RGWXMLDecoder::err("missing StorageClass in NoncurrentVersionTransition section");
}
}
void LCNoncurTransition_S3::dump_xml(Formatter *f) const
{
encode_xml("NoncurrentDays", days, f);
encode_xml("StorageClass", storage_class, f);
}
void LCRule_S3::decode_xml(XMLObj *obj)
{
id.clear();
prefix.clear();
status.clear();
dm_expiration = false;
RGWXMLDecoder::decode_xml("ID", id, obj);
LCFilter_S3 filter_s3;
if (!RGWXMLDecoder::decode_xml("Filter", filter_s3, obj)) {
// Ideally the following code should be deprecated and we should return
// False here, The new S3 LC configuration xml spec. makes Filter mandatory
// and Prefix optional. However older clients including boto2 still generate
// xml according to the older spec, where Prefix existed outside of Filter
// and S3 itself seems to be sloppy on enforcing the mandatory Filter
// argument. A day will come when S3 enforces their own xml-spec, but it is
// not this day
if (!RGWXMLDecoder::decode_xml("Prefix", prefix, obj)) {
throw RGWXMLDecoder::err("missing Prefix in Filter");
}
}
filter = (LCFilter)filter_s3;
if (!RGWXMLDecoder::decode_xml("Status", status, obj)) {
throw RGWXMLDecoder::err("missing Status in Filter");
}
if (status.compare("Enabled") != 0 && status.compare("Disabled") != 0) {
throw RGWXMLDecoder::err("bad Status in Filter");
}
LCExpiration_S3 s3_expiration;
LCNoncurExpiration_S3 s3_noncur_expiration;
LCMPExpiration_S3 s3_mp_expiration;
LCFilter_S3 s3_filter;
bool has_expiration = RGWXMLDecoder::decode_xml("Expiration", s3_expiration, obj);
bool has_noncur_expiration = RGWXMLDecoder::decode_xml("NoncurrentVersionExpiration", s3_noncur_expiration, obj);
bool has_mp_expiration = RGWXMLDecoder::decode_xml("AbortIncompleteMultipartUpload", s3_mp_expiration, obj);
vector<LCTransition_S3> transitions;
vector<LCNoncurTransition_S3> noncur_transitions;
bool has_transition = RGWXMLDecoder::decode_xml("Transition", transitions, obj);
bool has_noncur_transition = RGWXMLDecoder::decode_xml("NoncurrentVersionTransition", noncur_transitions, obj);
if (!has_expiration &&
!has_noncur_expiration &&
!has_mp_expiration &&
!has_transition &&
!has_noncur_transition) {
throw RGWXMLDecoder::err("bad Rule");
}
if (has_expiration) {
if (s3_expiration.has_days() ||
s3_expiration.has_date()) {
expiration = s3_expiration;
} else {
dm_expiration = s3_expiration.get_dm_expiration();
}
}
if (has_noncur_expiration) {
noncur_expiration = s3_noncur_expiration;
}
if (has_mp_expiration) {
mp_expiration = s3_mp_expiration;
}
for (auto& t : transitions) {
if (!add_transition(t)) {
throw RGWXMLDecoder::err("Failed to add transition");
}
}
for (auto& t : noncur_transitions) {
if (!add_noncur_transition(t)) {
throw RGWXMLDecoder::err("Failed to add non-current version transition");
}
}
}
void LCRule_S3::dump_xml(Formatter *f) const {
encode_xml("ID", id, f);
// In case of an empty filter and an empty Prefix, we defer to Prefix.
if (!filter.empty()) {
const LCFilter_S3& lc_filter = static_cast<const LCFilter_S3&>(filter);
encode_xml("Filter", lc_filter, f);
} else {
encode_xml("Prefix", prefix, f);
}
encode_xml("Status", status, f);
if (!expiration.empty() || dm_expiration) {
LCExpiration_S3 expir(expiration.get_days_str(), expiration.get_date(), dm_expiration);
encode_xml("Expiration", expir, f);
}
if (!noncur_expiration.empty()) {
const LCNoncurExpiration_S3& noncur_expir = static_cast<const LCNoncurExpiration_S3&>(noncur_expiration);
encode_xml("NoncurrentVersionExpiration", noncur_expir, f);
}
if (!mp_expiration.empty()) {
const LCMPExpiration_S3& mp_expir = static_cast<const LCMPExpiration_S3&>(mp_expiration);
encode_xml("AbortIncompleteMultipartUpload", mp_expir, f);
}
if (!transitions.empty()) {
for (auto &elem : transitions) {
const LCTransition_S3& tran = static_cast<const LCTransition_S3&>(elem.second);
encode_xml("Transition", tran, f);
}
}
if (!noncur_transitions.empty()) {
for (auto &elem : noncur_transitions) {
const LCNoncurTransition_S3& noncur_tran = static_cast<const LCNoncurTransition_S3&>(elem.second);
encode_xml("NoncurrentVersionTransition", noncur_tran, f);
}
}
}
int RGWLifecycleConfiguration_S3::rebuild(RGWLifecycleConfiguration& dest)
{
int ret = 0;
multimap<string, LCRule>::iterator iter;
for (iter = rule_map.begin(); iter != rule_map.end(); ++iter) {
LCRule& src_rule = iter->second;
ret = dest.check_and_add_rule(src_rule);
if (ret < 0)
return ret;
}
if (!dest.valid()) {
ret = -ERR_INVALID_REQUEST;
}
return ret;
}
void RGWLifecycleConfiguration_S3::dump_xml(Formatter *f) const
{
for (auto iter = rule_map.begin(); iter != rule_map.end(); ++iter) {
const LCRule_S3& rule = static_cast<const LCRule_S3&>(iter->second);
encode_xml("Rule", rule, f);
}
}
| 10,501 | 28.666667 | 115 |
cc
|
null |
ceph-main/src/rgw/rgw_lc_s3.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <string>
#include <iostream>
#include <include/types.h>
#include "include/str_list.h"
#include "rgw_lc.h"
#include "rgw_xml.h"
#include "rgw_tag_s3.h"
class LCFilter_S3 : public LCFilter
{
public:
void dump_xml(Formatter *f) const;
void decode_xml(XMLObj *obj);
};
class LCExpiration_S3 : public LCExpiration
{
private:
bool dm_expiration{false};
public:
LCExpiration_S3() {}
LCExpiration_S3(std::string _days, std::string _date, bool _dm_expiration) : LCExpiration(_days, _date), dm_expiration(_dm_expiration) {}
void dump_xml(Formatter *f) const;
void decode_xml(XMLObj *obj);
void set_dm_expiration(bool _dm_expiration) {
dm_expiration = _dm_expiration;
}
bool get_dm_expiration() {
return dm_expiration;
}
};
class LCNoncurExpiration_S3 : public LCExpiration
{
public:
LCNoncurExpiration_S3() {}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
class LCMPExpiration_S3 : public LCExpiration
{
public:
LCMPExpiration_S3() {}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
class LCTransition_S3 : public LCTransition
{
public:
LCTransition_S3() {}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
class LCNoncurTransition_S3 : public LCTransition
{
public:
LCNoncurTransition_S3() {}
~LCNoncurTransition_S3() {}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
class LCRule_S3 : public LCRule
{
public:
LCRule_S3() {}
void dump_xml(Formatter *f) const;
void decode_xml(XMLObj *obj);
};
class RGWLifecycleConfiguration_S3 : public RGWLifecycleConfiguration
{
public:
explicit RGWLifecycleConfiguration_S3(CephContext *_cct) : RGWLifecycleConfiguration(_cct) {}
RGWLifecycleConfiguration_S3() : RGWLifecycleConfiguration(nullptr) {}
void decode_xml(XMLObj *obj);
int rebuild(RGWLifecycleConfiguration& dest);
void dump_xml(Formatter *f) const;
};
| 2,063 | 19.435644 | 139 |
h
|
null |
ceph-main/src/rgw/rgw_ldap.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_ldap.h"
#include "common/ceph_crypto.h"
#include "common/ceph_context.h"
#include "common/common_init.h"
#include "common/dout.h"
#include "common/safe_io.h"
#include <boost/algorithm/string.hpp>
#include "include/ceph_assert.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
std::string parse_rgw_ldap_bindpw(CephContext* ctx)
{
string ldap_bindpw;
string ldap_secret = ctx->_conf->rgw_ldap_secret;
if (ldap_secret.empty()) {
ldout(ctx, 10)
<< __func__ << " LDAP auth no rgw_ldap_secret file found in conf"
<< dendl;
} else {
// FIPS zeroization audit 20191116: this memset is not intended to
// wipe out a secret after use.
char bindpw[1024];
memset(bindpw, 0, 1024);
int pwlen = safe_read_file("" /* base */, ldap_secret.c_str(),
bindpw, 1023);
if (pwlen > 0) {
ldap_bindpw = bindpw;
boost::algorithm::trim(ldap_bindpw);
if (ldap_bindpw.back() == '\n')
ldap_bindpw.pop_back();
}
::ceph::crypto::zeroize_for_security(bindpw, sizeof(bindpw));
}
return ldap_bindpw;
}
#if defined(HAVE_OPENLDAP)
namespace rgw {
int LDAPHelper::auth(const std::string &uid, const std::string &pwd) {
int ret;
std::string filter;
if (msad) {
filter = "(&(objectClass=user)(sAMAccountName=";
filter += uid;
filter += "))";
} else {
/* openldap */
if (searchfilter.empty()) {
/* no search filter provided in config, we construct our own */
filter = "(";
filter += dnattr;
filter += "=";
filter += uid;
filter += ")";
} else {
if (searchfilter.find("@USERNAME@") != std::string::npos) {
/* we need to substitute the @USERNAME@ placeholder */
filter = searchfilter;
filter.replace(searchfilter.find("@USERNAME@"), std::string("@USERNAME@").length(), uid);
} else {
/* no placeholder for username, so we need to append our own username filter to the custom searchfilter */
filter = "(&(";
filter += searchfilter;
filter += ")(";
filter += dnattr;
filter += "=";
filter += uid;
filter += "))";
}
}
}
ldout(g_ceph_context, 12)
<< __func__ << " search filter: " << filter
<< dendl;
char *attrs[] = { const_cast<char*>(dnattr.c_str()), nullptr };
LDAPMessage *answer = nullptr, *entry = nullptr;
bool once = true;
lock_guard guard(mtx);
retry_bind:
ret = ldap_search_s(ldap, searchdn.c_str(), LDAP_SCOPE_SUBTREE,
filter.c_str(), attrs, 0, &answer);
if (ret == LDAP_SUCCESS) {
entry = ldap_first_entry(ldap, answer);
if (entry) {
char *dn = ldap_get_dn(ldap, entry);
ret = simple_bind(dn, pwd);
if (ret != LDAP_SUCCESS) {
ldout(g_ceph_context, 10)
<< __func__ << " simple_bind failed uid=" << uid
<< "ldap err=" << ret
<< dendl;
}
ldap_memfree(dn);
} else {
ldout(g_ceph_context, 12)
<< __func__ << " ldap_search_s no user matching uid=" << uid
<< dendl;
ret = LDAP_NO_SUCH_ATTRIBUTE; // fixup result
}
ldap_msgfree(answer);
} else {
ldout(g_ceph_context, 5)
<< __func__ << " ldap_search_s error uid=" << uid
<< " ldap err=" << ret
<< dendl;
/* search should never fail--try to rebind */
if (once) {
rebind();
once = false;
goto retry_bind;
}
}
return (ret == LDAP_SUCCESS) ? ret : -EACCES;
} /* LDAPHelper::auth */
}
#endif /* defined(HAVE_OPENLDAP) */
| 3,669 | 27.015267 | 114 |
cc
|
null |
ceph-main/src/rgw/rgw_ldap.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "acconfig.h"
#if defined(HAVE_OPENLDAP)
#define LDAP_DEPRECATED 1
#include "ldap.h"
#endif
#include <stdint.h>
#include <tuple>
#include <vector>
#include <string>
#include <iostream>
#include <mutex>
namespace rgw {
#if defined(HAVE_OPENLDAP)
class LDAPHelper
{
std::string uri;
std::string binddn;
std::string bindpw;
std::string searchdn;
std::string searchfilter;
std::string dnattr;
LDAP *ldap;
bool msad = false; /* TODO: possible future specialization */
std::mutex mtx;
public:
using lock_guard = std::lock_guard<std::mutex>;
LDAPHelper(std::string _uri, std::string _binddn, std::string _bindpw,
const std::string &_searchdn, const std::string &_searchfilter, const std::string &_dnattr)
: uri(std::move(_uri)), binddn(std::move(_binddn)),
bindpw(std::move(_bindpw)), searchdn(_searchdn), searchfilter(_searchfilter), dnattr(_dnattr),
ldap(nullptr) {
// nothing
}
int init() {
int ret;
ret = ldap_initialize(&ldap, uri.c_str());
if (ret == LDAP_SUCCESS) {
unsigned long ldap_ver = LDAP_VERSION3;
ret = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION,
(void*) &ldap_ver);
}
if (ret == LDAP_SUCCESS) {
ret = ldap_set_option(ldap, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
}
return (ret == LDAP_SUCCESS) ? ret : -EINVAL;
}
int bind() {
int ret;
ret = ldap_simple_bind_s(ldap, binddn.c_str(), bindpw.c_str());
return (ret == LDAP_SUCCESS) ? ret : -EINVAL;
}
int rebind() {
if (ldap) {
(void) ldap_unbind(ldap);
(void) init();
return bind();
}
return -EINVAL;
}
int simple_bind(const char *dn, const std::string& pwd) {
LDAP* tldap;
int ret = ldap_initialize(&tldap, uri.c_str());
if (ret == LDAP_SUCCESS) {
unsigned long ldap_ver = LDAP_VERSION3;
ret = ldap_set_option(tldap, LDAP_OPT_PROTOCOL_VERSION,
(void*) &ldap_ver);
if (ret == LDAP_SUCCESS) {
ret = ldap_simple_bind_s(tldap, dn, pwd.c_str());
}
(void) ldap_unbind(tldap);
}
return ret; // OpenLDAP client error space
}
int auth(const std::string &uid, const std::string &pwd);
~LDAPHelper() {
if (ldap)
(void) ldap_unbind(ldap);
}
}; /* LDAPHelper */
#else
class LDAPHelper
{
public:
LDAPHelper(const std::string &_uri, const std::string &_binddn, const std::string &_bindpw,
const std::string &_searchdn, const std::string &_searchfilter, const std::string &_dnattr)
{}
int init() {
return -ENOTSUP;
}
int bind() {
return -ENOTSUP;
}
int auth(const std::string &uid, const std::string &pwd) {
return -EACCES;
}
~LDAPHelper() {}
}; /* LDAPHelper */
#endif /* HAVE_OPENLDAP */
} /* namespace rgw */
#include "common/ceph_context.h"
#include "common/common_init.h"
#include "common/dout.h"
#include "common/safe_io.h"
#include <boost/algorithm/string.hpp>
#include "include/ceph_assert.h"
std::string parse_rgw_ldap_bindpw(CephContext* ctx);
| 3,195 | 21.992806 | 99 |
h
|
null |
ceph-main/src/rgw/rgw_lib.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <sys/types.h>
#include <string.h>
#include <chrono>
#include "include/rados/librgw.h"
#include "rgw_acl.h"
#include "include/str_list.h"
#include "global/signal_handler.h"
#include "common/Timer.h"
#include "common/WorkQueue.h"
#include "common/ceph_argparse.h"
#include "common/ceph_context.h"
#include "common/common_init.h"
#include "common/dout.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_log.h"
#include "rgw_frontend.h"
#include "rgw_request.h"
#include "rgw_process.h"
#include "rgw_auth.h"
#include "rgw_lib.h"
#include "rgw_lib_frontend.h"
#include "rgw_perf_counters.h"
#include "rgw_signal.h"
#include "rgw_main.h"
#include <errno.h>
#include <thread>
#include <string>
#include <mutex>
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw {
RGWLib* g_rgwlib = nullptr;
class C_InitTimeout : public Context {
public:
C_InitTimeout() {}
void finish(int r) override {
derr << "Initialization timeout, failed to initialize" << dendl;
exit(1);
}
};
void RGWLibProcess::checkpoint()
{
m_tp.drain(&req_wq);
}
#define MIN_EXPIRE_S 120
void RGWLibProcess::run()
{
/* write completion interval */
RGWLibFS::write_completion_interval_s =
cct->_conf->rgw_nfs_write_completion_interval_s;
/* start write timer */
RGWLibFS::write_timer.resume();
/* gc loop */
while (! shutdown) {
lsubdout(cct, rgw, 5) << "RGWLibProcess GC" << dendl;
/* dirent invalidate timeout--basically, the upper-bound on
* inconsistency with the S3 namespace */
auto expire_s = cct->_conf->rgw_nfs_namespace_expire_secs;
/* delay between gc cycles */
auto delay_s = std::max(int64_t(1), std::min(int64_t(MIN_EXPIRE_S), expire_s/2));
unique_lock uniq(mtx);
restart:
int cur_gen = gen;
for (auto iter = mounted_fs.begin(); iter != mounted_fs.end();
++iter) {
RGWLibFS* fs = iter->first->ref();
uniq.unlock();
fs->gc();
const DoutPrefix dp(cct, dout_subsys, "librgw: ");
fs->update_user(&dp);
fs->rele();
uniq.lock();
if (cur_gen != gen)
goto restart; /* invalidated */
}
cv.wait_for(uniq, std::chrono::seconds(delay_s));
uniq.unlock();
}
}
void RGWLibProcess::handle_request(const DoutPrefixProvider *dpp, RGWRequest* r)
{
/*
* invariant: valid requests are derived from RGWLibRequst
*/
RGWLibRequest* req = static_cast<RGWLibRequest*>(r);
// XXX move RGWLibIO and timing setup into process_request
#if 0 /* XXX */
utime_t tm = ceph_clock_now();
#endif
RGWLibIO io_ctx;
int ret = process_request(req, &io_ctx);
if (ret < 0) {
/* we don't really care about return code */
dout(20) << "process_request() returned " << ret << dendl;
}
delete req;
} /* handle_request */
int RGWLibProcess::process_request(RGWLibRequest* req)
{
// XXX move RGWLibIO and timing setup into process_request
#if 0 /* XXX */
utime_t tm = ceph_clock_now();
#endif
RGWLibIO io_ctx;
int ret = process_request(req, &io_ctx);
if (ret < 0) {
/* we don't really care about return code */
dout(20) << "process_request() returned " << ret << dendl;
}
return ret;
} /* process_request */
static inline void abort_req(req_state *s, RGWOp *op, int err_no)
{
if (!s)
return;
/* XXX the dump_errno and dump_bucket_from_state behaviors in
* the abort_early (rgw_rest.cc) might be valuable, but aren't
* safe to call presently as they return HTTP data */
perfcounter->inc(l_rgw_failed_req);
} /* abort_req */
int RGWLibProcess::process_request(RGWLibRequest* req, RGWLibIO* io)
{
int ret = 0;
bool should_log = true; // XXX
dout(1) << "====== " << __func__
<< " starting new request req=" << hex << req << dec
<< " ======" << dendl;
/*
* invariant: valid requests are derived from RGWOp--well-formed
* requests should have assigned RGWRequest::op in their descendant
* constructor--if not, the compiler can find it, at the cost of
* a runtime check
*/
RGWOp *op = (req->op) ? req->op : dynamic_cast<RGWOp*>(req);
if (! op) {
ldpp_dout(op, 1) << "failed to derive cognate RGWOp (invalid op?)" << dendl;
return -EINVAL;
}
io->init(req->cct);
perfcounter->inc(l_rgw_req);
RGWEnv& rgw_env = io->get_env();
/* XXX
* until major refactoring of req_state and req_info, we need
* to build their RGWEnv boilerplate from the RGWLibRequest,
* pre-staging any strings (HTTP_HOST) that provoke a crash when
* not found
*/
/* XXX for now, use ""; could be a legit hostname, or, in future,
* perhaps a tenant (Yehuda) */
rgw_env.set("HTTP_HOST", "");
/* XXX and -then- bloat up req_state with string copies from it */
req_state rstate(req->cct, env, &rgw_env, req->id);
req_state *s = &rstate;
// XXX fix this
s->cio = io;
/* XXX and -then- stash req_state pointers everywhere they are needed */
ret = req->init(rgw_env, env.driver, io, s);
if (ret < 0) {
ldpp_dout(op, 10) << "failed to initialize request" << dendl;
abort_req(s, op, ret);
goto done;
}
/* req is-a RGWOp, currently initialized separately */
ret = req->op_init();
if (ret < 0) {
dout(10) << "failed to initialize RGWOp" << dendl;
abort_req(s, op, ret);
goto done;
}
/* now expected by rgw_log_op() */
rgw_env.set("REQUEST_METHOD", s->info.method);
rgw_env.set("REQUEST_URI", s->info.request_uri);
rgw_env.set("QUERY_STRING", "");
try {
/* XXX authorize does less here then in the REST path, e.g.,
* the user's info is cached, but still incomplete */
ldpp_dout(s, 2) << "authorizing" << dendl;
ret = req->authorize(op, null_yield);
if (ret < 0) {
dout(10) << "failed to authorize request" << dendl;
abort_req(s, op, ret);
goto done;
}
/* FIXME: remove this after switching all handlers to the new
* authentication infrastructure. */
if (! s->auth.identity) {
s->auth.identity = rgw::auth::transform_old_authinfo(s);
}
ldpp_dout(s, 2) << "reading op permissions" << dendl;
ret = req->read_permissions(op, null_yield);
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "init op" << dendl;
ret = op->init_processing(null_yield);
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "verifying op mask" << dendl;
ret = op->verify_op_mask();
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "verifying op permissions" << dendl;
ret = op->verify_permission(null_yield);
if (ret < 0) {
if (s->system_request) {
ldpp_dout(op, 2) << "overriding permissions due to system operation" << dendl;
} else if (s->auth.identity->is_admin_of(s->user->get_id())) {
ldpp_dout(op, 2) << "overriding permissions due to admin operation" << dendl;
} else {
abort_req(s, op, ret);
goto done;
}
}
ldpp_dout(s, 2) << "verifying op params" << dendl;
ret = op->verify_params();
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "executing" << dendl;
op->pre_exec();
op->execute(null_yield);
op->complete();
} catch (const ceph::crypto::DigestException& e) {
dout(0) << "authentication failed" << e.what() << dendl;
abort_req(s, op, -ERR_INVALID_SECRET_KEY);
}
done:
try {
io->complete_request();
} catch (rgw::io::Exception& e) {
dout(0) << "ERROR: io->complete_request() returned "
<< e.what() << dendl;
}
if (should_log) {
rgw_log_op(nullptr /* !rest */, s, op, env.olog);
}
int http_ret = s->err.http_ret;
ldpp_dout(s, 2) << "http status=" << http_ret << dendl;
ldpp_dout(op, 1) << "====== " << __func__
<< " req done req=" << hex << req << dec << " http_status="
<< http_ret
<< " ======" << dendl;
return (ret < 0 ? ret : s->err.ret);
} /* process_request */
int RGWLibProcess::start_request(RGWLibContinuedReq* req)
{
dout(1) << "====== " << __func__
<< " starting new continued request req=" << hex << req << dec
<< " ======" << dendl;
/*
* invariant: valid requests are derived from RGWOp--well-formed
* requests should have assigned RGWRequest::op in their descendant
* constructor--if not, the compiler can find it, at the cost of
* a runtime check
*/
RGWOp *op = (req->op) ? req->op : dynamic_cast<RGWOp*>(req);
if (! op) {
ldpp_dout(op, 1) << "failed to derive cognate RGWOp (invalid op?)" << dendl;
return -EINVAL;
}
req_state* s = req->get_state();
RGWLibIO& io_ctx = req->get_io();
RGWEnv& rgw_env = io_ctx.get_env();
rgw_env.set("HTTP_HOST", "");
int ret = req->init(rgw_env, env.driver, &io_ctx, s);
if (ret < 0) {
ldpp_dout(op, 10) << "failed to initialize request" << dendl;
abort_req(s, op, ret);
goto done;
}
/* req is-a RGWOp, currently initialized separately */
ret = req->op_init();
if (ret < 0) {
dout(10) << "failed to initialize RGWOp" << dendl;
abort_req(s, op, ret);
goto done;
}
/* XXX authorize does less here then in the REST path, e.g.,
* the user's info is cached, but still incomplete */
ldpp_dout(s, 2) << "authorizing" << dendl;
ret = req->authorize(op, null_yield);
if (ret < 0) {
dout(10) << "failed to authorize request" << dendl;
abort_req(s, op, ret);
goto done;
}
/* FIXME: remove this after switching all handlers to the new authentication
* infrastructure. */
if (! s->auth.identity) {
s->auth.identity = rgw::auth::transform_old_authinfo(s);
}
ldpp_dout(s, 2) << "reading op permissions" << dendl;
ret = req->read_permissions(op, null_yield);
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "init op" << dendl;
ret = op->init_processing(null_yield);
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "verifying op mask" << dendl;
ret = op->verify_op_mask();
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
ldpp_dout(s, 2) << "verifying op permissions" << dendl;
ret = op->verify_permission(null_yield);
if (ret < 0) {
if (s->system_request) {
ldpp_dout(op, 2) << "overriding permissions due to system operation" << dendl;
} else if (s->auth.identity->is_admin_of(s->user->get_id())) {
ldpp_dout(op, 2) << "overriding permissions due to admin operation" << dendl;
} else {
abort_req(s, op, ret);
goto done;
}
}
ldpp_dout(s, 2) << "verifying op params" << dendl;
ret = op->verify_params();
if (ret < 0) {
abort_req(s, op, ret);
goto done;
}
op->pre_exec();
req->exec_start();
done:
return (ret < 0 ? ret : s->err.ret);
}
int RGWLibProcess::finish_request(RGWLibContinuedReq* req)
{
RGWOp *op = (req->op) ? req->op : dynamic_cast<RGWOp*>(req);
if (! op) {
ldpp_dout(op, 1) << "failed to derive cognate RGWOp (invalid op?)" << dendl;
return -EINVAL;
}
int ret = req->exec_finish();
int op_ret = op->get_ret();
ldpp_dout(op, 1) << "====== " << __func__
<< " finishing continued request req=" << hex << req << dec
<< " op status=" << op_ret
<< " ======" << dendl;
perfcounter->inc(l_rgw_req);
return ret;
}
int RGWLibFrontend::init()
{
std::string uri_prefix; // empty
pprocess = new RGWLibProcess(g_ceph_context, env,
g_conf()->rgw_thread_pool_size, uri_prefix, conf);
return 0;
}
void RGWLib::set_fe(rgw::RGWLibFrontend* fe)
{
this->fe = fe;
}
int RGWLib::init()
{
vector<const char*> args;
return init(args);
}
int RGWLib::init(vector<const char*>& args)
{
/* alternative default for module */
map<std::string,std::string> defaults = {
{ "debug_rgw", "1/5" },
{ "keyring", "$rgw_data/keyring" },
{ "log_file", "/var/log/radosgw/$cluster-$name.log" },
{ "objecter_inflight_ops", "24576" },
// require a secure mon connection by default
{ "ms_mon_client_mode", "secure" },
{ "auth_client_required", "cephx" },
};
cct = rgw_global_init(&defaults, args,
CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_DAEMON,
CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS);
ceph::mutex mutex = ceph::make_mutex("main");
SafeTimer init_timer(g_ceph_context, mutex);
init_timer.init();
mutex.lock();
init_timer.add_event_after(g_conf()->rgw_init_timeout, new C_InitTimeout);
mutex.unlock();
/* stage all front-ends (before common-init-finish) */
main.init_frontends1(true /* nfs */);
common_init_finish(g_ceph_context);
main.init_perfcounters();
main.init_http_clients();
main.init_storage();
if (! main.get_driver()) {
mutex.lock();
init_timer.cancel_all_events();
init_timer.shutdown();
mutex.unlock();
derr << "Couldn't init storage provider (RADOS)" << dendl;
return -EIO;
}
main.cond_init_apis();
mutex.lock();
init_timer.cancel_all_events();
init_timer.shutdown();
mutex.unlock();
main.init_ldap();
main.init_opslog();
init_async_signal_handler();
register_async_signal_handler(SIGUSR1, rgw::signal::handle_sigterm);
main.init_tracepoints();
main.init_frontends2(this /* rgwlib */);
main.init_notification_endpoints();
main.init_lua();
return 0;
} /* RGWLib::init() */
int RGWLib::stop()
{
derr << "shutting down" << dendl;
const auto finalize_async_signals = []() {
unregister_async_signal_handler(SIGUSR1, rgw::signal::handle_sigterm);
shutdown_async_signal_handler();
};
main.shutdown(finalize_async_signals);
return 0;
} /* RGWLib::stop() */
int RGWLibIO::set_uid(rgw::sal::Driver* driver, const rgw_user& uid)
{
const DoutPrefix dp(driver->ctx(), dout_subsys, "librgw: ");
std::unique_ptr<rgw::sal::User> user = driver->get_user(uid);
/* object exists, but policy is broken */
int ret = user->load_user(&dp, null_yield);
if (ret < 0) {
derr << "ERROR: failed reading user info: uid=" << uid << " ret="
<< ret << dendl;
}
user_info = user->get_info();
return ret;
}
int RGWLibRequest::read_permissions(RGWOp* op, optional_yield y) {
/* bucket and object ops */
int ret =
rgw_build_bucket_policies(op, g_rgwlib->get_driver(), get_state(), y);
if (ret < 0) {
ldpp_dout(op, 10) << "read_permissions (bucket policy) on "
<< get_state()->bucket << ":"
<< get_state()->object
<< " only_bucket=" << only_bucket()
<< " ret=" << ret << dendl;
if (ret == -ENODATA)
ret = -EACCES;
} else if (! only_bucket()) {
/* object ops */
ret = rgw_build_object_policies(op, g_rgwlib->get_driver(), get_state(),
op->prefetch_data(), y);
if (ret < 0) {
ldpp_dout(op, 10) << "read_permissions (object policy) on"
<< get_state()->bucket << ":"
<< get_state()->object
<< " ret=" << ret << dendl;
if (ret == -ENODATA)
ret = -EACCES;
}
}
return ret;
} /* RGWLibRequest::read_permissions */
int RGWHandler_Lib::authorize(const DoutPrefixProvider *dpp, optional_yield y)
{
/* TODO: handle
* 1. subusers
* 2. anonymous access
* 3. system access
* 4. ?
*
* Much or all of this depends on handling the cached authorization
* correctly (e.g., dealing with keystone) at mount time.
*/
s->perm_mask = RGW_PERM_FULL_CONTROL;
// populate the owner info
s->owner.set_id(s->user->get_id());
s->owner.set_name(s->user->get_display_name());
return 0;
} /* RGWHandler_Lib::authorize */
} /* namespace rgw */
| 16,552 | 26.091653 | 87 |
cc
|
null |
ceph-main/src/rgw/rgw_lib.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <mutex>
#include "rgw_common.h"
#include "rgw_client_io.h"
#include "rgw_rest.h"
#include "rgw_request.h"
#include "rgw_ldap.h"
#include "include/ceph_assert.h"
#include "rgw_main.h"
class OpsLogSink;
namespace rgw {
class RGWLibFrontend;
class RGWLib : public DoutPrefixProvider {
boost::intrusive_ptr<CephContext> cct;
AppMain main;
RGWLibFrontend* fe;
public:
RGWLib() : main(this), fe(nullptr)
{}
~RGWLib() {}
rgw::sal::Driver* get_driver() { return main.get_driver(); }
RGWLibFrontend* get_fe() { return fe; }
rgw::LDAPHelper* get_ldh() { return main.get_ldh(); }
CephContext *get_cct() const override { return cct.get(); }
unsigned get_subsys() const { return ceph_subsys_rgw; }
std::ostream& gen_prefix(std::ostream& out) const { return out << "lib rgw: "; }
void set_fe(RGWLibFrontend* fe);
int init();
int init(std::vector<const char *>& args);
int stop();
};
extern RGWLib* g_rgwlib;
/* request interface */
class RGWLibIO : public rgw::io::BasicClient,
public rgw::io::Accounter
{
RGWUserInfo user_info;
RGWEnv env;
public:
RGWLibIO() {
get_env().set("HTTP_HOST", "");
}
explicit RGWLibIO(const RGWUserInfo &_user_info)
: user_info(_user_info) {}
int init_env(CephContext *cct) override {
env.init(cct);
return 0;
}
const RGWUserInfo& get_user() {
return user_info;
}
int set_uid(rgw::sal::Driver* driver, const rgw_user& uid);
int write_data(const char *buf, int len);
int read_data(char *buf, int len);
int send_status(int status, const char *status_name);
int send_100_continue();
int complete_header();
int send_content_length(uint64_t len);
RGWEnv& get_env() noexcept override {
return env;
}
size_t complete_request() override { /* XXX */
return 0;
};
void set_account(bool) override {
return;
}
uint64_t get_bytes_sent() const override {
return 0;
}
uint64_t get_bytes_received() const override {
return 0;
}
}; /* RGWLibIO */
class RGWRESTMgr_Lib : public RGWRESTMgr {
public:
RGWRESTMgr_Lib() {}
~RGWRESTMgr_Lib() override {}
}; /* RGWRESTMgr_Lib */
class RGWHandler_Lib : public RGWHandler {
friend class RGWRESTMgr_Lib;
public:
int authorize(const DoutPrefixProvider *dpp, optional_yield y) override;
RGWHandler_Lib() {}
~RGWHandler_Lib() override {}
static int init_from_header(rgw::sal::Driver* driver,
req_state *s);
}; /* RGWHandler_Lib */
class RGWLibRequest : public RGWRequest,
public RGWHandler_Lib {
private:
std::unique_ptr<rgw::sal::User> tuser; // Don't use this. It's empty except during init.
public:
CephContext* cct;
/* unambiguiously return req_state */
inline req_state* get_state() { return this->RGWRequest::s; }
RGWLibRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user)
: RGWRequest(g_rgwlib->get_driver()->get_new_req_id()),
tuser(std::move(_user)), cct(_cct)
{}
int postauth_init(optional_yield) override { return 0; }
/* descendant equivalent of *REST*::init_from_header(...):
* prepare request for execute()--should mean, fixup URI-alikes
* and any other expected stat vars in local req_state, for
* now */
virtual int header_init() = 0;
/* descendant initializer responsible to call RGWOp::init()--which
* descendants are required to inherit */
virtual int op_init() = 0;
using RGWHandler::init;
int init(const RGWEnv& rgw_env, rgw::sal::Driver* _driver,
RGWLibIO* io, req_state* _s) {
RGWRequest::init_state(_s);
RGWHandler::init(_driver, _s, io);
get_state()->req_id = driver->zone_unique_id(id);
get_state()->trans_id = driver->zone_unique_trans_id(id);
get_state()->bucket_tenant = tuser->get_tenant();
get_state()->set_user(tuser);
ldpp_dout(_s, 2) << "initializing for trans_id = "
<< get_state()->trans_id.c_str() << dendl;
int ret = header_init();
if (ret == 0) {
ret = init_from_header(driver, _s);
}
return ret;
}
virtual bool only_bucket() = 0;
int read_permissions(RGWOp *op, optional_yield y) override;
}; /* RGWLibRequest */
class RGWLibContinuedReq : public RGWLibRequest {
RGWLibIO io_ctx;
req_state rstate;
public:
RGWLibContinuedReq(CephContext* _cct, const RGWProcessEnv& penv,
std::unique_ptr<rgw::sal::User> _user)
: RGWLibRequest(_cct, std::move(_user)), io_ctx(),
rstate(_cct, penv, &io_ctx.get_env(), id)
{
io_ctx.init(_cct);
RGWRequest::init_state(&rstate);
RGWHandler::init(g_rgwlib->get_driver(), &rstate, &io_ctx);
get_state()->req_id = driver->zone_unique_id(id);
get_state()->trans_id = driver->zone_unique_trans_id(id);
ldpp_dout(get_state(), 2) << "initializing for trans_id = "
<< get_state()->trans_id.c_str() << dendl;
}
inline rgw::sal::Driver* get_driver() { return driver; }
inline RGWLibIO& get_io() { return io_ctx; }
virtual int execute() final { ceph_abort(); }
virtual int exec_start() = 0;
virtual int exec_continue() = 0;
virtual int exec_finish() = 0;
}; /* RGWLibContinuedReq */
} /* namespace rgw */
| 5,465 | 25.028571 | 93 |
h
|
null |
ceph-main/src/rgw/rgw_lib_frontend.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <boost/container/flat_map.hpp>
#include "rgw_lib.h"
#include "rgw_file.h"
namespace rgw {
class RGWLibProcess : public RGWProcess {
RGWAccessKey access_key;
std::mutex mtx;
std::condition_variable cv;
int gen;
bool shutdown;
typedef flat_map<RGWLibFS*, RGWLibFS*> FSMAP;
FSMAP mounted_fs;
using lock_guard = std::lock_guard<std::mutex>;
using unique_lock = std::unique_lock<std::mutex>;
public:
RGWLibProcess(CephContext* cct, RGWProcessEnv& pe, int num_threads,
std::string uri_prefix, RGWFrontendConfig* _conf) :
RGWProcess(cct, pe, num_threads, std::move(uri_prefix), _conf),
gen(0), shutdown(false) {}
void run() override;
void checkpoint();
void stop() {
shutdown = true;
for (const auto& fs: mounted_fs) {
fs.second->stop();
}
cv.notify_all();
}
void register_fs(RGWLibFS* fs) {
lock_guard guard(mtx);
mounted_fs.insert(FSMAP::value_type(fs, fs));
++gen;
}
void unregister_fs(RGWLibFS* fs) {
lock_guard guard(mtx);
FSMAP::iterator it = mounted_fs.find(fs);
if (it != mounted_fs.end()) {
mounted_fs.erase(it);
++gen;
}
}
void enqueue_req(RGWLibRequest* req) {
lsubdout(g_ceph_context, rgw, 10)
<< __func__ << " enqueue request req="
<< std::hex << req << std::dec << dendl;
req_throttle.get(1);
req_wq.queue(req);
} /* enqueue_req */
/* "regular" requests */
void handle_request(const DoutPrefixProvider *dpp, RGWRequest* req) override; // async handler, deletes req
int process_request(RGWLibRequest* req);
int process_request(RGWLibRequest* req, RGWLibIO* io);
void set_access_key(RGWAccessKey& key) { access_key = key; }
/* requests w/continue semantics */
int start_request(RGWLibContinuedReq* req);
int finish_request(RGWLibContinuedReq* req);
}; /* RGWLibProcess */
class RGWLibFrontend : public RGWProcessFrontend {
public:
RGWLibFrontend(RGWProcessEnv& pe, RGWFrontendConfig *_conf)
: RGWProcessFrontend(pe, _conf) {}
int init() override;
void stop() override {
RGWProcessFrontend::stop();
get_process()->stop();
}
RGWLibProcess* get_process() {
return static_cast<RGWLibProcess*>(pprocess);
}
inline void enqueue_req(RGWLibRequest* req) {
static_cast<RGWLibProcess*>(pprocess)->enqueue_req(req); // async
}
inline int execute_req(RGWLibRequest* req) {
return static_cast<RGWLibProcess*>(pprocess)->process_request(req); // !async
}
inline int start_req(RGWLibContinuedReq* req) {
return static_cast<RGWLibProcess*>(pprocess)->start_request(req);
}
inline int finish_req(RGWLibContinuedReq* req) {
return static_cast<RGWLibProcess*>(pprocess)->finish_request(req);
}
}; /* RGWLibFrontend */
} /* namespace rgw */
| 3,015 | 25.45614 | 111 |
h
|
null |
ceph-main/src/rgw/rgw_loadgen.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <algorithm>
#include <sstream>
#include <string.h>
#include "rgw_loadgen.h"
#include "rgw_auth_s3.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
void RGWLoadGenRequestEnv::set_date(utime_t& tm)
{
date_str = rgw_to_asctime(tm);
}
int RGWLoadGenRequestEnv::sign(const DoutPrefixProvider *dpp, RGWAccessKey& access_key)
{
meta_map_t meta_map;
map<string, string> sub_resources;
string canonical_header;
string digest;
rgw_create_s3_canonical_header(dpp,
request_method.c_str(),
nullptr, /* const char *content_md5 */
content_type.c_str(),
date_str.c_str(),
meta_map,
meta_map_t{},
uri.c_str(),
sub_resources,
canonical_header);
headers["HTTP_DATE"] = date_str;
try {
/* FIXME(rzarzynski): kill the dependency on g_ceph_context. */
const auto signature = static_cast<std::string>(
rgw::auth::s3::get_v2_signature(g_ceph_context, canonical_header,
access_key.key));
headers["HTTP_AUTHORIZATION"] = \
std::string("AWS ") + access_key.id + ":" + signature;
} catch (int ret) {
return ret;
}
return 0;
}
size_t RGWLoadGenIO::write_data(const char* const buf,
const size_t len)
{
return len;
}
size_t RGWLoadGenIO::read_data(char* const buf, const size_t len)
{
const size_t read_len = std::min(left_to_read,
static_cast<uint64_t>(len));
left_to_read -= read_len;
return read_len;
}
void RGWLoadGenIO::flush()
{
}
size_t RGWLoadGenIO::complete_request()
{
return 0;
}
int RGWLoadGenIO::init_env(CephContext *cct)
{
env.init(cct);
left_to_read = req->content_length;
char buf[32];
snprintf(buf, sizeof(buf), "%lld", (long long)req->content_length);
env.set("CONTENT_LENGTH", buf);
env.set("CONTENT_TYPE", req->content_type.c_str());
env.set("HTTP_DATE", req->date_str.c_str());
for (map<string, string>::iterator iter = req->headers.begin(); iter != req->headers.end(); ++iter) {
env.set(iter->first.c_str(), iter->second.c_str());
}
env.set("REQUEST_METHOD", req->request_method.c_str());
env.set("REQUEST_URI", req->uri.c_str());
env.set("QUERY_STRING", req->query_string.c_str());
env.set("SCRIPT_URI", req->uri.c_str());
char port_buf[16];
snprintf(port_buf, sizeof(port_buf), "%d", req->port);
env.set("SERVER_PORT", port_buf);
return 0;
}
size_t RGWLoadGenIO::send_status(const int status,
const char* const status_name)
{
return 0;
}
size_t RGWLoadGenIO::send_100_continue()
{
return 0;
}
size_t RGWLoadGenIO::send_header(const std::string_view& name,
const std::string_view& value)
{
return 0;
}
size_t RGWLoadGenIO::complete_header()
{
return 0;
}
size_t RGWLoadGenIO::send_content_length(const uint64_t len)
{
return 0;
}
| 3,240 | 23.55303 | 103 |
cc
|
null |
ceph-main/src/rgw/rgw_loadgen.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <string>
#include "rgw_client_io.h"
struct RGWLoadGenRequestEnv {
int port;
uint64_t content_length;
std::string content_type;
std::string request_method;
std::string uri;
std::string query_string;
std::string date_str;
std::map<std::string, std::string> headers;
RGWLoadGenRequestEnv()
: port(0),
content_length(0) {
}
void set_date(utime_t& tm);
int sign(const DoutPrefixProvider *dpp, RGWAccessKey& access_key);
};
/* XXX does RGWLoadGenIO actually want to perform stream/HTTP I/O,
* or (e.g) are these NOOPs? */
class RGWLoadGenIO : public rgw::io::RestfulClient
{
uint64_t left_to_read;
RGWLoadGenRequestEnv* req;
RGWEnv env;
int init_env(CephContext *cct) override;
size_t read_data(char *buf, size_t len);
size_t write_data(const char *buf, size_t len);
public:
explicit RGWLoadGenIO(RGWLoadGenRequestEnv* const req)
: left_to_read(0),
req(req) {
}
size_t send_status(int status, const char *status_name) override;
size_t send_100_continue() override;
size_t send_header(const std::string_view& name,
const std::string_view& value) override;
size_t complete_header() override;
size_t send_content_length(uint64_t len) override;
size_t recv_body(char* buf, size_t max) override {
return read_data(buf, max);
}
size_t send_body(const char* buf, size_t len) override {
return write_data(buf, len);
}
void flush() override;
RGWEnv& get_env() noexcept override {
return env;
}
size_t complete_request() override;
};
| 1,697 | 22.260274 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_loadgen_process.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "common/errno.h"
#include "common/Throttle.h"
#include "common/WorkQueue.h"
#include "rgw_rest.h"
#include "rgw_frontend.h"
#include "rgw_request.h"
#include "rgw_process.h"
#include "rgw_loadgen.h"
#include "rgw_client_io.h"
#include "rgw_signal.h"
#include <atomic>
#define dout_subsys ceph_subsys_rgw
using namespace std;
void RGWLoadGenProcess::checkpoint()
{
m_tp.drain(&req_wq);
}
void RGWLoadGenProcess::run()
{
m_tp.start(); /* start thread pool */
int i;
int num_objs;
conf->get_val("num_objs", 1000, &num_objs);
int num_buckets;
conf->get_val("num_buckets", 1, &num_buckets);
vector<string> buckets(num_buckets);
std::atomic<bool> failed = { false };
for (i = 0; i < num_buckets; i++) {
buckets[i] = "/loadgen";
string& bucket = buckets[i];
append_rand_alpha(cct, bucket, bucket, 16);
/* first create a bucket */
gen_request("PUT", bucket, 0, &failed);
checkpoint();
}
string *objs = new string[num_objs];
if (failed) {
derr << "ERROR: bucket creation failed" << dendl;
goto done;
}
for (i = 0; i < num_objs; i++) {
char buf[16 + 1];
gen_rand_alphanumeric(cct, buf, sizeof(buf));
buf[16] = '\0';
objs[i] = buckets[i % num_buckets] + "/" + buf;
}
for (i = 0; i < num_objs; i++) {
gen_request("PUT", objs[i], 4096, &failed);
}
checkpoint();
if (failed) {
derr << "ERROR: bucket creation failed" << dendl;
goto done;
}
for (i = 0; i < num_objs; i++) {
gen_request("GET", objs[i], 4096, NULL);
}
checkpoint();
for (i = 0; i < num_objs; i++) {
gen_request("DELETE", objs[i], 0, NULL);
}
checkpoint();
for (i = 0; i < num_buckets; i++) {
gen_request("DELETE", buckets[i], 0, NULL);
}
done:
checkpoint();
m_tp.stop();
delete[] objs;
rgw::signal::signal_shutdown();
} /* RGWLoadGenProcess::run() */
void RGWLoadGenProcess::gen_request(const string& method,
const string& resource,
int content_length, std::atomic<bool>* fail_flag)
{
RGWLoadGenRequest* req =
new RGWLoadGenRequest(env.driver->get_new_req_id(), method, resource,
content_length, fail_flag);
dout(10) << "allocated request req=" << hex << req << dec << dendl;
req_throttle.get(1);
req_wq.queue(req);
} /* RGWLoadGenProcess::gen_request */
void RGWLoadGenProcess::handle_request(const DoutPrefixProvider *dpp, RGWRequest* r)
{
RGWLoadGenRequest* req = static_cast<RGWLoadGenRequest*>(r);
RGWLoadGenRequestEnv renv;
utime_t tm = ceph_clock_now();
renv.port = 80;
renv.content_length = req->content_length;
renv.content_type = "binary/octet-stream";
renv.request_method = req->method;
renv.uri = req->resource;
renv.set_date(tm);
renv.sign(dpp, access_key);
RGWLoadGenIO real_client_io(&renv);
RGWRestfulIO client_io(cct, &real_client_io);
int ret = process_request(env, req, uri_prefix, &client_io,
null_yield, nullptr, nullptr, nullptr);
if (ret < 0) {
/* we don't really care about return code */
dout(20) << "process_request() returned " << ret << dendl;
if (req->fail_flag) {
req->fail_flag++;
}
}
delete req;
} /* RGWLoadGenProcess::handle_request */
| 3,325 | 21.472973 | 84 |
cc
|
null |
ceph-main/src/rgw/rgw_log.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "common/Clock.h"
#include "common/Timer.h"
#include "common/utf8.h"
#include "common/OutputDataSocket.h"
#include "common/Formatter.h"
#include "rgw_bucket.h"
#include "rgw_log.h"
#include "rgw_acl.h"
#include "rgw_client_io.h"
#include "rgw_rest.h"
#include "rgw_zone.h"
#include "rgw_rados.h"
#include "services/svc_zone.h"
#include <chrono>
#include <math.h>
#define dout_subsys ceph_subsys_rgw
using namespace std;
static void set_param_str(req_state *s, const char *name, string& str)
{
const char *p = s->info.env->get(name);
if (p)
str = p;
}
string render_log_object_name(const string& format,
struct tm *dt, const string& bucket_id,
const string& bucket_name)
{
string o;
for (unsigned i=0; i<format.size(); i++) {
if (format[i] == '%' && i+1 < format.size()) {
i++;
char buf[32];
switch (format[i]) {
case '%':
strcpy(buf, "%");
break;
case 'Y':
sprintf(buf, "%.4d", dt->tm_year + 1900);
break;
case 'y':
sprintf(buf, "%.2d", dt->tm_year % 100);
break;
case 'm':
sprintf(buf, "%.2d", dt->tm_mon + 1);
break;
case 'd':
sprintf(buf, "%.2d", dt->tm_mday);
break;
case 'H':
sprintf(buf, "%.2d", dt->tm_hour);
break;
case 'I':
sprintf(buf, "%.2d", (dt->tm_hour % 12) + 1);
break;
case 'k':
sprintf(buf, "%d", dt->tm_hour);
break;
case 'l':
sprintf(buf, "%d", (dt->tm_hour % 12) + 1);
break;
case 'M':
sprintf(buf, "%.2d", dt->tm_min);
break;
case 'i':
o += bucket_id;
continue;
case 'n':
o += bucket_name;
continue;
default:
// unknown code
sprintf(buf, "%%%c", format[i]);
break;
}
o += buf;
continue;
}
o += format[i];
}
return o;
}
/* usage logger */
class UsageLogger : public DoutPrefixProvider {
CephContext *cct;
rgw::sal::Driver* driver;
map<rgw_user_bucket, RGWUsageBatch> usage_map;
ceph::mutex lock = ceph::make_mutex("UsageLogger");
int32_t num_entries;
ceph::mutex timer_lock = ceph::make_mutex("UsageLogger::timer_lock");
SafeTimer timer;
utime_t round_timestamp;
class C_UsageLogTimeout : public Context {
UsageLogger *logger;
public:
explicit C_UsageLogTimeout(UsageLogger *_l) : logger(_l) {}
void finish(int r) override {
logger->flush();
logger->set_timer();
}
};
void set_timer() {
timer.add_event_after(cct->_conf->rgw_usage_log_tick_interval, new C_UsageLogTimeout(this));
}
public:
UsageLogger(CephContext *_cct, rgw::sal::Driver* _driver) : cct(_cct), driver(_driver), num_entries(0), timer(cct, timer_lock) {
timer.init();
std::lock_guard l{timer_lock};
set_timer();
utime_t ts = ceph_clock_now();
recalc_round_timestamp(ts);
}
~UsageLogger() {
std::lock_guard l{timer_lock};
flush();
timer.cancel_all_events();
timer.shutdown();
}
void recalc_round_timestamp(utime_t& ts) {
round_timestamp = ts.round_to_hour();
}
void insert_user(utime_t& timestamp, const rgw_user& user, rgw_usage_log_entry& entry) {
lock.lock();
if (timestamp.sec() > round_timestamp + 3600)
recalc_round_timestamp(timestamp);
entry.epoch = round_timestamp.sec();
bool account;
string u = user.to_str();
rgw_user_bucket ub(u, entry.bucket);
real_time rt = round_timestamp.to_real_time();
usage_map[ub].insert(rt, entry, &account);
if (account)
num_entries++;
bool need_flush = (num_entries > cct->_conf->rgw_usage_log_flush_threshold);
lock.unlock();
if (need_flush) {
std::lock_guard l{timer_lock};
flush();
}
}
void insert(utime_t& timestamp, rgw_usage_log_entry& entry) {
if (entry.payer.empty()) {
insert_user(timestamp, entry.owner, entry);
} else {
insert_user(timestamp, entry.payer, entry);
}
}
void flush() {
map<rgw_user_bucket, RGWUsageBatch> old_map;
lock.lock();
old_map.swap(usage_map);
num_entries = 0;
lock.unlock();
driver->log_usage(this, old_map, null_yield);
}
CephContext *get_cct() const override { return cct; }
unsigned get_subsys() const override { return dout_subsys; }
std::ostream& gen_prefix(std::ostream& out) const override { return out << "rgw UsageLogger: "; }
};
static UsageLogger *usage_logger = NULL;
void rgw_log_usage_init(CephContext *cct, rgw::sal::Driver* driver)
{
usage_logger = new UsageLogger(cct, driver);
}
void rgw_log_usage_finalize()
{
delete usage_logger;
usage_logger = NULL;
}
static void log_usage(req_state *s, const string& op_name)
{
if (s->system_request) /* don't log system user operations */
return;
if (!usage_logger)
return;
rgw_user user;
rgw_user payer;
string bucket_name;
bucket_name = s->bucket_name;
if (!bucket_name.empty()) {
bucket_name = s->bucket_name;
user = s->bucket_owner.get_id();
if (!rgw::sal::Bucket::empty(s->bucket.get()) &&
s->bucket->get_info().requester_pays) {
payer = s->user->get_id();
}
} else {
user = s->user->get_id();
}
bool error = s->err.is_err();
if (error && s->err.http_ret == 404) {
bucket_name = "-"; /* bucket not found, use the invalid '-' as bucket name */
}
string u = user.to_str();
string p = payer.to_str();
rgw_usage_log_entry entry(u, p, bucket_name);
uint64_t bytes_sent = ACCOUNTING_IO(s)->get_bytes_sent();
uint64_t bytes_received = ACCOUNTING_IO(s)->get_bytes_received();
rgw_usage_data data(bytes_sent, bytes_received);
data.ops = 1;
if (!s->is_err())
data.successful_ops = 1;
ldpp_dout(s, 30) << "log_usage: bucket_name=" << bucket_name
<< " tenant=" << s->bucket_tenant
<< ", bytes_sent=" << bytes_sent << ", bytes_received="
<< bytes_received << ", success=" << data.successful_ops << dendl;
entry.add(op_name, data);
utime_t ts = ceph_clock_now();
usage_logger->insert(ts, entry);
}
void rgw_format_ops_log_entry(struct rgw_log_entry& entry, Formatter *formatter)
{
formatter->open_object_section("log_entry");
formatter->dump_string("bucket", entry.bucket);
{
auto t = utime_t{entry.time};
t.gmtime(formatter->dump_stream("time")); // UTC
t.localtime(formatter->dump_stream("time_local"));
}
formatter->dump_string("remote_addr", entry.remote_addr);
string obj_owner = entry.object_owner.to_str();
if (obj_owner.length())
formatter->dump_string("object_owner", obj_owner);
formatter->dump_string("user", entry.user);
formatter->dump_string("operation", entry.op);
formatter->dump_string("uri", entry.uri);
formatter->dump_string("http_status", entry.http_status);
formatter->dump_string("error_code", entry.error_code);
formatter->dump_int("bytes_sent", entry.bytes_sent);
formatter->dump_int("bytes_received", entry.bytes_received);
formatter->dump_int("object_size", entry.obj_size);
{
using namespace std::chrono;
uint64_t total_time = duration_cast<milliseconds>(entry.total_time).count();
formatter->dump_int("total_time", total_time);
}
formatter->dump_string("user_agent", entry.user_agent);
formatter->dump_string("referrer", entry.referrer);
if (entry.x_headers.size() > 0) {
formatter->open_array_section("http_x_headers");
for (const auto& iter: entry.x_headers) {
formatter->open_object_section(iter.first.c_str());
formatter->dump_string(iter.first.c_str(), iter.second);
formatter->close_section();
}
formatter->close_section();
}
formatter->dump_string("trans_id", entry.trans_id);
switch(entry.identity_type) {
case TYPE_RGW:
formatter->dump_string("authentication_type","Local");
break;
case TYPE_LDAP:
formatter->dump_string("authentication_type","LDAP");
break;
case TYPE_KEYSTONE:
formatter->dump_string("authentication_type","Keystone");
break;
case TYPE_WEB:
formatter->dump_string("authentication_type","OIDC Provider");
break;
case TYPE_ROLE:
formatter->dump_string("authentication_type","STS");
break;
default:
break;
}
if (entry.token_claims.size() > 0) {
if (entry.token_claims[0] == "sts") {
formatter->open_object_section("sts_info");
for (const auto& iter: entry.token_claims) {
auto pos = iter.find(":");
if (pos != string::npos) {
formatter->dump_string(iter.substr(0, pos), iter.substr(pos + 1));
}
}
formatter->close_section();
}
}
if (!entry.access_key_id.empty()) {
formatter->dump_string("access_key_id", entry.access_key_id);
}
if (!entry.subuser.empty()) {
formatter->dump_string("subuser", entry.subuser);
}
formatter->dump_bool("temp_url", entry.temp_url);
if (entry.op == "multi_object_delete") {
formatter->open_object_section("op_data");
formatter->dump_int("num_ok", entry.delete_multi_obj_meta.num_ok);
formatter->dump_int("num_err", entry.delete_multi_obj_meta.num_err);
formatter->open_array_section("objects");
for (const auto& iter: entry.delete_multi_obj_meta.objects) {
formatter->open_object_section("");
formatter->dump_string("key", iter.key);
formatter->dump_string("version_id", iter.version_id);
formatter->dump_int("http_status", iter.http_status);
formatter->dump_bool("error", iter.error);
if (iter.error) {
formatter->dump_string("error_message", iter.error_message);
} else {
formatter->dump_bool("delete_marker", iter.delete_marker);
formatter->dump_string("marker_version_id", iter.marker_version_id);
}
formatter->close_section();
}
formatter->close_section();
formatter->close_section();
}
formatter->close_section();
}
OpsLogManifold::~OpsLogManifold()
{
for (const auto &sink : sinks) {
delete sink;
}
}
void OpsLogManifold::add_sink(OpsLogSink* sink)
{
sinks.push_back(sink);
}
int OpsLogManifold::log(req_state* s, struct rgw_log_entry& entry)
{
int ret = 0;
for (const auto &sink : sinks) {
if (sink->log(s, entry) < 0) {
ret = -1;
}
}
return ret;
}
OpsLogFile::OpsLogFile(CephContext* cct, std::string& path, uint64_t max_data_size) :
cct(cct), data_size(0), max_data_size(max_data_size), path(path), need_reopen(false)
{
}
void OpsLogFile::reopen() {
need_reopen = true;
}
void OpsLogFile::flush()
{
{
std::scoped_lock log_lock(mutex);
assert(flush_buffer.empty());
flush_buffer.swap(log_buffer);
data_size = 0;
}
for (auto bl : flush_buffer) {
int try_num = 0;
while (true) {
if (!file.is_open() || need_reopen) {
need_reopen = false;
file.close();
file.open(path, std::ofstream::app);
}
bl.write_stream(file);
if (!file) {
ldpp_dout(this, 0) << "ERROR: failed to log RGW ops log file entry" << dendl;
file.clear();
if (stopped) {
break;
}
int sleep_time_secs = std::min((int) pow(2, try_num), 60);
std::this_thread::sleep_for(std::chrono::seconds(sleep_time_secs));
try_num++;
} else {
break;
}
}
}
flush_buffer.clear();
file << std::endl;
}
void* OpsLogFile::entry() {
std::unique_lock lock(mutex);
while (!stopped) {
if (!log_buffer.empty()) {
lock.unlock();
flush();
lock.lock();
continue;
}
cond.wait(lock);
}
lock.unlock();
flush();
return NULL;
}
void OpsLogFile::start() {
stopped = false;
create("ops_log_file");
}
void OpsLogFile::stop() {
{
std::unique_lock lock(mutex);
cond.notify_one();
stopped = true;
}
join();
}
OpsLogFile::~OpsLogFile()
{
if (!stopped) {
stop();
}
file.close();
}
int OpsLogFile::log_json(req_state* s, bufferlist& bl)
{
std::unique_lock lock(mutex);
if (data_size + bl.length() >= max_data_size) {
ldout(s->cct, 0) << "ERROR: RGW ops log file buffer too full, dropping log for txn: " << s->trans_id << dendl;
return -1;
}
log_buffer.push_back(bl);
data_size += bl.length();
cond.notify_all();
return 0;
}
unsigned OpsLogFile::get_subsys() const {
return dout_subsys;
}
JsonOpsLogSink::JsonOpsLogSink() {
formatter = new JSONFormatter;
}
JsonOpsLogSink::~JsonOpsLogSink() {
delete formatter;
}
void JsonOpsLogSink::formatter_to_bl(bufferlist& bl)
{
stringstream ss;
formatter->flush(ss);
const string& s = ss.str();
bl.append(s);
}
int JsonOpsLogSink::log(req_state* s, struct rgw_log_entry& entry)
{
bufferlist bl;
lock.lock();
rgw_format_ops_log_entry(entry, formatter);
formatter_to_bl(bl);
lock.unlock();
return log_json(s, bl);
}
void OpsLogSocket::init_connection(bufferlist& bl)
{
bl.append("[");
}
OpsLogSocket::OpsLogSocket(CephContext *cct, uint64_t _backlog) : OutputDataSocket(cct, _backlog)
{
delim.append(",\n");
}
int OpsLogSocket::log_json(req_state* s, bufferlist& bl)
{
append_output(bl);
return 0;
}
OpsLogRados::OpsLogRados(rgw::sal::Driver* const& driver): driver(driver)
{
}
int OpsLogRados::log(req_state* s, struct rgw_log_entry& entry)
{
if (!s->cct->_conf->rgw_ops_log_rados) {
return 0;
}
bufferlist bl;
encode(entry, bl);
struct tm bdt;
time_t t = req_state::Clock::to_time_t(entry.time);
if (s->cct->_conf->rgw_log_object_name_utc)
gmtime_r(&t, &bdt);
else
localtime_r(&t, &bdt);
string oid = render_log_object_name(s->cct->_conf->rgw_log_object_name, &bdt,
entry.bucket_id, entry.bucket);
if (driver->log_op(s, oid, bl) < 0) {
ldpp_dout(s, 0) << "ERROR: failed to log RADOS RGW ops log entry for txn: " << s->trans_id << dendl;
return -1;
}
return 0;
}
int rgw_log_op(RGWREST* const rest, req_state *s, const RGWOp* op, OpsLogSink *olog)
{
struct rgw_log_entry entry;
string bucket_id;
string op_name = (op ? op->name() : "unknown");
if (s->enable_usage_log)
log_usage(s, op_name);
if (!s->enable_ops_log)
return 0;
if (s->bucket_name.empty()) {
/* this case is needed for, e.g., list_buckets */
} else {
if (s->err.ret == -ERR_NO_SUCH_BUCKET ||
rgw::sal::Bucket::empty(s->bucket.get())) {
if (!s->cct->_conf->rgw_log_nonexistent_bucket) {
ldout(s->cct, 5) << "bucket " << s->bucket_name << " doesn't exist, not logging" << dendl;
return 0;
}
bucket_id = "";
} else {
bucket_id = s->bucket->get_bucket_id();
}
entry.bucket = rgw_make_bucket_entry_name(s->bucket_tenant, s->bucket_name);
if (check_utf8(entry.bucket.c_str(), entry.bucket.size()) != 0) {
ldpp_dout(s, 5) << "not logging op on bucket with non-utf8 name" << dendl;
return 0;
}
if (!rgw::sal::Object::empty(s->object.get())) {
entry.obj = s->object->get_key();
} else {
entry.obj = rgw_obj_key("-");
}
entry.obj_size = s->obj_size;
} /* !bucket empty */
if (s->cct->_conf->rgw_remote_addr_param.length())
set_param_str(s, s->cct->_conf->rgw_remote_addr_param.c_str(),
entry.remote_addr);
else
set_param_str(s, "REMOTE_ADDR", entry.remote_addr);
set_param_str(s, "HTTP_USER_AGENT", entry.user_agent);
// legacy apps are still using misspelling referer, such as curl -e option
if (s->info.env->exists("HTTP_REFERRER"))
set_param_str(s, "HTTP_REFERRER", entry.referrer);
else
set_param_str(s, "HTTP_REFERER", entry.referrer);
std::string uri;
if (s->info.env->exists("REQUEST_METHOD")) {
uri.append(s->info.env->get("REQUEST_METHOD"));
uri.append(" ");
}
if (s->info.env->exists("REQUEST_URI")) {
uri.append(s->info.env->get("REQUEST_URI"));
}
/* Formerly, we appended QUERY_STRING to uri, but in RGW, QUERY_STRING is a
* substring of REQUEST_URI--appending qs to uri here duplicates qs to the
* ops log */
if (s->info.env->exists("HTTP_VERSION")) {
uri.append(" ");
uri.append("HTTP/");
uri.append(s->info.env->get("HTTP_VERSION"));
}
entry.uri = std::move(uri);
entry.op = op_name;
if (op) {
op->write_ops_log_entry(entry);
}
if (s->auth.identity) {
entry.identity_type = s->auth.identity->get_identity_type();
s->auth.identity->write_ops_log_entry(entry);
} else {
entry.identity_type = TYPE_NONE;
}
if (! s->token_claims.empty()) {
entry.token_claims = std::move(s->token_claims);
}
/* custom header logging */
if (rest) {
if (rest->log_x_headers()) {
for (const auto& iter : s->info.env->get_map()) {
if (rest->log_x_header(iter.first)) {
entry.x_headers.insert(
rgw_log_entry::headers_map::value_type(iter.first, iter.second));
}
}
}
}
entry.user = s->user->get_id().to_str();
if (s->object_acl)
entry.object_owner = s->object_acl->get_owner().get_id();
entry.bucket_owner = s->bucket_owner.get_id();
uint64_t bytes_sent = ACCOUNTING_IO(s)->get_bytes_sent();
uint64_t bytes_received = ACCOUNTING_IO(s)->get_bytes_received();
entry.time = s->time;
entry.total_time = s->time_elapsed();
entry.bytes_sent = bytes_sent;
entry.bytes_received = bytes_received;
if (s->err.http_ret) {
char buf[16];
snprintf(buf, sizeof(buf), "%d", s->err.http_ret);
entry.http_status = buf;
} else {
entry.http_status = "200"; // default
}
entry.error_code = s->err.err_code;
entry.bucket_id = bucket_id;
entry.trans_id = s->trans_id;
if (olog) {
return olog->log(s, entry);
}
return 0;
}
void rgw_log_entry::generate_test_instances(list<rgw_log_entry*>& o)
{
rgw_log_entry *e = new rgw_log_entry;
e->object_owner = "object_owner";
e->bucket_owner = "bucket_owner";
e->bucket = "bucket";
e->remote_addr = "1.2.3.4";
e->user = "user";
e->obj = rgw_obj_key("obj");
e->uri = "http://uri/bucket/obj";
e->http_status = "200";
e->error_code = "error_code";
e->bytes_sent = 1024;
e->bytes_received = 512;
e->obj_size = 2048;
e->user_agent = "user_agent";
e->referrer = "referrer";
e->bucket_id = "10";
e->trans_id = "trans_id";
e->identity_type = TYPE_RGW;
o.push_back(e);
o.push_back(new rgw_log_entry);
}
void rgw_log_entry::dump(Formatter *f) const
{
f->dump_string("object_owner", object_owner.to_str());
f->dump_string("bucket_owner", bucket_owner.to_str());
f->dump_string("bucket", bucket);
f->dump_stream("time") << time;
f->dump_string("remote_addr", remote_addr);
f->dump_string("user", user);
f->dump_stream("obj") << obj;
f->dump_string("op", op);
f->dump_string("uri", uri);
f->dump_string("http_status", http_status);
f->dump_string("error_code", error_code);
f->dump_unsigned("bytes_sent", bytes_sent);
f->dump_unsigned("bytes_received", bytes_received);
f->dump_unsigned("obj_size", obj_size);
f->dump_stream("total_time") << total_time;
f->dump_string("user_agent", user_agent);
f->dump_string("referrer", referrer);
f->dump_string("bucket_id", bucket_id);
f->dump_string("trans_id", trans_id);
f->dump_unsigned("identity_type", identity_type);
}
| 19,060 | 25.363762 | 130 |
cc
|
null |
ceph-main/src/rgw/rgw_log.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <boost/container/flat_map.hpp>
#include "rgw_common.h"
#include "common/OutputDataSocket.h"
#include <vector>
#include <fstream>
#include "rgw_sal_fwd.h"
class RGWOp;
struct delete_multi_obj_entry {
std::string key;
std::string version_id;
std::string error_message;
std::string marker_version_id;
uint32_t http_status = 0;
bool error = false;
bool delete_marker = false;
void encode(bufferlist &bl) const {
ENCODE_START(1, 1, bl);
encode(key, bl);
encode(version_id, bl);
encode(error_message, bl);
encode(marker_version_id, bl);
encode(http_status, bl);
encode(error, bl);
encode(delete_marker, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &p) {
DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, p);
decode(key, p);
decode(version_id, p);
decode(error_message, p);
decode(marker_version_id, p);
decode(http_status, p);
decode(error, p);
decode(delete_marker, p);
DECODE_FINISH(p);
}
};
WRITE_CLASS_ENCODER(delete_multi_obj_entry)
struct delete_multi_obj_op_meta {
uint32_t num_ok = 0;
uint32_t num_err = 0;
std::vector<delete_multi_obj_entry> objects;
void encode(bufferlist &bl) const {
ENCODE_START(1, 1, bl);
encode(num_ok, bl);
encode(num_err, bl);
encode(objects, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &p) {
DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, p);
decode(num_ok, p);
decode(num_err, p);
decode(objects, p);
DECODE_FINISH(p);
}
};
WRITE_CLASS_ENCODER(delete_multi_obj_op_meta)
struct rgw_log_entry {
using headers_map = boost::container::flat_map<std::string, std::string>;
using Clock = req_state::Clock;
rgw_user object_owner;
rgw_user bucket_owner;
std::string bucket;
Clock::time_point time;
std::string remote_addr;
std::string user;
rgw_obj_key obj;
std::string op;
std::string uri;
std::string http_status;
std::string error_code;
uint64_t bytes_sent = 0;
uint64_t bytes_received = 0;
uint64_t obj_size = 0;
Clock::duration total_time{};
std::string user_agent;
std::string referrer;
std::string bucket_id;
headers_map x_headers;
std::string trans_id;
std::vector<std::string> token_claims;
uint32_t identity_type = TYPE_NONE;
std::string access_key_id;
std::string subuser;
bool temp_url {false};
delete_multi_obj_op_meta delete_multi_obj_meta;
void encode(bufferlist &bl) const {
ENCODE_START(14, 5, bl);
encode(object_owner.id, bl);
encode(bucket_owner.id, bl);
encode(bucket, bl);
encode(time, bl);
encode(remote_addr, bl);
encode(user, bl);
encode(obj.name, bl);
encode(op, bl);
encode(uri, bl);
encode(http_status, bl);
encode(error_code, bl);
encode(bytes_sent, bl);
encode(obj_size, bl);
encode(total_time, bl);
encode(user_agent, bl);
encode(referrer, bl);
encode(bytes_received, bl);
encode(bucket_id, bl);
encode(obj, bl);
encode(object_owner, bl);
encode(bucket_owner, bl);
encode(x_headers, bl);
encode(trans_id, bl);
encode(token_claims, bl);
encode(identity_type,bl);
encode(access_key_id, bl);
encode(subuser, bl);
encode(temp_url, bl);
encode(delete_multi_obj_meta, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator &p) {
DECODE_START_LEGACY_COMPAT_LEN(14, 5, 5, p);
decode(object_owner.id, p);
if (struct_v > 3)
decode(bucket_owner.id, p);
decode(bucket, p);
decode(time, p);
decode(remote_addr, p);
decode(user, p);
decode(obj.name, p);
decode(op, p);
decode(uri, p);
decode(http_status, p);
decode(error_code, p);
decode(bytes_sent, p);
decode(obj_size, p);
decode(total_time, p);
decode(user_agent, p);
decode(referrer, p);
if (struct_v >= 2)
decode(bytes_received, p);
else
bytes_received = 0;
if (struct_v >= 3) {
if (struct_v <= 5) {
uint64_t id;
decode(id, p);
char buf[32];
snprintf(buf, sizeof(buf), "%" PRIu64, id);
bucket_id = buf;
} else {
decode(bucket_id, p);
}
} else {
bucket_id = "";
}
if (struct_v >= 7) {
decode(obj, p);
}
if (struct_v >= 8) {
decode(object_owner, p);
decode(bucket_owner, p);
}
if (struct_v >= 9) {
decode(x_headers, p);
}
if (struct_v >= 10) {
decode(trans_id, p);
}
if (struct_v >= 11) {
decode(token_claims, p);
}
if (struct_v >= 12) {
decode(identity_type, p);
}
if (struct_v >= 13) {
decode(access_key_id, p);
decode(subuser, p);
decode(temp_url, p);
}
if (struct_v >= 14) {
decode(delete_multi_obj_meta, p);
}
DECODE_FINISH(p);
}
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<rgw_log_entry*>& o);
};
WRITE_CLASS_ENCODER(rgw_log_entry)
class OpsLogSink {
public:
virtual int log(req_state* s, struct rgw_log_entry& entry) = 0;
virtual ~OpsLogSink() = default;
};
class OpsLogManifold: public OpsLogSink {
std::vector<OpsLogSink*> sinks;
public:
~OpsLogManifold() override;
void add_sink(OpsLogSink* sink);
int log(req_state* s, struct rgw_log_entry& entry) override;
};
class JsonOpsLogSink : public OpsLogSink {
ceph::Formatter *formatter;
ceph::mutex lock = ceph::make_mutex("JsonOpsLogSink");
void formatter_to_bl(bufferlist& bl);
protected:
virtual int log_json(req_state* s, bufferlist& bl) = 0;
public:
JsonOpsLogSink();
~JsonOpsLogSink() override;
int log(req_state* s, struct rgw_log_entry& entry) override;
};
class OpsLogFile : public JsonOpsLogSink, public Thread, public DoutPrefixProvider {
CephContext* cct;
ceph::mutex mutex = ceph::make_mutex("OpsLogFile");
std::vector<bufferlist> log_buffer;
std::vector<bufferlist> flush_buffer;
ceph::condition_variable cond;
std::ofstream file;
bool stopped;
uint64_t data_size;
uint64_t max_data_size;
std::string path;
std::atomic_bool need_reopen;
void flush();
protected:
int log_json(req_state* s, bufferlist& bl) override;
void *entry() override;
public:
OpsLogFile(CephContext* cct, std::string& path, uint64_t max_data_size);
~OpsLogFile() override;
CephContext *get_cct() const override { return cct; }
unsigned get_subsys() const override;
std::ostream& gen_prefix(std::ostream& out) const override { return out << "rgw OpsLogFile: "; }
void reopen();
void start();
void stop();
};
class OpsLogSocket : public OutputDataSocket, public JsonOpsLogSink {
protected:
int log_json(req_state* s, bufferlist& bl) override;
void init_connection(bufferlist& bl) override;
public:
OpsLogSocket(CephContext *cct, uint64_t _backlog);
};
class OpsLogRados : public OpsLogSink {
// main()'s driver pointer as a reference, possibly modified by RGWRealmReloader
rgw::sal::Driver* const& driver;
public:
OpsLogRados(rgw::sal::Driver* const& driver);
int log(req_state* s, struct rgw_log_entry& entry) override;
};
class RGWREST;
int rgw_log_op(RGWREST* const rest, struct req_state* s,
const RGWOp* op, OpsLogSink* olog);
void rgw_log_usage_init(CephContext* cct, rgw::sal::Driver* driver);
void rgw_log_usage_finalize();
void rgw_format_ops_log_entry(struct rgw_log_entry& entry,
ceph::Formatter *formatter);
| 7,535 | 24.986207 | 98 |
h
|
null |
ceph-main/src/rgw/rgw_lua.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <lua.hpp>
#include "services/svc_zone.h"
#include "rgw_lua_utils.h"
#include "rgw_sal_rados.h"
#include "rgw_lua.h"
#ifdef WITH_RADOSGW_LUA_PACKAGES
#include <filesystem>
#include <boost/process.hpp>
#endif
#define dout_subsys ceph_subsys_rgw
namespace rgw::lua {
context to_context(const std::string& s)
{
if (strcasecmp(s.c_str(), "prerequest") == 0) {
return context::preRequest;
}
if (strcasecmp(s.c_str(), "postrequest") == 0) {
return context::postRequest;
}
if (strcasecmp(s.c_str(), "background") == 0) {
return context::background;
}
if (strcasecmp(s.c_str(), "getdata") == 0) {
return context::getData;
}
if (strcasecmp(s.c_str(), "putdata") == 0) {
return context::putData;
}
return context::none;
}
std::string to_string(context ctx)
{
switch (ctx) {
case context::preRequest:
return "prerequest";
case context::postRequest:
return "postrequest";
case context::background:
return "background";
case context::getData:
return "getdata";
case context::putData:
return "putdata";
case context::none:
break;
}
return "none";
}
bool verify(const std::string& script, std::string& err_msg)
{
lua_State *L = luaL_newstate();
lua_state_guard guard(L);
open_standard_libs(L);
try {
if (luaL_loadstring(L, script.c_str()) != LUA_OK) {
err_msg.assign(lua_tostring(L, -1));
return false;
}
} catch (const std::runtime_error& e) {
err_msg = e.what();
return false;
}
err_msg = "";
return true;
}
std::string script_oid(context ctx, const std::string& tenant) {
static const std::string SCRIPT_OID_PREFIX("script.");
return SCRIPT_OID_PREFIX + to_string(ctx) + "." + tenant;
}
int read_script(const DoutPrefixProvider *dpp, sal::LuaManager* manager, const std::string& tenant, optional_yield y, context ctx, std::string& script)
{
return manager ? manager->get_script(dpp, y, script_oid(ctx, tenant), script) : -ENOENT;
}
int write_script(const DoutPrefixProvider *dpp, sal::LuaManager* manager, const std::string& tenant, optional_yield y, context ctx, const std::string& script)
{
return manager ? manager->put_script(dpp, y, script_oid(ctx, tenant), script) : -ENOENT;
}
int delete_script(const DoutPrefixProvider *dpp, sal::LuaManager* manager, const std::string& tenant, optional_yield y, context ctx)
{
return manager ? manager->del_script(dpp, y, script_oid(ctx, tenant)) : -ENOENT;
}
#ifdef WITH_RADOSGW_LUA_PACKAGES
namespace bp = boost::process;
int add_package(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y, const std::string& package_name, bool allow_compilation)
{
// verify that luarocks can load this package
const auto p = bp::search_path("luarocks");
if (p.empty()) {
return -ECHILD;
}
bp::ipstream is;
const auto cmd = p.string() + " search --porcelain" + (allow_compilation ? " " : " --binary ") + package_name;
bp::child c(cmd,
bp::std_in.close(),
bp::std_err > bp::null,
bp::std_out > is);
std::string line;
bool package_found = false;
while (c.running() && std::getline(is, line) && !line.empty()) {
package_found = true;
}
c.wait();
auto ret = c.exit_code();
if (ret) {
return -ret;
}
if (!package_found) {
return -EINVAL;
}
//replace previous versions of the package
const std::string package_name_no_version = package_name.substr(0, package_name.find(" "));
ret = remove_package(dpp, driver, y, package_name_no_version);
if (ret < 0) {
return ret;
}
auto lua_mgr = driver->get_lua_manager();
return lua_mgr->add_package(dpp, y, package_name);
}
int remove_package(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y, const std::string& package_name)
{
auto lua_mgr = driver->get_lua_manager();
return lua_mgr->remove_package(dpp, y, package_name);
}
namespace bp = boost::process;
int list_packages(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y, packages_t& packages)
{
auto lua_mgr = driver->get_lua_manager();
return lua_mgr->list_packages(dpp, y, packages);
}
int install_packages(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
optional_yield y, const std::string& luarocks_path,
packages_t& failed_packages, std::string& output) {
// luarocks directory cleanup
std::error_code ec;
if (std::filesystem::remove_all(luarocks_path, ec)
== static_cast<std::uintmax_t>(-1) &&
ec != std::errc::no_such_file_or_directory) {
output.append("failed to clear luarocks directory: ");
output.append(ec.message());
output.append("\n");
return ec.value();
}
packages_t packages;
auto ret = list_packages(dpp, driver, y, packages);
if (ret == -ENOENT) {
// allowlist is empty
return 0;
}
if (ret < 0) {
output.append("failed to get lua package list");
return ret;
}
// verify that luarocks exists
const auto p = bp::search_path("luarocks");
if (p.empty()) {
output.append("failed to find luarocks");
return -ECHILD;
}
// the lua rocks install dir will be created by luarocks the first time it is called
for (const auto& package : packages) {
bp::ipstream is;
const auto cmd = p.string() + " install --lua-version " + CEPH_LUA_VERSION + " --tree " + luarocks_path + " --deps-mode one " + package;
bp::child c(cmd, bp::std_in.close(), (bp::std_err & bp::std_out) > is);
// once package reload is supported, code should yield when reading output
std::string line = std::string("CMD: ") + cmd;
do {
if (!line.empty()) {
output.append(line);
output.append("\n");
}
} while (c.running() && std::getline(is, line));
c.wait();
if (c.exit_code()) {
failed_packages.insert(package);
}
}
return 0;
}
#endif
}
| 6,007 | 26.686636 | 158 |
cc
|
null |
ceph-main/src/rgw/rgw_lua.h
|
#pragma once
#include <string>
#include <set>
#include "rgw_lua_version.h"
#include "common/async/yield_context.h"
#include "common/dout.h"
#include "rgw_sal_fwd.h"
class DoutPrefixProvider;
class lua_State;
class rgw_user;
class DoutPrefixProvider;
namespace rgw::sal {
class RadosStore;
class LuaManager;
}
namespace rgw::lua {
enum class context {
preRequest,
postRequest,
background,
getData,
putData,
none
};
// get context enum from string
// the expected string the same as the enum (case insensitive)
// return "none" if not matched
context to_context(const std::string& s);
// verify a lua script
bool verify(const std::string& script, std::string& err_msg);
// driver a lua script in a context
int write_script(const DoutPrefixProvider *dpp, rgw::sal::LuaManager* manager, const std::string& tenant, optional_yield y, context ctx, const std::string& script);
// read the stored lua script from a context
int read_script(const DoutPrefixProvider *dpp, rgw::sal::LuaManager* manager, const std::string& tenant, optional_yield y, context ctx, std::string& script);
// delete the stored lua script from a context
int delete_script(const DoutPrefixProvider *dpp, rgw::sal::LuaManager* manager, const std::string& tenant, optional_yield y, context ctx);
using packages_t = std::set<std::string>;
#ifdef WITH_RADOSGW_LUA_PACKAGES
// add a lua package to the allowlist
int add_package(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y, const std::string& package_name, bool allow_compilation);
// remove a lua package from the allowlist
int remove_package(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y, const std::string& package_name);
// list lua packages in the allowlist
int list_packages(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y, packages_t& packages);
// install all packages from the allowlist
// return the list of packages that failed to install and the output of the install command
int install_packages(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
optional_yield y, const std::string& luarocks_path,
packages_t& failed_packages, std::string& output);
#endif
}
| 2,245 | 32.029412 | 164 |
h
|
null |
ceph-main/src/rgw/rgw_lua_background.cc
|
#include "rgw_sal_rados.h"
#include "rgw_lua_background.h"
#include "rgw_lua.h"
#include "rgw_lua_utils.h"
#include "rgw_perf_counters.h"
#include "include/ceph_assert.h"
#include <lua.hpp>
#define dout_subsys ceph_subsys_rgw
namespace rgw::lua {
const char* RGWTable::INCREMENT = "increment";
const char* RGWTable::DECREMENT = "decrement";
int RGWTable::increment_by(lua_State* L) {
const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL)));
auto decrement = lua_toboolean(L, lua_upvalueindex(THIRD_UPVAL));
const auto args = lua_gettop(L);
const auto index = luaL_checkstring(L, 1);
// by default we increment by 1/-1
const long long int default_inc = (decrement ? -1 : 1);
BackgroundMapValue inc_by = default_inc;
if (args == 2) {
if (lua_isinteger(L, 2)) {
inc_by = lua_tointeger(L, 2)*default_inc;
} else if (lua_isnumber(L, 2)){
inc_by = lua_tonumber(L, 2)*static_cast<double>(default_inc);
} else {
return luaL_error(L, "can increment only by numeric values");
}
}
std::unique_lock l(mtx);
const auto it = map->find(std::string(index));
if (it != map->end()) {
auto& value = it->second;
if (std::holds_alternative<double>(value) && std::holds_alternative<double>(inc_by)) {
value = std::get<double>(value) + std::get<double>(inc_by);
} else if (std::holds_alternative<long long int>(value) && std::holds_alternative<long long int>(inc_by)) {
value = std::get<long long int>(value) + std::get<long long int>(inc_by);
} else if (std::holds_alternative<double>(value) && std::holds_alternative<long long int>(inc_by)) {
value = std::get<double>(value) + static_cast<double>(std::get<long long int>(inc_by));
} else if (std::holds_alternative<long long int>(value) && std::holds_alternative<double>(inc_by)) {
value = static_cast<double>(std::get<long long int>(value)) + std::get<double>(inc_by);
} else {
mtx.unlock();
return luaL_error(L, "can increment only numeric values");
}
}
return 0;
}
Background::Background(rgw::sal::Driver* driver,
CephContext* cct,
const std::string& luarocks_path,
int execute_interval) :
execute_interval(execute_interval),
dp(cct, dout_subsys, "lua background: "),
lua_manager(driver->get_lua_manager()),
cct(cct),
luarocks_path(luarocks_path) {}
void Background::shutdown(){
stopped = true;
cond.notify_all();
if (runner.joinable()) {
runner.join();
}
started = false;
stopped = false;
}
void Background::start() {
if (started) {
// start the thread only once
return;
}
started = true;
runner = std::thread(&Background::run, this);
const auto rc = ceph_pthread_setname(runner.native_handle(),
"lua_background");
ceph_assert(rc == 0);
}
void Background::pause() {
{
std::unique_lock cond_lock(pause_mutex);
paused = true;
}
cond.notify_all();
}
void Background::resume(rgw::sal::Driver* driver) {
lua_manager = driver->get_lua_manager();
paused = false;
cond.notify_all();
}
int Background::read_script() {
std::unique_lock cond_lock(pause_mutex);
if (paused) {
return -EAGAIN;
}
std::string tenant;
return rgw::lua::read_script(&dp, lua_manager.get(), tenant, null_yield, rgw::lua::context::background, rgw_script);
}
const BackgroundMapValue Background::empty_table_value;
const BackgroundMapValue& Background::get_table_value(const std::string& key) const {
std::unique_lock cond_lock(table_mutex);
const auto it = rgw_map.find(key);
if (it == rgw_map.end()) {
return empty_table_value;
}
return it->second;
}
//(1) Loads the script from the object if not paused
//(2) Executes the script
//(3) Sleep (configurable)
void Background::run() {
lua_State* const L = luaL_newstate();
rgw::lua::lua_state_guard lguard(L);
open_standard_libs(L);
set_package_path(L, luarocks_path);
create_debug_action(L, cct);
create_background_metatable(L);
const DoutPrefixProvider* const dpp = &dp;
while (!stopped) {
if (paused) {
ldpp_dout(dpp, 10) << "Lua background thread paused" << dendl;
std::unique_lock cond_lock(cond_mutex);
cond.wait(cond_lock, [this]{return !paused || stopped;});
if (stopped) {
ldpp_dout(dpp, 10) << "Lua background thread stopped" << dendl;
return;
}
ldpp_dout(dpp, 10) << "Lua background thread resumed" << dendl;
}
const auto rc = read_script();
if (rc == -ENOENT || rc == -EAGAIN) {
// either no script or paused, nothing to do
} else if (rc < 0) {
ldpp_dout(dpp, 1) << "WARNING: failed to read background script. error " << rc << dendl;
} else {
auto failed = false;
try {
//execute the background lua script
if (luaL_dostring(L, rgw_script.c_str()) != LUA_OK) {
const std::string err(lua_tostring(L, -1));
ldpp_dout(dpp, 1) << "Lua ERROR: " << err << dendl;
failed = true;
}
} catch (const std::exception& e) {
ldpp_dout(dpp, 1) << "Lua ERROR: " << e.what() << dendl;
failed = true;
}
if (perfcounter) {
perfcounter->inc((failed ? l_rgw_lua_script_fail : l_rgw_lua_script_ok), 1);
}
}
std::unique_lock cond_lock(cond_mutex);
cond.wait_for(cond_lock, std::chrono::seconds(execute_interval), [this]{return stopped;});
}
ldpp_dout(dpp, 10) << "Lua background thread stopped" << dendl;
}
void Background::create_background_metatable(lua_State* L) {
create_metatable<rgw::lua::RGWTable>(L, true, &rgw_map, &table_mutex);
}
} //namespace rgw::lua
| 5,748 | 30.587912 | 118 |
cc
|
null |
ceph-main/src/rgw/rgw_lua_background.h
|
#pragma once
#include "common/dout.h"
#include "rgw_common.h"
#include <string>
#include <unordered_map>
#include <variant>
#include "rgw_lua_utils.h"
#include "rgw_realm_reloader.h"
namespace rgw::lua {
//Interval between each execution of the script is set to 5 seconds
constexpr const int INIT_EXECUTE_INTERVAL = 5;
//Writeable meta table named RGW with mutex protection
using BackgroundMapValue = std::variant<std::string, long long int, double, bool>;
using BackgroundMap = std::unordered_map<std::string, BackgroundMapValue>;
struct RGWTable : EmptyMetaTable {
static const char* INCREMENT;
static const char* DECREMENT;
static std::string TableName() {return "RGW";}
static std::string Name() {return TableName() + "Meta";}
static int increment_by(lua_State* L);
static int IndexClosure(lua_State* L) {
const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, INCREMENT) == 0) {
lua_pushlightuserdata(L, map);
lua_pushlightuserdata(L, &mtx);
lua_pushboolean(L, false /*increment*/);
lua_pushcclosure(L, increment_by, THREE_UPVALS);
return ONE_RETURNVAL;
}
if (strcasecmp(index, DECREMENT) == 0) {
lua_pushlightuserdata(L, map);
lua_pushlightuserdata(L, &mtx);
lua_pushboolean(L, true /*decrement*/);
lua_pushcclosure(L, increment_by, THREE_UPVALS);
return ONE_RETURNVAL;
}
std::lock_guard l(mtx);
const auto it = map->find(std::string(index));
if (it == map->end()) {
lua_pushnil(L);
} else {
std::visit([L](auto&& value) { pushvalue(L, value); }, it->second);
}
return ONE_RETURNVAL;
}
static int LenClosure(lua_State* L) {
const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL)));
std::lock_guard l(mtx);
lua_pushinteger(L, map->size());
return ONE_RETURNVAL;
}
static int NewIndexClosure(lua_State* L) {
const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL)));
const auto index = luaL_checkstring(L, 2);
if (strcasecmp(index, INCREMENT) == 0 || strcasecmp(index, DECREMENT) == 0) {
return luaL_error(L, "increment/decrement are reserved function names for RGW");
}
std::unique_lock l(mtx);
size_t len;
BackgroundMapValue value;
const int value_type = lua_type(L, 3);
switch (value_type) {
case LUA_TNIL:
// erase the element. since in lua: "t[index] = nil" is removing the entry at "t[index]"
if (const auto it = map->find(index); it != map->end()) {
// index was found
update_erased_iterator<BackgroundMap>(L, it, map->erase(it));
}
return NO_RETURNVAL;
case LUA_TBOOLEAN:
value = static_cast<bool>(lua_toboolean(L, 3));
len = sizeof(bool);
break;
case LUA_TNUMBER:
if (lua_isinteger(L, 3)) {
value = lua_tointeger(L, 3);
len = sizeof(long long int);
} else {
value = lua_tonumber(L, 3);
len = sizeof(double);
}
break;
case LUA_TSTRING:
{
const auto str = lua_tolstring(L, 3, &len);
value = std::string{str, len};
break;
}
default:
l.unlock();
return luaL_error(L, "unsupported value type for RGW table");
}
if (len + strnlen(index, MAX_LUA_VALUE_SIZE)
> MAX_LUA_VALUE_SIZE) {
return luaL_error(L, "Lua maximum size of entry limit exceeded");
} else if (map->size() > MAX_LUA_KEY_ENTRIES) {
l.unlock();
return luaL_error(L, "Lua max number of entries limit exceeded");
} else {
map->insert_or_assign(index, value);
}
return NO_RETURNVAL;
}
static int PairsClosure(lua_State* L) {
auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
lua_pushlightuserdata(L, map);
lua_pushcclosure(L, next<BackgroundMap>, ONE_UPVAL); // push the stateless iterator function
lua_pushnil(L); // indicate this is the first call
// return next(), nil
return TWO_RETURNVALS;
}
};
class Background : public RGWRealmReloader::Pauser {
public:
static const BackgroundMapValue empty_table_value;
private:
BackgroundMap rgw_map;
bool stopped = false;
bool started = false;
bool paused = false;
int execute_interval;
const DoutPrefix dp;
std::unique_ptr<rgw::sal::LuaManager> lua_manager;
CephContext* const cct;
const std::string luarocks_path;
std::thread runner;
mutable std::mutex table_mutex;
std::mutex cond_mutex;
std::mutex pause_mutex;
std::condition_variable cond;
void run();
protected:
std::string rgw_script;
virtual int read_script();
public:
Background(rgw::sal::Driver* driver,
CephContext* cct,
const std::string& luarocks_path,
int execute_interval = INIT_EXECUTE_INTERVAL);
virtual ~Background() = default;
void start();
void shutdown();
void create_background_metatable(lua_State* L);
const BackgroundMapValue& get_table_value(const std::string& key) const;
template<typename T>
void put_table_value(const std::string& key, T value) {
std::unique_lock cond_lock(table_mutex);
rgw_map[key] = value;
}
void pause() override;
void resume(rgw::sal::Driver* _driver) override;
};
} //namepsace rgw::lua
| 5,848 | 29.784211 | 104 |
h
|
null |
ceph-main/src/rgw/rgw_lua_data_filter.cc
|
#include "rgw_lua_data_filter.h"
#include "rgw_lua_utils.h"
#include "rgw_lua_request.h"
#include "rgw_lua_background.h"
#include "rgw_process_env.h"
#include <lua.hpp>
namespace rgw::lua {
void push_bufferlist_byte(lua_State* L, bufferlist::iterator& it) {
char byte[1];
it.copy(1, byte);
lua_pushlstring(L, byte, 1);
}
struct BufferlistMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Data";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
const auto index = luaL_checkinteger(L, 2);
if (index <= 0 || index > bl->length()) {
// lua arrays start from 1
lua_pushnil(L);
return ONE_RETURNVAL;
}
auto it = bl->begin(index-1);
if (it != bl->end()) {
push_bufferlist_byte(L, it);
} else {
lua_pushnil(L);
}
return ONE_RETURNVAL;
}
static int PairsClosure(lua_State* L) {
auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(bl);
lua_pushlightuserdata(L, bl);
lua_pushcclosure(L, stateless_iter, ONE_UPVAL); // push the stateless iterator function
lua_pushnil(L); // indicate this is the first call
// return stateless_iter, nil
return TWO_RETURNVALS;
}
static int stateless_iter(lua_State* L) {
// based on: http://lua-users.org/wiki/GeneralizedPairsAndIpairs
auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
lua_Integer index;
if (lua_isnil(L, -1)) {
index = 1;
} else {
index = luaL_checkinteger(L, -1) + 1;
}
// lua arrays start from 1
auto it = bl->begin(index-1);
if (index > bl->length()) {
// index of the last element was provided
lua_pushnil(L);
lua_pushnil(L);
// return nil, nil
} else {
lua_pushinteger(L, index);
push_bufferlist_byte(L, it);
// return key, value
}
return TWO_RETURNVALS;
}
static int LenClosure(lua_State* L) {
const auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
lua_pushinteger(L, bl->length());
return ONE_RETURNVAL;
}
};
int RGWObjFilter::execute(bufferlist& bl, off_t offset, const char* op_name) const {
auto L = luaL_newstate();
lua_state_guard lguard(L);
open_standard_libs(L);
create_debug_action(L, s->cct);
// create the "Data" table
create_metatable<BufferlistMetaTable>(L, true, &bl);
lua_getglobal(L, BufferlistMetaTable::TableName().c_str());
ceph_assert(lua_istable(L, -1));
// create the "Request" table
request::create_top_metatable(L, s, op_name);
// create the "Offset" variable
lua_pushinteger(L, offset);
lua_setglobal(L, "Offset");
if (s->penv.lua.background) {
// create the "RGW" table
s->penv.lua.background->create_background_metatable(L);
lua_getglobal(L, rgw::lua::RGWTable::TableName().c_str());
ceph_assert(lua_istable(L, -1));
}
try {
// execute the lua script
if (luaL_dostring(L, script.c_str()) != LUA_OK) {
const std::string err(lua_tostring(L, -1));
ldpp_dout(s, 1) << "Lua ERROR: " << err << dendl;
return -EINVAL;
}
} catch (const std::runtime_error& e) {
ldpp_dout(s, 1) << "Lua ERROR: " << e.what() << dendl;
return -EINVAL;
}
return 0;
}
int RGWGetObjFilter::handle_data(bufferlist& bl,
off_t bl_ofs,
off_t bl_len) {
filter.execute(bl, bl_ofs, "get_obj");
// return value is ignored since we don't want to fail execution if lua script fails
return RGWGetObj_Filter::handle_data(bl, bl_ofs, bl_len);
}
int RGWPutObjFilter::process(bufferlist&& data, uint64_t logical_offset) {
filter.execute(data, logical_offset, "put_obj");
// return value is ignored since we don't want to fail execution if lua script fails
return rgw::putobj::Pipe::process(std::move(data), logical_offset);
}
} // namespace rgw::lua
| 4,100 | 27.479167 | 94 |
cc
|
null |
ceph-main/src/rgw/rgw_lua_data_filter.h
|
#pragma once
#include "rgw_op.h"
class DoutPrefixProvider;
namespace rgw::lua {
class RGWObjFilter {
req_state* const s;
const std::string script;
public:
RGWObjFilter(req_state* s,
const std::string& script) :
s(s), script(script) {}
int execute(bufferlist& bl, off_t offset, const char* op_name) const;
};
class RGWGetObjFilter : public RGWGetObj_Filter {
const RGWObjFilter filter;
public:
RGWGetObjFilter(req_state* s,
const std::string& script,
RGWGetObj_Filter* next) : RGWGetObj_Filter(next), filter(s, script)
{}
~RGWGetObjFilter() override = default;
int handle_data(bufferlist& bl,
off_t bl_ofs,
off_t bl_len) override;
};
class RGWPutObjFilter : public rgw::putobj::Pipe {
const RGWObjFilter filter;
public:
RGWPutObjFilter(req_state* s,
const std::string& script,
rgw::sal::DataProcessor* next) : rgw::putobj::Pipe(next), filter(s, script)
{}
~RGWPutObjFilter() override = default;
int process(bufferlist&& data, uint64_t logical_offset) override;
};
} // namespace rgw::lua
| 1,104 | 19.849057 | 82 |
h
|
null |
ceph-main/src/rgw/rgw_lua_request.cc
|
#include <sstream>
#include <stdexcept>
#include <lua.hpp>
#include "common/dout.h"
#include "services/svc_zone.h"
#include "rgw_lua_utils.h"
#include "rgw_lua.h"
#include "rgw_common.h"
#include "rgw_log.h"
#include "rgw_op.h"
#include "rgw_process_env.h"
#include "rgw_zone.h"
#include "rgw_acl.h"
#include "rgw_sal_rados.h"
#include "rgw_lua_background.h"
#include "rgw_perf_counters.h"
#define dout_subsys ceph_subsys_rgw
namespace rgw::lua::request {
// closure that perform ops log action
// e.g.
// Request.Log()
//
constexpr const char* RequestLogAction{"Log"};
int RequestLog(lua_State* L)
{
const auto rest = reinterpret_cast<RGWREST*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const auto olog = reinterpret_cast<OpsLogSink*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL)));
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(THIRD_UPVAL)));
const auto op(reinterpret_cast<RGWOp*>(lua_touserdata(L, lua_upvalueindex(FOURTH_UPVAL))));
if (s) {
const auto rc = rgw_log_op(rest, s, op, olog);
lua_pushinteger(L, rc);
} else {
ldpp_dout(s, 1) << "Lua ERROR: missing request state, cannot use ops log" << dendl;
lua_pushinteger(L, -EINVAL);
}
return ONE_RETURNVAL;
}
int SetAttribute(lua_State* L) {
auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(1)));
if (!s->trace || !s->trace->IsRecording()) {
return 0;
}
auto key = luaL_checkstring(L, 1);
int value_type = lua_type(L, 2);
switch (value_type) {
case LUA_TSTRING:
s->trace->SetAttribute(key, lua_tostring(L, 2));
break;
case LUA_TNUMBER:
if (lua_isinteger(L, 2)) {
s->trace->SetAttribute(key, static_cast<int64_t>(lua_tointeger(L, 2)));
} else {
s->trace->SetAttribute(key, static_cast<double>(lua_tonumber(L, 2)));
}
break;
default:
luaL_error(L, "unsupported value type for SetAttribute");
}
return 0;
}
int AddEvent(lua_State* L) {
auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(1)));
if (!s->trace || !s->trace->IsRecording()) {
return 0;
}
int args = lua_gettop(L);
if (args == 1) {
auto log = luaL_checkstring(L, 1);
s->trace->AddEvent(log);
} else if(args == 2) {
auto event_name = luaL_checkstring(L, 1);
std::unordered_map<const char*, jspan_attribute> event_values;
lua_pushnil(L);
while (lua_next(L, 2) != 0) {
if (lua_type(L, -2) != LUA_TSTRING) {
// skip pair if key is not a string
lua_pop(L, 1);
continue;
}
auto key = luaL_checkstring(L, -2);
int value_type = lua_type(L, -1);
switch (value_type) {
case LUA_TSTRING:
event_values.emplace(key, lua_tostring(L, -1));
break;
case LUA_TNUMBER:
if (lua_isinteger(L, -1)) {
event_values.emplace(key, static_cast<int64_t>(lua_tointeger(L, -1)));
} else {
event_values.emplace(key, static_cast<double>(lua_tonumber(L, -1)));
}
break;
}
lua_pop(L, 1);
}
lua_pop(L, 1);
s->trace->AddEvent(event_name, event_values);
}
return 0;
}
struct ResponseMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Response";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto err = reinterpret_cast<const rgw_err*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "HTTPStatusCode") == 0) {
lua_pushinteger(L, err->http_ret);
} else if (strcasecmp(index, "RGWCode") == 0) {
lua_pushinteger(L, err->ret);
} else if (strcasecmp(index, "HTTPStatus") == 0) {
pushstring(L, err->err_code);
} else if (strcasecmp(index, "Message") == 0) {
pushstring(L, err->message);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
static int NewIndexClosure(lua_State* L) {
auto err = reinterpret_cast<rgw_err*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "HTTPStatusCode") == 0) {
err->http_ret = luaL_checkinteger(L, 3);
} else if (strcasecmp(index, "RGWCode") == 0) {
err->ret = luaL_checkinteger(L, 3);
} else if (strcasecmp(index, "HTTPStatus") == 0) {
err->err_code.assign(luaL_checkstring(L, 3));
} else if (strcasecmp(index, "Message") == 0) {
err->message.assign(luaL_checkstring(L, 3));
} else {
return error_unknown_field(L, index, TableName());
}
return NO_RETURNVAL;
}
};
struct QuotaMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Quota";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto info = reinterpret_cast<RGWQuotaInfo*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "MaxSize") == 0) {
lua_pushinteger(L, info->max_size);
} else if (strcasecmp(index, "MaxObjects") == 0) {
lua_pushinteger(L, info->max_objects);
} else if (strcasecmp(index, "Enabled") == 0) {
lua_pushboolean(L, info->enabled);
} else if (strcasecmp(index, "Rounded") == 0) {
lua_pushboolean(L, !info->check_on_raw);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct PlacementRuleMetaTable : public EmptyMetaTable {
static std::string TableName() {return "PlacementRule";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto rule = reinterpret_cast<rgw_placement_rule*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Name") == 0) {
pushstring(L, rule->name);
} else if (strcasecmp(index, "StorageClass") == 0) {
pushstring(L, rule->storage_class);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct UserMetaTable : public EmptyMetaTable {
static std::string TableName() {return "User";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto user = reinterpret_cast<const rgw_user*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Tenant") == 0) {
pushstring(L, user->tenant);
} else if (strcasecmp(index, "Id") == 0) {
pushstring(L, user->id);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct TraceMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Trace";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Enable") == 0) {
lua_pushboolean(L, s->trace_enabled);
} else if(strcasecmp(index, "SetAttribute") == 0) {
lua_pushlightuserdata(L, s);
lua_pushcclosure(L, SetAttribute, ONE_UPVAL);
} else if(strcasecmp(index, "AddEvent") == 0) {
lua_pushlightuserdata(L, s);
lua_pushcclosure(L, AddEvent, ONE_UPVAL);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
static int NewIndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Enable") == 0) {
s->trace_enabled = lua_toboolean(L, 3);
} else {
return error_unknown_field(L, index, TableName());
}
return NO_RETURNVAL;
}
};
struct OwnerMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Owner";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto owner = reinterpret_cast<ACLOwner*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "DisplayName") == 0) {
pushstring(L, owner->get_display_name());
} else if (strcasecmp(index, "User") == 0) {
create_metatable<UserMetaTable>(L, false, &(owner->get_id()));
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct BucketMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Bucket";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const auto bucket = s->bucket.get();
const char* index = luaL_checkstring(L, 2);
if (rgw::sal::Bucket::empty(bucket)) {
if (strcasecmp(index, "Name") == 0) {
pushstring(L, s->init_state.url_bucket);
} else {
lua_pushnil(L);
}
} else if (strcasecmp(index, "Tenant") == 0) {
pushstring(L, bucket->get_tenant());
} else if (strcasecmp(index, "Name") == 0) {
pushstring(L, bucket->get_name());
} else if (strcasecmp(index, "Marker") == 0) {
pushstring(L, bucket->get_marker());
} else if (strcasecmp(index, "Id") == 0) {
pushstring(L, bucket->get_bucket_id());
} else if (strcasecmp(index, "Count") == 0) {
lua_pushinteger(L, bucket->get_count());
} else if (strcasecmp(index, "Size") == 0) {
lua_pushinteger(L, bucket->get_size());
} else if (strcasecmp(index, "ZoneGroupId") == 0) {
pushstring(L, bucket->get_info().zonegroup);
} else if (strcasecmp(index, "CreationTime") == 0) {
pushtime(L, bucket->get_creation_time());
} else if (strcasecmp(index, "MTime") == 0) {
pushtime(L, bucket->get_modification_time());
} else if (strcasecmp(index, "Quota") == 0) {
create_metatable<QuotaMetaTable>(L, false, &(bucket->get_info().quota));
} else if (strcasecmp(index, "PlacementRule") == 0) {
create_metatable<PlacementRuleMetaTable>(L, false, &(bucket->get_info().placement_rule));
} else if (strcasecmp(index, "User") == 0) {
create_metatable<UserMetaTable>(L, false, &(bucket->get_info().owner));
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
static int NewIndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const auto bucket = s->bucket.get();
const char* index = luaL_checkstring(L, 2);
if (rgw::sal::Bucket::empty(bucket)) {
if (strcasecmp(index, "Name") == 0) {
s->init_state.url_bucket = luaL_checkstring(L, 3);
return NO_RETURNVAL;
}
}
return error_unknown_field(L, index, TableName());
}
};
struct ObjectMetaTable : public EmptyMetaTable {
static const std::string TableName() {return "Object";}
static std::string Name() {return TableName() + "Meta";}
using Type = rgw::sal::Object;
static int IndexClosure(lua_State* L) {
const auto obj = reinterpret_cast<const Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Name") == 0) {
pushstring(L, obj->get_name());
} else if (strcasecmp(index, "Instance") == 0) {
pushstring(L, obj->get_instance());
} else if (strcasecmp(index, "Id") == 0) {
pushstring(L, obj->get_oid());
} else if (strcasecmp(index, "Size") == 0) {
lua_pushinteger(L, obj->get_obj_size());
} else if (strcasecmp(index, "MTime") == 0) {
pushtime(L, obj->get_mtime());
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct GrantMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Grant";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto grant = reinterpret_cast<ACLGrant*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Type") == 0) {
lua_pushinteger(L, grant->get_type().get_type());
} else if (strcasecmp(index, "User") == 0) {
const auto id_ptr = grant->get_id();
if (id_ptr) {
create_metatable<UserMetaTable>(L, false, const_cast<rgw_user*>(id_ptr));
} else {
lua_pushnil(L);
}
} else if (strcasecmp(index, "Permission") == 0) {
lua_pushinteger(L, grant->get_permission().get_permissions());
} else if (strcasecmp(index, "GroupType") == 0) {
lua_pushinteger(L, grant->get_group());
} else if (strcasecmp(index, "Referer") == 0) {
pushstring(L, grant->get_referer());
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct GrantsMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Grants";}
static std::string Name() {return TableName() + "Meta";}
using Type = ACLGrantMap;
static int IndexClosure(lua_State* L) {
const auto map = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
const auto it = map->find(std::string(index));
if (it == map->end()) {
lua_pushnil(L);
} else {
create_metatable<GrantMetaTable>(L, false, &(it->second));
}
return ONE_RETURNVAL;
}
static int PairsClosure(lua_State* L) {
auto map = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(map);
lua_pushlightuserdata(L, map);
lua_pushcclosure(L, next<Type, GrantMetaTable>, ONE_UPVAL); // push the "next()" function
lua_pushnil(L); // indicate this is the first call
// return next, nil
return TWO_RETURNVALS;
}
static int LenClosure(lua_State* L) {
const auto map = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
lua_pushinteger(L, map->size());
return ONE_RETURNVAL;
}
};
struct ACLMetaTable : public EmptyMetaTable {
static std::string TableName() {return "ACL";}
static std::string Name() {return TableName() + "Meta";}
using Type = RGWAccessControlPolicy;
static int IndexClosure(lua_State* L) {
const auto acl = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Owner") == 0) {
create_metatable<OwnerMetaTable>(L, false, &(acl->get_owner()));
} else if (strcasecmp(index, "Grants") == 0) {
create_metatable<GrantsMetaTable>(L, false, &(acl->get_acl().get_grant_map()));
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct StatementsMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Statements";}
static std::string Name() {return TableName() + "Meta";}
using Type = std::vector<rgw::IAM::Statement>;
static std::string statement_to_string(const rgw::IAM::Statement& statement) {
std::stringstream ss;
ss << statement;
return ss.str();
}
static int IndexClosure(lua_State* L) {
const auto statements = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const auto index = luaL_checkinteger(L, 2);
if (index >= (int)statements->size() || index < 0) {
lua_pushnil(L);
} else {
// TODO: policy language could be interpreted to lua and executed as such
pushstring(L, statement_to_string((*statements)[index]));
}
return ONE_RETURNVAL;
}
static int PairsClosure(lua_State* L) {
auto statements = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(statements);
lua_pushlightuserdata(L, statements);
lua_pushcclosure(L, stateless_iter, ONE_UPVAL); // push the stateless iterator function
lua_pushnil(L); // indicate this is the first call
// return stateless_iter, nil
return TWO_RETURNVALS;
}
static int stateless_iter(lua_State* L) {
auto statements = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
size_t next_it;
if (lua_isnil(L, -1)) {
next_it = 0;
} else {
const auto it = luaL_checkinteger(L, -1);
next_it = it+1;
}
if (next_it >= statements->size()) {
// index of the last element was provided
lua_pushnil(L);
lua_pushnil(L);
// return nil, nil
} else {
lua_pushinteger(L, next_it);
pushstring(L, statement_to_string((*statements)[next_it]));
// return key, value
}
return TWO_RETURNVALS;
}
static int LenClosure(lua_State* L) {
const auto statements = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
lua_pushinteger(L, statements->size());
return ONE_RETURNVAL;
}
};
struct PolicyMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Policy";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto policy = reinterpret_cast<rgw::IAM::Policy*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Text") == 0) {
pushstring(L, policy->text);
} else if (strcasecmp(index, "Id") == 0) {
// TODO create pushstring for std::unique_ptr
if (!policy->id) {
lua_pushnil(L);
} else {
pushstring(L, policy->id.get());
}
} else if (strcasecmp(index, "Statements") == 0) {
create_metatable<StatementsMetaTable>(L, false, &(policy->statements));
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct PoliciesMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Policies";}
static std::string Name() {return TableName() + "Meta";}
using Type = std::vector<rgw::IAM::Policy>;
static int IndexClosure(lua_State* L) {
const auto policies = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const auto index = luaL_checkinteger(L, 2);
if (index >= (int)policies->size() || index < 0) {
lua_pushnil(L);
} else {
create_metatable<PolicyMetaTable>(L, false, &((*policies)[index]));
}
return ONE_RETURNVAL;
}
static int PairsClosure(lua_State* L) {
auto policies = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(policies);
lua_pushlightuserdata(L, policies);
lua_pushcclosure(L, stateless_iter, ONE_UPVAL); // push the stateless iterator function
lua_pushnil(L); // indicate this is the first call
// return stateless_iter, nil
return TWO_RETURNVALS;
}
static int stateless_iter(lua_State* L) {
auto policies = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
size_t next_it;
if (lua_isnil(L, -1)) {
next_it = 0;
} else {
ceph_assert(lua_isinteger(L, -1));
const auto it = luaL_checkinteger(L, -1);
next_it = it+1;
}
if (next_it >= policies->size()) {
// index of the last element was provided
lua_pushnil(L);
lua_pushnil(L);
// return nil, nil
} else {
lua_pushinteger(L, next_it);
create_metatable<PolicyMetaTable>(L, false, &((*policies)[next_it]));
// return key, value
}
return TWO_RETURNVALS;
}
static int LenClosure(lua_State* L) {
const auto policies = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
lua_pushinteger(L, policies->size());
return ONE_RETURNVAL;
}
};
struct HTTPMetaTable : public EmptyMetaTable {
static std::string TableName() {return "HTTP";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto info = reinterpret_cast<req_info*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Parameters") == 0) {
create_metatable<StringMapMetaTable<>>(L, false, &(info->args.get_params()));
} else if (strcasecmp(index, "Resources") == 0) {
// TODO: add non-const api to get resources
create_metatable<StringMapMetaTable<>>(L, false,
const_cast<std::map<std::string, std::string>*>(&(info->args.get_sub_resources())));
} else if (strcasecmp(index, "Metadata") == 0) {
create_metatable<StringMapMetaTable<meta_map_t, StringMapWriteableNewIndex<meta_map_t>>>(L, false, &(info->x_meta_map));
} else if (strcasecmp(index, "Host") == 0) {
pushstring(L, info->host);
} else if (strcasecmp(index, "Method") == 0) {
pushstring(L, info->method);
} else if (strcasecmp(index, "URI") == 0) {
pushstring(L, info->request_uri);
} else if (strcasecmp(index, "QueryString") == 0) {
pushstring(L, info->request_params);
} else if (strcasecmp(index, "Domain") == 0) {
pushstring(L, info->domain);
} else if (strcasecmp(index, "StorageClass") == 0) {
pushstring(L, info->storage_class);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
static int NewIndexClosure(lua_State* L) {
auto info = reinterpret_cast<req_info*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "StorageClass") == 0) {
info->storage_class = luaL_checkstring(L, 3);
} else {
return error_unknown_field(L, index, TableName());
}
return NO_RETURNVAL;
}
};
struct CopyFromMetaTable : public EmptyMetaTable {
static std::string TableName() {return "CopyFrom";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Tenant") == 0) {
pushstring(L, s->src_tenant_name);
} else if (strcasecmp(index, "Bucket") == 0) {
pushstring(L, s->src_bucket_name);
} else if (strcasecmp(index, "Object") == 0) {
create_metatable<ObjectMetaTable>(L, false, s->src_object);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct ZoneGroupMetaTable : public EmptyMetaTable {
static std::string TableName() {return "ZoneGroup";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "Name") == 0) {
pushstring(L, s->zonegroup_name);
} else if (strcasecmp(index, "Endpoint") == 0) {
pushstring(L, s->zonegroup_endpoint);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
struct RequestMetaTable : public EmptyMetaTable {
static std::string TableName() {return "Request";}
static std::string Name() {return TableName() + "Meta";}
// __index closure that expect req_state to be captured
static int IndexClosure(lua_State* L) {
const auto s = reinterpret_cast<req_state*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
const auto op_name = reinterpret_cast<const char*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL)));
const char* index = luaL_checkstring(L, 2);
if (strcasecmp(index, "RGWOp") == 0) {
pushstring(L, op_name);
} else if (strcasecmp(index, "DecodedURI") == 0) {
pushstring(L, s->decoded_uri);
} else if (strcasecmp(index, "ContentLength") == 0) {
lua_pushinteger(L, s->content_length);
} else if (strcasecmp(index, "GenericAttributes") == 0) {
create_metatable<StringMapMetaTable<>>(L, false, &(s->generic_attrs));
} else if (strcasecmp(index, "Response") == 0) {
create_metatable<ResponseMetaTable>(L, false, &(s->err));
} else if (strcasecmp(index, "SwiftAccountName") == 0) {
if (s->dialect == "swift") {
pushstring(L, s->account_name);
} else {
lua_pushnil(L);
}
} else if (strcasecmp(index, "Bucket") == 0) {
create_metatable<BucketMetaTable>(L, false, s);
} else if (strcasecmp(index, "Object") == 0) {
create_metatable<ObjectMetaTable>(L, false, s->object);
} else if (strcasecmp(index, "CopyFrom") == 0) {
if (s->op_type == RGW_OP_COPY_OBJ) {
create_metatable<CopyFromMetaTable>(L, false, s);
} else {
lua_pushnil(L);
}
} else if (strcasecmp(index, "ObjectOwner") == 0) {
create_metatable<OwnerMetaTable>(L, false, &(s->owner));
} else if (strcasecmp(index, "ZoneGroup") == 0) {
create_metatable<ZoneGroupMetaTable>(L, false, s);
} else if (strcasecmp(index, "UserACL") == 0) {
create_metatable<ACLMetaTable>(L, false, s->user_acl);
} else if (strcasecmp(index, "BucketACL") == 0) {
create_metatable<ACLMetaTable>(L, false, s->bucket_acl);
} else if (strcasecmp(index, "ObjectACL") == 0) {
create_metatable<ACLMetaTable>(L, false, s->object_acl);
} else if (strcasecmp(index, "Environment") == 0) {
create_metatable<StringMapMetaTable<rgw::IAM::Environment>>(L, false, &(s->env));
} else if (strcasecmp(index, "Policy") == 0) {
// TODO: create a wrapper to std::optional
if (!s->iam_policy) {
lua_pushnil(L);
} else {
create_metatable<PolicyMetaTable>(L, false, s->iam_policy.get_ptr());
}
} else if (strcasecmp(index, "UserPolicies") == 0) {
create_metatable<PoliciesMetaTable>(L, false, &(s->iam_user_policies));
} else if (strcasecmp(index, "RGWId") == 0) {
pushstring(L, s->host_id);
} else if (strcasecmp(index, "HTTP") == 0) {
create_metatable<HTTPMetaTable>(L, false, &(s->info));
} else if (strcasecmp(index, "Time") == 0) {
pushtime(L, s->time);
} else if (strcasecmp(index, "Dialect") == 0) {
pushstring(L, s->dialect);
} else if (strcasecmp(index, "Id") == 0) {
pushstring(L, s->req_id);
} else if (strcasecmp(index, "TransactionId") == 0) {
pushstring(L, s->trans_id);
} else if (strcasecmp(index, "Tags") == 0) {
create_metatable<StringMapMetaTable<RGWObjTags::tag_map_t>>(L, false, &(s->tagset.get_tags()));
} else if (strcasecmp(index, "User") == 0) {
if (!s->user) {
lua_pushnil(L);
} else {
create_metatable<UserMetaTable>(L, false, const_cast<rgw_user*>(&(s->user->get_id())));
}
} else if (strcasecmp(index, "Trace") == 0) {
create_metatable<TraceMetaTable>(L, false, s);
} else {
return error_unknown_field(L, index, TableName());
}
return ONE_RETURNVAL;
}
};
void create_top_metatable(lua_State* L, req_state* s, const char* op_name) {
create_metatable<RequestMetaTable>(L, true, s, const_cast<char*>(op_name));
lua_getglobal(L, RequestMetaTable::TableName().c_str());
ceph_assert(lua_istable(L, -1));
}
int execute(
rgw::sal::Driver* driver,
RGWREST* rest,
OpsLogSink* olog,
req_state* s,
RGWOp* op,
const std::string& script)
{
auto L = luaL_newstate();
const char* op_name = op ? op->name() : "Unknown";
lua_state_guard lguard(L);
open_standard_libs(L);
set_package_path(L, s->penv.lua.luarocks_path);
create_debug_action(L, s->cct);
create_metatable<RequestMetaTable>(L, true, s, const_cast<char*>(op_name));
lua_getglobal(L, RequestMetaTable::TableName().c_str());
ceph_assert(lua_istable(L, -1));
// add the ops log action
pushstring(L, RequestLogAction);
lua_pushlightuserdata(L, rest);
lua_pushlightuserdata(L, olog);
lua_pushlightuserdata(L, s);
lua_pushlightuserdata(L, op);
lua_pushcclosure(L, RequestLog, FOUR_UPVALS);
lua_rawset(L, -3);
if (s->penv.lua.background) {
s->penv.lua.background->create_background_metatable(L);
lua_getglobal(L, rgw::lua::RGWTable::TableName().c_str());
ceph_assert(lua_istable(L, -1));
}
int rc = 0;
try {
// execute the lua script
if (luaL_dostring(L, script.c_str()) != LUA_OK) {
const std::string err(lua_tostring(L, -1));
ldpp_dout(s, 1) << "Lua ERROR: " << err << dendl;
rc = -1;
}
} catch (const std::runtime_error& e) {
ldpp_dout(s, 1) << "Lua ERROR: " << e.what() << dendl;
rc = -1;
}
if (perfcounter) {
perfcounter->inc((rc == -1 ? l_rgw_lua_script_fail : l_rgw_lua_script_ok), 1);
}
return rc;
}
} // namespace rgw::lua::request
| 29,324 | 32.745685 | 126 |
cc
|
null |
ceph-main/src/rgw/rgw_lua_request.h
|
#pragma once
#include <string>
#include "include/common_fwd.h"
#include "rgw_sal_fwd.h"
struct lua_State;
class req_state;
class RGWREST;
class OpsLogSink;
namespace rgw::lua::request {
// create the request metatable
void create_top_metatable(lua_State* L, req_state* s, const char* op_name);
// execute a lua script in the Request context
int execute(
rgw::sal::Driver* driver,
RGWREST* rest,
OpsLogSink* olog,
req_state *s,
RGWOp* op,
const std::string& script);
} // namespace rgw::lua::request
| 530 | 18.666667 | 75 |
h
|
null |
ceph-main/src/rgw/rgw_lua_utils.cc
|
#include <string>
#include <lua.hpp>
#include "common/ceph_context.h"
#include "common/dout.h"
#include "rgw_lua_utils.h"
#include "rgw_lua_version.h"
#define dout_subsys ceph_subsys_rgw
namespace rgw::lua {
// TODO - add the folowing generic functions
// lua_push(lua_State* L, const std::string& str)
// template<typename T> lua_push(lua_State* L, const std::optional<T>& val)
// lua_push(lua_State* L, const ceph::real_time& tp)
constexpr const char* RGWDebugLogAction{"RGWDebugLog"};
int RGWDebugLog(lua_State* L)
{
auto cct = reinterpret_cast<CephContext*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
auto message = luaL_checkstring(L, 1);
ldout(cct, 20) << "Lua INFO: " << message << dendl;
return 0;
}
void create_debug_action(lua_State* L, CephContext* cct) {
lua_pushlightuserdata(L, cct);
lua_pushcclosure(L, RGWDebugLog, ONE_UPVAL);
lua_setglobal(L, RGWDebugLogAction);
}
void stack_dump(lua_State* L) {
const auto top = lua_gettop(L);
std::cout << std::endl << " ---------------- Stack Dump ----------------" << std::endl;
std::cout << "Stack Size: " << top << std::endl;
for (int i = 1, j = -top; i <= top; i++, j++) {
std::cout << "[" << i << "," << j << "][" << luaL_typename(L, i) << "]: ";
switch (lua_type(L, i)) {
case LUA_TNUMBER:
std::cout << lua_tonumber(L, i);
break;
case LUA_TSTRING:
std::cout << lua_tostring(L, i);
break;
case LUA_TBOOLEAN:
std::cout << (lua_toboolean(L, i) ? "true" : "false");
break;
case LUA_TNIL:
std::cout << "nil";
break;
default:
std::cout << lua_topointer(L, i);
break;
}
std::cout << std::endl;
}
std::cout << "--------------- Stack Dump Finished ---------------" << std::endl;
}
void set_package_path(lua_State* L, const std::string& install_dir) {
if (install_dir.empty()) {
return;
}
lua_getglobal(L, "package");
if (!lua_istable(L, -1)) {
return;
}
const auto path = install_dir+"/share/lua/"+CEPH_LUA_VERSION+"/?.lua";
pushstring(L, path);
lua_setfield(L, -2, "path");
const auto cpath = install_dir+"/lib/lua/"+CEPH_LUA_VERSION+"/?.so;"+install_dir+"/lib64/lua/"+CEPH_LUA_VERSION+"/?.so";
pushstring(L, cpath);
lua_setfield(L, -2, "cpath");
}
void open_standard_libs(lua_State* L) {
luaL_openlibs(L);
unsetglobal(L, "load");
unsetglobal(L, "loadfile");
unsetglobal(L, "loadstring");
unsetglobal(L, "dofile");
unsetglobal(L, "debug");
// remove os.exit()
lua_getglobal(L, "os");
lua_pushstring(L, "exit");
lua_pushnil(L);
lua_settable(L, -3);
}
} // namespace rgw::lua
| 2,652 | 26.635417 | 122 |
cc
|
null |
ceph-main/src/rgw/rgw_lua_utils.h
|
#pragma once
#include <type_traits>
#include <variant>
#include <string.h>
#include <memory>
#include <map>
#include <string>
#include <string_view>
#include <ctime>
#include <lua.hpp>
#include "include/common_fwd.h"
#include "rgw_perf_counters.h"
// a helper type traits structs for detecting std::variant
template<class>
struct is_variant : std::false_type {};
template<class... Ts>
struct is_variant<std::variant<Ts...>> :
std::true_type {};
namespace rgw::lua {
// push ceph time in string format: "%Y-%m-%d %H:%M:%S"
template <typename CephTime>
void pushtime(lua_State* L, const CephTime& tp)
{
const auto tt = CephTime::clock::to_time_t(tp);
const auto tm = *std::localtime(&tt);
char buff[64];
std::strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", &tm);
lua_pushstring(L, buff);
}
inline void pushstring(lua_State* L, std::string_view str)
{
lua_pushlstring(L, str.data(), str.size());
}
inline void pushvalue(lua_State* L, const std::string& value) {
pushstring(L, value);
}
inline void pushvalue(lua_State* L, long long value) {
lua_pushinteger(L, value);
}
inline void pushvalue(lua_State* L, double value) {
lua_pushnumber(L, value);
}
inline void pushvalue(lua_State* L, bool value) {
lua_pushboolean(L, value);
}
inline void unsetglobal(lua_State* L, const char* name)
{
lua_pushnil(L);
lua_setglobal(L, name);
}
// dump the lua stack to stdout
void stack_dump(lua_State* L);
class lua_state_guard {
lua_State* l;
public:
lua_state_guard(lua_State* _l) : l(_l) {
if (perfcounter) {
perfcounter->inc(l_rgw_lua_current_vms, 1);
}
}
~lua_state_guard() {
lua_close(l);
if (perfcounter) {
perfcounter->dec(l_rgw_lua_current_vms, 1);
}
}
void reset(lua_State* _l=nullptr) {l = _l;}
};
constexpr const int MAX_LUA_VALUE_SIZE = 1000;
constexpr const int MAX_LUA_KEY_ENTRIES = 100000;
constexpr auto ONE_UPVAL = 1;
constexpr auto TWO_UPVALS = 2;
constexpr auto THREE_UPVALS = 3;
constexpr auto FOUR_UPVALS = 4;
constexpr auto FIVE_UPVALS = 5;
constexpr auto FIRST_UPVAL = 1;
constexpr auto SECOND_UPVAL = 2;
constexpr auto THIRD_UPVAL = 3;
constexpr auto FOURTH_UPVAL = 4;
constexpr auto FIFTH_UPVAL = 5;
constexpr auto NO_RETURNVAL = 0;
constexpr auto ONE_RETURNVAL = 1;
constexpr auto TWO_RETURNVALS = 2;
constexpr auto THREE_RETURNVALS = 3;
constexpr auto FOUR_RETURNVALS = 4;
// utility functions to create a metatable
// and tie it to an unnamed table
//
// add an __index method to it, to allow reading values
// if "readonly" parameter is set to "false", it will also add
// a __newindex method to it, to allow writing values
// if the "toplevel" parameter is set to "true", it will name the
// table as well as the metatable, this would allow direct access from
// the lua script.
//
// The MetaTable is expected to be a class with the following members:
// Name (static function returning the unique name of the metatable)
// TableName (static function returning the unique name of the table - needed only for "toplevel" tables)
// Type (typename) - the type of the "upvalue" (the type that the meta table represent)
// IndexClosure (static function return "int" and accept "lua_State*")
// NewIndexClosure (static function return "int" and accept "lua_State*")
// e.g.
// struct MyStructMetaTable {
// static std::string TableName() {
// return "MyStruct";
// }
//
// using Type = MyStruct;
//
// static int IndexClosure(lua_State* L) {
// const auto value = reinterpret_cast<const Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
// ...
// }
// static int NewIndexClosure(lua_State* L) {
// auto value = reinterpret_cast<Type*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
// ...
// }
// };
//
template<typename MetaTable, typename... Upvalues>
void create_metatable(lua_State* L, bool toplevel, Upvalues... upvalues)
{
constexpr auto upvals_size = sizeof...(upvalues);
const std::array<void*, upvals_size> upvalue_arr = {upvalues...};
// create table
lua_newtable(L);
if (toplevel) {
// duplicate the table to make sure it remain in the stack
lua_pushvalue(L, -1);
// give table a name (in cae of "toplevel")
lua_setglobal(L, MetaTable::TableName().c_str());
}
// create metatable
[[maybe_unused]] const auto rc = luaL_newmetatable(L, MetaTable::Name().c_str());
const auto table_stack_pos = lua_gettop(L);
// add "index" closure to metatable
lua_pushliteral(L, "__index");
for (const auto upvalue : upvalue_arr) {
lua_pushlightuserdata(L, upvalue);
}
lua_pushcclosure(L, MetaTable::IndexClosure, upvals_size);
lua_rawset(L, table_stack_pos);
// add "newindex" closure to metatable
lua_pushliteral(L, "__newindex");
for (const auto upvalue : upvalue_arr) {
lua_pushlightuserdata(L, upvalue);
}
lua_pushcclosure(L, MetaTable::NewIndexClosure, upvals_size);
lua_rawset(L, table_stack_pos);
// add "pairs" closure to metatable
lua_pushliteral(L, "__pairs");
for (const auto upvalue : upvalue_arr) {
lua_pushlightuserdata(L, upvalue);
}
lua_pushcclosure(L, MetaTable::PairsClosure, upvals_size);
lua_rawset(L, table_stack_pos);
// add "len" closure to metatable
lua_pushliteral(L, "__len");
for (const auto upvalue : upvalue_arr) {
lua_pushlightuserdata(L, upvalue);
}
lua_pushcclosure(L, MetaTable::LenClosure, upvals_size);
lua_rawset(L, table_stack_pos);
// tie metatable and table
ceph_assert(lua_gettop(L) == table_stack_pos);
lua_setmetatable(L, -2);
}
template<typename MetaTable>
void create_metatable(lua_State* L, bool toplevel, std::unique_ptr<typename MetaTable::Type>& ptr)
{
if (ptr) {
create_metatable<MetaTable>(L, toplevel, reinterpret_cast<void*>(ptr.get()));
} else {
lua_pushnil(L);
}
}
// following struct may be used as a base class for other MetaTable classes
// note, however, this is not mandatory to use it as a base
struct EmptyMetaTable {
// by default everythinmg is "readonly"
// to change, overload this function in the derived
static int NewIndexClosure(lua_State* L) {
return luaL_error(L, "trying to write to readonly field");
}
// by default nothing is iterable
// to change, overload this function in the derived
static int PairsClosure(lua_State* L) {
return luaL_error(L, "trying to iterate over non-iterable field");
}
// by default nothing is iterable
// to change, overload this function in the derived
static int LenClosure(lua_State* L) {
return luaL_error(L, "trying to get length of non-iterable field");
}
static int error_unknown_field(lua_State* L, const std::string& index, const std::string& table) {
return luaL_error(L, "unknown field name: %s provided to: %s",
index.c_str(), table.c_str());
}
};
// create a debug log action
// it expects CephContext to be captured
// it expects one string parameter, which is the message to log
// could be executed from any context that has CephContext
// e.g.
// RGWDebugLog("hello world from lua")
//
void create_debug_action(lua_State* L, CephContext* cct);
// set the packages search path according to:
// package.path = "<install_dir>/share/lua/5.3/?.lua"
// package.cpath = "<install_dir>/lib/lua/5.3/?.so"
void set_package_path(lua_State* L, const std::string& install_dir);
// open standard lua libs and remove the following functions:
// os.exit()
// load()
// loadfile()
// loadstring()
// dofile()
// and the "debug" library
void open_standard_libs(lua_State* L);
typedef int MetaTableClosure(lua_State* L);
// copy the input iterator into a new iterator with memory allocated as userdata
// - allow for string conversion of the iterator (into its key)
// - storing the iterator in the metadata table to be used for iterator invalidation handling
// - since we have only one iterator per map/table we don't allow for nested loops or another iterationn
// after breaking out of an iteration
template<typename MapType>
typename MapType::iterator* create_iterator_metadata(lua_State* L, const typename MapType::iterator& start_it, const typename MapType::iterator& end_it) {
using Iterator = typename MapType::iterator;
// create metatable for userdata
// metatable is created before the userdata to save on allocation if the metatable already exists
const auto metatable_is_new = luaL_newmetatable(L, typeid(typename MapType::key_type).name());
const auto metatable_pos = lua_gettop(L);
int userdata_pos;
Iterator* new_it = nullptr;
if (!metatable_is_new) {
// metatable already exists
lua_pushliteral(L, "__iterator");
const auto type = lua_rawget(L, metatable_pos);
ceph_assert(type != LUA_TNIL);
auto old_it = reinterpret_cast<typename MapType::iterator*>(lua_touserdata(L, -1));
// verify we are not mid-iteration
if (*old_it != end_it) {
luaL_error(L, "Trying to iterate '%s' before previous iteration finished",
typeid(typename MapType::key_type).name());
return nullptr;
}
// we use the same memory buffer
new_it = old_it;
*new_it = start_it;
// push the userdata so it could be tied to the metatable
lua_pushlightuserdata(L, new_it);
userdata_pos = lua_gettop(L);
} else {
// new metatable
auto it_buff = lua_newuserdata(L, sizeof(Iterator));
userdata_pos = lua_gettop(L);
new_it = new (it_buff) Iterator(start_it);
}
// push the metatable again so it could be tied to the userdata
lua_pushvalue(L, metatable_pos);
// store the iterator pointer in the metatable
lua_pushliteral(L, "__iterator");
lua_pushlightuserdata(L, new_it);
lua_rawset(L, metatable_pos);
// add indication that we are "mid iteration"
// add "tostring" closure to metatable
lua_pushliteral(L, "__tostring");
lua_pushlightuserdata(L, new_it);
lua_pushcclosure(L, [](lua_State* L) {
// the key of the table is expected to be convertible to char*
static_assert(std::is_constructible<typename MapType::key_type, const char*>());
auto iter = reinterpret_cast<Iterator*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(iter);
pushstring(L, (*iter)->first);
return ONE_RETURNVAL;
}, ONE_UPVAL);
lua_rawset(L, metatable_pos);
// define a finalizer of the iterator
lua_pushliteral(L, "__gc");
lua_pushlightuserdata(L, new_it);
lua_pushcclosure(L, [](lua_State* L) {
auto iter = reinterpret_cast<Iterator*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(iter);
iter->~Iterator();
return NO_RETURNVAL;
}, ONE_UPVAL);
lua_rawset(L, metatable_pos);
// tie userdata and metatable
lua_setmetatable(L, userdata_pos);
return new_it;
}
template<typename MapType>
void update_erased_iterator(lua_State* L, const typename MapType::iterator& old_it, const typename MapType::iterator& new_it) {
// a metatable exists for the iterator
if (luaL_getmetatable(L, typeid(typename MapType::key_type).name()) != LUA_TNIL) {
const auto metatable_pos = lua_gettop(L);
lua_pushliteral(L, "__iterator");
if (lua_rawget(L, metatable_pos) != LUA_TNIL) {
// an iterator was stored
auto stored_it = reinterpret_cast<typename MapType::iterator*>(lua_touserdata(L, -1));
ceph_assert(stored_it);
if (old_it == *stored_it) {
// changed the stored iterator to the iteator
*stored_it = new_it;
}
}
}
}
// __newindex implementation for any map type holding strings
// or other types constructable from "char*"
// this function allow deletion of an entry by setting "nil" to the entry
// it also limits the size of the entry: key + value cannot exceed MAX_LUA_VALUE_SIZE
// and limits the number of entries in the map, to not exceed MAX_LUA_KEY_ENTRIES
template<typename MapType=std::map<std::string, std::string>>
int StringMapWriteableNewIndex(lua_State* L) {
static_assert(std::is_constructible<typename MapType::key_type, const char*>());
static_assert(std::is_constructible<typename MapType::mapped_type, const char*>());
const auto map = reinterpret_cast<MapType*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(map);
const char* index = luaL_checkstring(L, 2);
if (lua_isnil(L, 3) == 0) {
const char* value = luaL_checkstring(L, 3);
if (strnlen(value, MAX_LUA_VALUE_SIZE) + strnlen(index, MAX_LUA_VALUE_SIZE)
> MAX_LUA_VALUE_SIZE) {
return luaL_error(L, "Lua maximum size of entry limit exceeded");
} else if (map->size() > MAX_LUA_KEY_ENTRIES) {
return luaL_error(L, "Lua max number of entries limit exceeded");
} else {
map->insert_or_assign(index, value);
}
} else {
// erase the element. since in lua: "t[index] = nil" is removing the entry at "t[index]"
if (const auto it = map->find(index); it != map->end()) {
// index was found
update_erased_iterator<MapType>(L, it, map->erase(it));
}
}
return NO_RETURNVAL;
}
// implements the lua next() function for iterating over a table
// first argument is a table and the second argument is an index in this table
// returns the next index of the table and its associated value
// when input index is nil, the function returns the initial value and index
// when the it reaches the last entry of the table it return nil as the index and value
template<typename MapType, typename ValueMetaType=void>
int next(lua_State* L) {
using Iterator = typename MapType::iterator;
auto map = reinterpret_cast<MapType*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(map);
Iterator* next_it = nullptr;
if (lua_isnil(L, 2)) {
// pop the 2 nils
lua_pop(L, 2);
// create userdata
next_it = create_iterator_metadata<MapType>(L, map->begin(), map->end());
} else {
next_it = reinterpret_cast<Iterator*>(lua_touserdata(L, 2));
ceph_assert(next_it);
*next_it = std::next(*next_it);
}
if (*next_it == map->end()) {
// index of the last element was provided
lua_pushnil(L);
lua_pushnil(L);
return TWO_RETURNVALS;
// return nil, nil
}
// key (userdata iterator) is already on the stack
// push the value
using ValueType = typename MapType::mapped_type;
auto& value = (*next_it)->second;
if constexpr(std::is_constructible<std::string, ValueType>()) {
// as an std::string
pushstring(L, value);
} else if constexpr(is_variant<ValueType>()) {
// as an std::variant
std::visit([L](auto&& value) { pushvalue(L, value); }, value);
} else {
// as a metatable
create_metatable<ValueMetaType>(L, false, &(value));
}
// return key, value
return TWO_RETURNVALS;
}
template<typename MapType=std::map<std::string, std::string>,
MetaTableClosure NewIndex=EmptyMetaTable::NewIndexClosure>
struct StringMapMetaTable : public EmptyMetaTable {
static std::string TableName() {return "StringMap";}
static std::string Name() {return TableName() + "Meta";}
static int IndexClosure(lua_State* L) {
const auto map = reinterpret_cast<MapType*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(map);
const char* index = luaL_checkstring(L, 2);
const auto it = map->find(std::string(index));
if (it == map->end()) {
lua_pushnil(L);
} else {
pushstring(L, it->second);
}
return ONE_RETURNVAL;
}
static int NewIndexClosure(lua_State* L) {
return NewIndex(L);
}
static int PairsClosure(lua_State* L) {
auto map = reinterpret_cast<MapType*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
ceph_assert(map);
lua_pushlightuserdata(L, map);
lua_pushcclosure(L, next<MapType>, ONE_UPVAL); // push the "next()" function
lua_pushnil(L); // indicate this is the first call
// return next, nil
return TWO_RETURNVALS;
}
static int LenClosure(lua_State* L) {
const auto map = reinterpret_cast<MapType*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL)));
lua_pushinteger(L, map->size());
return ONE_RETURNVAL;
}
};
} // namespace rgw::lua
| 16,092 | 32.737945 | 154 |
h
|
null |
ceph-main/src/rgw/rgw_lua_version.h
|
#pragma once
#include <lua.hpp>
#include <string>
namespace rgw::lua {
const std::string CEPH_LUA_VERSION(LUA_VERSION_MAJOR "." LUA_VERSION_MINOR);
}
| 155 | 12 | 76 |
h
|
null |
ceph-main/src/rgw/rgw_main.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <boost/intrusive/list.hpp>
#include "common/ceph_argparse.h"
#include "global/global_init.h"
#include "global/signal_handler.h"
#include "common/config.h"
#include "common/errno.h"
#include "common/Timer.h"
#include "common/TracepointProvider.h"
#include "rgw_main.h"
#include "rgw_signal.h"
#include "rgw_common.h"
#include "rgw_lib.h"
#include "rgw_log.h"
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
using namespace std;
static constexpr auto dout_subsys = ceph_subsys_rgw;
static sig_t sighandler_alrm;
static void godown_alarm(int signum)
{
_exit(0);
}
class C_InitTimeout : public Context {
public:
C_InitTimeout() {}
void finish(int r) override {
derr << "Initialization timeout, failed to initialize" << dendl;
exit(1);
}
};
static int usage()
{
cout << "usage: radosgw [options...]" << std::endl;
cout << "options:\n";
cout << " --rgw-region=<region> region in which radosgw runs\n";
cout << " --rgw-zone=<zone> zone in which radosgw runs\n";
cout << " --rgw-socket-path=<path> specify a unix domain socket path\n";
cout << " -m monaddress[:port] connect to specified monitor\n";
cout << " --keyring=<path> path to radosgw keyring\n";
cout << " --logfile=<logfile> file to log debug output\n";
cout << " --debug-rgw=<log-level>/<memory-level> set radosgw debug level\n";
generic_server_usage();
return 0;
}
/*
* start up the RADOS connection and then handle HTTP messages as they come in
*/
int main(int argc, char *argv[])
{
int r{0};
// dout() messages will be sent to stderr, but FCGX wants messages on stdout
// Redirect stderr to stdout.
TEMP_FAILURE_RETRY(close(STDERR_FILENO));
if (TEMP_FAILURE_RETRY(dup2(STDOUT_FILENO, STDERR_FILENO)) < 0) {
int err = errno;
cout << "failed to redirect stderr to stdout: " << cpp_strerror(err)
<< std::endl;
return ENOSYS;
}
/* alternative default for module */
map<std::string,std::string> defaults = {
{ "debug_rgw", "1/5" },
{ "keyring", "$rgw_data/keyring" },
{ "objecter_inflight_ops", "24576" },
// require a secure mon connection by default
{ "ms_mon_client_mode", "secure" },
{ "auth_client_required", "cephx" }
};
auto args = argv_to_vec(argc, argv);
if (args.empty()) {
cerr << argv[0] << ": -h or --help for usage" << std::endl;
exit(1);
}
if (ceph_argparse_need_usage(args)) {
usage();
exit(0);
}
int flags = CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS;
// Prevent global_init() from dropping permissions until frontends can bind
// privileged ports
flags |= CINIT_FLAG_DEFER_DROP_PRIVILEGES;
auto cct = rgw_global_init(&defaults, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_DAEMON, flags);
DoutPrefix dp(cct.get(), dout_subsys, "rgw main: ");
rgw::AppMain main(&dp);
main.init_frontends1(false /* nfs */);
main.init_numa();
if (g_conf()->daemonize) {
global_init_daemonize(g_ceph_context);
}
ceph::mutex mutex = ceph::make_mutex("main");
SafeTimer init_timer(g_ceph_context, mutex);
init_timer.init();
mutex.lock();
init_timer.add_event_after(g_conf()->rgw_init_timeout, new C_InitTimeout);
mutex.unlock();
common_init_finish(g_ceph_context);
init_async_signal_handler();
/* XXXX check locations thru sighandler_alrm */
register_async_signal_handler(SIGHUP, rgw::signal::sighup_handler);
r = rgw::signal::signal_fd_init();
if (r < 0) {
derr << "ERROR: unable to initialize signal fds" << dendl;
exit(1);
}
register_async_signal_handler(SIGTERM, rgw::signal::handle_sigterm);
register_async_signal_handler(SIGINT, rgw::signal::handle_sigterm);
register_async_signal_handler(SIGUSR1, rgw::signal::handle_sigterm);
sighandler_alrm = signal(SIGALRM, godown_alarm);
main.init_perfcounters();
main.init_http_clients();
r = main.init_storage();
if (r < 0) {
mutex.lock();
init_timer.cancel_all_events();
init_timer.shutdown();
mutex.unlock();
derr << "Couldn't init storage provider (RADOS)" << dendl;
return -r;
}
main.cond_init_apis();
mutex.lock();
init_timer.cancel_all_events();
init_timer.shutdown();
mutex.unlock();
main.init_ldap();
main.init_opslog();
main.init_tracepoints();
main.init_lua();
main.init_frontends2(nullptr /* RGWLib */);
main.init_notification_endpoints();
#if defined(HAVE_SYS_PRCTL_H)
if (prctl(PR_SET_DUMPABLE, 1) == -1) {
cerr << "warning: unable to set dumpable flag: " << cpp_strerror(errno) << std::endl;
}
#endif
rgw::signal::wait_shutdown();
derr << "shutting down" << dendl;
const auto finalize_async_signals = []() {
unregister_async_signal_handler(SIGHUP, rgw::signal::sighup_handler);
unregister_async_signal_handler(SIGTERM, rgw::signal::handle_sigterm);
unregister_async_signal_handler(SIGINT, rgw::signal::handle_sigterm);
unregister_async_signal_handler(SIGUSR1, rgw::signal::handle_sigterm);
shutdown_async_signal_handler();
};
main.shutdown(finalize_async_signals);
dout(1) << "final shutdown" << dendl;
rgw::signal::signal_fd_finalize();
return 0;
} /* main(int argc, char* argv[]) */
| 5,292 | 27.005291 | 89 |
cc
|
null |
ceph-main/src/rgw/rgw_main.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2022 Red Hat, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <vector>
#include <map>
#include <string>
#include "rgw_common.h"
#include "rgw_rest.h"
#include "rgw_frontend.h"
#include "rgw_period_pusher.h"
#include "rgw_realm_reloader.h"
#include "rgw_ldap.h"
#include "rgw_lua.h"
#include "rgw_dmclock_scheduler_ctx.h"
#include "rgw_ratelimit.h"
class RGWPauser : public RGWRealmReloader::Pauser {
std::vector<Pauser*> pausers;
public:
~RGWPauser() override = default;
void add_pauser(Pauser* pauser) {
pausers.push_back(pauser);
}
void pause() override {
std::for_each(pausers.begin(), pausers.end(), [](Pauser* p){p->pause();});
}
void resume(rgw::sal::Driver* driver) override {
std::for_each(pausers.begin(), pausers.end(), [driver](Pauser* p){p->resume(driver);});
}
};
namespace rgw {
namespace lua { class Background; }
namespace sal { class ConfigStore; }
class RGWLib;
class AppMain {
/* several components should be initalized only if librgw is
* also serving HTTP */
bool have_http_frontend{false};
bool nfs{false};
std::vector<RGWFrontend*> fes;
std::vector<RGWFrontendConfig*> fe_configs;
std::multimap<string, RGWFrontendConfig*> fe_map;
std::unique_ptr<rgw::LDAPHelper> ldh;
OpsLogSink* olog = nullptr;
RGWREST rest;
std::unique_ptr<rgw::lua::Background> lua_background;
std::unique_ptr<rgw::auth::ImplicitTenants> implicit_tenant_context;
std::unique_ptr<rgw::dmclock::SchedulerCtx> sched_ctx;
std::unique_ptr<ActiveRateLimiter> ratelimiter;
std::map<std::string, std::string> service_map_meta;
// wow, realm reloader has a lot of parts
std::unique_ptr<RGWRealmReloader> reloader;
std::unique_ptr<RGWPeriodPusher> pusher;
std::unique_ptr<RGWFrontendPauser> fe_pauser;
std::unique_ptr<RGWRealmWatcher> realm_watcher;
std::unique_ptr<RGWPauser> rgw_pauser;
std::unique_ptr<sal::ConfigStore> cfgstore;
SiteConfig site;
const DoutPrefixProvider* dpp;
RGWProcessEnv env;
public:
AppMain(const DoutPrefixProvider* dpp);
~AppMain();
void shutdown(std::function<void(void)> finalize_async_signals
= []() { /* nada */});
sal::ConfigStore* get_config_store() const {
return cfgstore.get();
}
rgw::sal::Driver* get_driver() {
return env.driver;
}
rgw::LDAPHelper* get_ldh() {
return ldh.get();
}
void init_frontends1(bool nfs = false);
void init_numa();
int init_storage();
void init_perfcounters();
void init_http_clients();
void cond_init_apis();
void init_ldap();
void init_opslog();
int init_frontends2(RGWLib* rgwlib = nullptr);
void init_tracepoints();
void init_notification_endpoints();
void init_lua();
bool have_http() {
return have_http_frontend;
}
static OpsLogFile* ops_log_file;
}; /* AppMain */
} // namespace rgw
static inline RGWRESTMgr *set_logging(RGWRESTMgr* mgr)
{
mgr->set_logging(true);
return mgr;
}
static inline RGWRESTMgr *rest_filter(rgw::sal::Driver* driver, int dialect, RGWRESTMgr* orig)
{
RGWSyncModuleInstanceRef sync_module = driver->get_sync_module();
if (sync_module) {
return sync_module->get_rest_filter(dialect, orig);
} else {
return orig;
}
}
| 3,556 | 24.407143 | 94 |
h
|
null |
ceph-main/src/rgw/rgw_mdlog.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "common/RWLock.h"
#include "rgw_metadata.h"
#include "rgw_mdlog_types.h"
#include "services/svc_rados.h"
#define META_LOG_OBJ_PREFIX "meta.log."
struct RGWMetadataLogInfo {
std::string marker;
real_time last_update;
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
};
class RGWCompletionManager;
class RGWMetadataLogInfoCompletion : public RefCountedObject {
public:
using info_callback_t = std::function<void(int, const cls_log_header&)>;
private:
cls_log_header header;
RGWSI_RADOS::Obj io_obj;
librados::AioCompletion *completion;
std::mutex mutex; //< protects callback between cancel/complete
boost::optional<info_callback_t> callback; //< cleared on cancel
public:
explicit RGWMetadataLogInfoCompletion(info_callback_t callback);
~RGWMetadataLogInfoCompletion() override;
RGWSI_RADOS::Obj& get_io_obj() { return io_obj; }
cls_log_header& get_header() { return header; }
librados::AioCompletion* get_completion() { return completion; }
void finish(librados::completion_t cb) {
std::lock_guard<std::mutex> lock(mutex);
if (callback) {
(*callback)(completion->get_return_value(), header);
}
}
void cancel() {
std::lock_guard<std::mutex> lock(mutex);
callback = boost::none;
}
};
class RGWMetadataLog {
CephContext *cct;
const std::string prefix;
struct Svc {
RGWSI_Zone *zone{nullptr};
RGWSI_Cls *cls{nullptr};
} svc;
static std::string make_prefix(const std::string& period) {
if (period.empty())
return META_LOG_OBJ_PREFIX;
return META_LOG_OBJ_PREFIX + period + ".";
}
RWLock lock;
std::set<int> modified_shards;
void mark_modified(int shard_id);
public:
RGWMetadataLog(CephContext *_cct,
RGWSI_Zone *_zone_svc,
RGWSI_Cls *_cls_svc,
const std::string& period)
: cct(_cct),
prefix(make_prefix(period)),
lock("RGWMetaLog::lock") {
svc.zone = _zone_svc;
svc.cls = _cls_svc;
}
void get_shard_oid(int id, std::string& oid) const {
char buf[16];
snprintf(buf, sizeof(buf), "%d", id);
oid = prefix + buf;
}
int add_entry(const DoutPrefixProvider *dpp, const std::string& hash_key, const std::string& section, const std::string& key, bufferlist& bl);
int get_shard_id(const std::string& hash_key, int *shard_id);
int store_entries_in_shard(const DoutPrefixProvider *dpp, std::list<cls_log_entry>& entries, int shard_id, librados::AioCompletion *completion);
struct LogListCtx {
int cur_shard;
std::string marker;
real_time from_time;
real_time end_time;
std::string cur_oid;
bool done;
LogListCtx() : cur_shard(0), done(false) {}
};
void init_list_entries(int shard_id, const real_time& from_time,
const real_time& end_time, const std::string& marker,
void **handle);
void complete_list_entries(void *handle);
int list_entries(const DoutPrefixProvider *dpp,
void *handle,
int max_entries,
std::list<cls_log_entry>& entries,
std::string *out_marker,
bool *truncated);
int trim(const DoutPrefixProvider *dpp, int shard_id, const real_time& from_time, const real_time& end_time, const std::string& start_marker, const std::string& end_marker);
int get_info(const DoutPrefixProvider *dpp, int shard_id, RGWMetadataLogInfo *info);
int get_info_async(const DoutPrefixProvider *dpp, int shard_id, RGWMetadataLogInfoCompletion *completion);
int lock_exclusive(const DoutPrefixProvider *dpp, int shard_id, timespan duration, std::string&zone_id, std::string& owner_id);
int unlock(const DoutPrefixProvider *dpp, int shard_id, std::string& zone_id, std::string& owner_id);
int update_shards(std::list<int>& shards);
void read_clear_modified(std::set<int> &modified);
};
struct LogStatusDump {
RGWMDLogStatus status;
explicit LogStatusDump(RGWMDLogStatus _status) : status(_status) {}
void dump(Formatter *f) const;
};
struct RGWMetadataLogData {
obj_version read_version;
obj_version write_version;
RGWMDLogStatus status;
RGWMetadataLogData() : status(MDLOG_STATUS_UNKNOWN) {}
void encode(bufferlist& bl) const;
void decode(bufferlist::const_iterator& bl);
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<RGWMetadataLogData *>& l);
};
WRITE_CLASS_ENCODER(RGWMetadataLogData)
struct RGWMetadataLogHistory {
epoch_t oldest_realm_epoch;
std::string oldest_period_id;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(oldest_realm_epoch, bl);
encode(oldest_period_id, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& p) {
DECODE_START(1, p);
decode(oldest_realm_epoch, p);
decode(oldest_period_id, p);
DECODE_FINISH(p);
}
static const std::string oid;
};
WRITE_CLASS_ENCODER(RGWMetadataLogHistory)
| 5,365 | 27.695187 | 175 |
h
|
null |
ceph-main/src/rgw/rgw_mdlog_types.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
enum RGWMDLogSyncType {
APPLY_ALWAYS,
APPLY_UPDATES,
APPLY_NEWER,
APPLY_EXCLUSIVE
};
enum RGWMDLogStatus {
MDLOG_STATUS_UNKNOWN,
MDLOG_STATUS_WRITE,
MDLOG_STATUS_SETATTRS,
MDLOG_STATUS_REMOVE,
MDLOG_STATUS_COMPLETE,
MDLOG_STATUS_ABORT,
};
| 689 | 18.166667 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_meta_sync_status.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string>
#include "common/ceph_time.h"
struct rgw_meta_sync_info {
enum SyncState {
StateInit = 0,
StateBuildingFullSyncMaps = 1,
StateSync = 2,
};
uint16_t state;
uint32_t num_shards;
std::string period; //< period id of current metadata log
epoch_t realm_epoch = 0; //< realm epoch of period
void encode(bufferlist& bl) const {
ENCODE_START(2, 1, bl);
encode(state, bl);
encode(num_shards, bl);
encode(period, bl);
encode(realm_epoch, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(state, bl);
decode(num_shards, bl);
if (struct_v >= 2) {
decode(period, bl);
decode(realm_epoch, bl);
}
DECODE_FINISH(bl);
}
void decode_json(JSONObj *obj);
void dump(Formatter *f) const;
static void generate_test_instances(std::list<rgw_meta_sync_info*>& ls);
rgw_meta_sync_info() : state((int)StateInit), num_shards(0) {}
};
WRITE_CLASS_ENCODER(rgw_meta_sync_info)
struct rgw_meta_sync_marker {
enum SyncState {
FullSync = 0,
IncrementalSync = 1,
};
uint16_t state;
std::string marker;
std::string next_step_marker;
uint64_t total_entries;
uint64_t pos;
real_time timestamp;
epoch_t realm_epoch{0}; //< realm_epoch of period marker
rgw_meta_sync_marker() : state(FullSync), total_entries(0), pos(0) {}
void encode(bufferlist& bl) const {
ENCODE_START(2, 1, bl);
encode(state, bl);
encode(marker, bl);
encode(next_step_marker, bl);
encode(total_entries, bl);
encode(pos, bl);
encode(timestamp, bl);
encode(realm_epoch, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(state, bl);
decode(marker, bl);
decode(next_step_marker, bl);
decode(total_entries, bl);
decode(pos, bl);
decode(timestamp, bl);
if (struct_v >= 2) {
decode(realm_epoch, bl);
}
DECODE_FINISH(bl);
}
void decode_json(JSONObj *obj);
void dump(Formatter *f) const;
static void generate_test_instances(std::list<rgw_meta_sync_marker*>& ls);
};
WRITE_CLASS_ENCODER(rgw_meta_sync_marker)
struct rgw_meta_sync_status {
rgw_meta_sync_info sync_info;
std::map<uint32_t, rgw_meta_sync_marker> sync_markers;
rgw_meta_sync_status() {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(sync_info, bl);
encode(sync_markers, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(sync_info, bl);
decode(sync_markers, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<rgw_meta_sync_status*>& ls);
};
WRITE_CLASS_ENCODER(rgw_meta_sync_status)
| 2,955 | 23.229508 | 76 |
h
|
null |
ceph-main/src/rgw/rgw_metadata.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_metadata.h"
#include "rgw_mdlog.h"
#include "services/svc_meta.h"
#include "services/svc_meta_be_sobj.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
void LogStatusDump::dump(Formatter *f) const {
string s;
switch (status) {
case MDLOG_STATUS_WRITE:
s = "write";
break;
case MDLOG_STATUS_SETATTRS:
s = "set_attrs";
break;
case MDLOG_STATUS_REMOVE:
s = "remove";
break;
case MDLOG_STATUS_COMPLETE:
s = "complete";
break;
case MDLOG_STATUS_ABORT:
s = "abort";
break;
default:
s = "unknown";
break;
}
encode_json("status", s, f);
}
void encode_json(const char *name, const obj_version& v, Formatter *f)
{
f->open_object_section(name);
f->dump_string("tag", v.tag);
f->dump_unsigned("ver", v.ver);
f->close_section();
}
void decode_json_obj(obj_version& v, JSONObj *obj)
{
JSONDecoder::decode_json("tag", v.tag, obj);
JSONDecoder::decode_json("ver", v.ver, obj);
}
void RGWMetadataLogData::encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(read_version, bl);
encode(write_version, bl);
uint32_t s = (uint32_t)status;
encode(s, bl);
ENCODE_FINISH(bl);
}
void RGWMetadataLogData::decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(read_version, bl);
decode(write_version, bl);
uint32_t s;
decode(s, bl);
status = (RGWMDLogStatus)s;
DECODE_FINISH(bl);
}
void RGWMetadataLogData::dump(Formatter *f) const {
encode_json("read_version", read_version, f);
encode_json("write_version", write_version, f);
encode_json("status", LogStatusDump(status), f);
}
void decode_json_obj(RGWMDLogStatus& status, JSONObj *obj) {
string s;
JSONDecoder::decode_json("status", s, obj);
if (s == "complete") {
status = MDLOG_STATUS_COMPLETE;
} else if (s == "write") {
status = MDLOG_STATUS_WRITE;
} else if (s == "remove") {
status = MDLOG_STATUS_REMOVE;
} else if (s == "set_attrs") {
status = MDLOG_STATUS_SETATTRS;
} else if (s == "abort") {
status = MDLOG_STATUS_ABORT;
} else {
status = MDLOG_STATUS_UNKNOWN;
}
}
void RGWMetadataLogData::decode_json(JSONObj *obj) {
JSONDecoder::decode_json("read_version", read_version, obj);
JSONDecoder::decode_json("write_version", write_version, obj);
JSONDecoder::decode_json("status", status, obj);
}
void RGWMetadataLogData::generate_test_instances(std::list<RGWMetadataLogData *>& l) {
l.push_back(new RGWMetadataLogData{});
l.push_back(new RGWMetadataLogData);
l.back()->read_version = obj_version();
l.back()->read_version.tag = "read_tag";
l.back()->write_version = obj_version();
l.back()->write_version.tag = "write_tag";
l.back()->status = MDLOG_STATUS_WRITE;
}
RGWMetadataHandler_GenericMetaBE::Put::Put(RGWMetadataHandler_GenericMetaBE *_handler,
RGWSI_MetaBackend_Handler::Op *_op,
string& _entry, RGWMetadataObject *_obj,
RGWObjVersionTracker& _objv_tracker,
optional_yield _y,
RGWMDLogSyncType _type, bool _from_remote_zone):
handler(_handler), op(_op),
entry(_entry), obj(_obj),
objv_tracker(_objv_tracker),
apply_type(_type),
y(_y),
from_remote_zone(_from_remote_zone)
{
}
int RGWMetadataHandler_GenericMetaBE::do_put_operate(Put *put_op, const DoutPrefixProvider *dpp)
{
int r = put_op->put_pre(dpp);
if (r != 0) { /* r can also be STATUS_NO_APPLY */
return r;
}
r = put_op->put(dpp);
if (r != 0) {
return r;
}
r = put_op->put_post(dpp);
if (r != 0) { /* e.g., -error or STATUS_APPLIED */
return r;
}
return 0;
}
int RGWMetadataHandler_GenericMetaBE::get(string& entry, RGWMetadataObject **obj, optional_yield y, const DoutPrefixProvider *dpp)
{
return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) {
return do_get(op, entry, obj, y, dpp);
});
}
int RGWMetadataHandler_GenericMetaBE::put(string& entry, RGWMetadataObject *obj, RGWObjVersionTracker& objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp, RGWMDLogSyncType type, bool from_remote_zone)
{
return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) {
return do_put(op, entry, obj, objv_tracker, y, dpp, type, from_remote_zone);
});
}
int RGWMetadataHandler_GenericMetaBE::remove(string& entry, RGWObjVersionTracker& objv_tracker, optional_yield y, const DoutPrefixProvider *dpp)
{
return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) {
return do_remove(op, entry, objv_tracker, y, dpp);
});
}
int RGWMetadataHandler_GenericMetaBE::mutate(const string& entry,
const ceph::real_time& mtime,
RGWObjVersionTracker *objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp,
RGWMDLogStatus op_type,
std::function<int()> f)
{
return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) {
RGWSI_MetaBackend::MutateParams params(mtime, op_type);
return op->mutate(entry,
params,
objv_tracker,
y,
f,
dpp);
});
}
int RGWMetadataHandler_GenericMetaBE::get_shard_id(const string& entry, int *shard_id)
{
return be_handler->call([&](RGWSI_MetaBackend_Handler::Op *op) {
return op->get_shard_id(entry, shard_id);
});
}
int RGWMetadataHandler_GenericMetaBE::list_keys_init(const DoutPrefixProvider *dpp, const string& marker, void **phandle)
{
auto op = std::make_unique<RGWSI_MetaBackend_Handler::Op_ManagedCtx>(be_handler);
int ret = op->list_init(dpp, marker);
if (ret < 0) {
return ret;
}
*phandle = (void *)op.release();
return 0;
}
int RGWMetadataHandler_GenericMetaBE::list_keys_next(const DoutPrefixProvider *dpp, void *handle, int max, list<string>& keys, bool *truncated)
{
auto op = static_cast<RGWSI_MetaBackend_Handler::Op_ManagedCtx *>(handle);
int ret = op->list_next(dpp, max, &keys, truncated);
if (ret < 0 && ret != -ENOENT) {
return ret;
}
if (ret == -ENOENT) {
if (truncated) {
*truncated = false;
}
return 0;
}
return 0;
}
void RGWMetadataHandler_GenericMetaBE::list_keys_complete(void *handle)
{
auto op = static_cast<RGWSI_MetaBackend_Handler::Op_ManagedCtx *>(handle);
delete op;
}
string RGWMetadataHandler_GenericMetaBE::get_marker(void *handle)
{
auto op = static_cast<RGWSI_MetaBackend_Handler::Op_ManagedCtx *>(handle);
string marker;
int r = op->list_get_marker(&marker);
if (r < 0) {
ldout(cct, 0) << "ERROR: " << __func__ << "(): list_get_marker() returned: r=" << r << dendl;
/* not much else to do */
}
return marker;
}
RGWMetadataHandlerPut_SObj::RGWMetadataHandlerPut_SObj(RGWMetadataHandler_GenericMetaBE *handler,
RGWSI_MetaBackend_Handler::Op *op,
string& entry, RGWMetadataObject *obj, RGWObjVersionTracker& objv_tracker,
optional_yield y,
RGWMDLogSyncType type, bool from_remote_zone) : Put(handler, op, entry, obj, objv_tracker, y, type, from_remote_zone) {
}
int RGWMetadataHandlerPut_SObj::put_pre(const DoutPrefixProvider *dpp)
{
int ret = get(&old_obj, dpp);
if (ret < 0 && ret != -ENOENT) {
return ret;
}
exists = (ret != -ENOENT);
oo.reset(old_obj);
auto old_ver = (!old_obj ? obj_version() : old_obj->get_version());
auto old_mtime = (!old_obj ? ceph::real_time() : old_obj->get_mtime());
// are we actually going to perform this put, or is it too old?
if (!handler->check_versions(exists, old_ver, old_mtime,
objv_tracker.write_version, obj->get_mtime(),
apply_type)) {
return STATUS_NO_APPLY;
}
objv_tracker.read_version = old_ver; /* maintain the obj version we just read */
return 0;
}
int RGWMetadataHandlerPut_SObj::put(const DoutPrefixProvider *dpp)
{
int ret = put_check(dpp);
if (ret != 0) {
return ret;
}
return put_checked(dpp);
}
int RGWMetadataHandlerPut_SObj::put_checked(const DoutPrefixProvider *dpp)
{
RGWSI_MBSObj_PutParams params(obj->get_pattrs(), obj->get_mtime());
encode_obj(¶ms.bl);
int ret = op->put(entry, params, &objv_tracker, y, dpp);
if (ret < 0) {
return ret;
}
return 0;
}
class RGWMetadataTopHandler : public RGWMetadataHandler {
struct iter_data {
set<string> sections;
set<string>::iterator iter;
};
struct Svc {
RGWSI_Meta *meta{nullptr};
} svc;
RGWMetadataManager *mgr;
public:
RGWMetadataTopHandler(RGWSI_Meta *meta_svc,
RGWMetadataManager *_mgr) : mgr(_mgr) {
base_init(meta_svc->ctx());
svc.meta = meta_svc;
}
string get_type() override { return string(); }
RGWMetadataObject *get_meta_obj(JSONObj *jo, const obj_version& objv, const ceph::real_time& mtime) {
return new RGWMetadataObject;
}
int get(string& entry, RGWMetadataObject **obj, optional_yield y, const DoutPrefixProvider *dpp) override {
return -ENOTSUP;
}
int put(string& entry, RGWMetadataObject *obj, RGWObjVersionTracker& objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp, RGWMDLogSyncType type, bool from_remote_zone) override {
return -ENOTSUP;
}
int remove(string& entry, RGWObjVersionTracker& objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) override {
return -ENOTSUP;
}
int mutate(const string& entry,
const ceph::real_time& mtime,
RGWObjVersionTracker *objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp,
RGWMDLogStatus op_type,
std::function<int()> f) {
return -ENOTSUP;
}
int list_keys_init(const DoutPrefixProvider *dpp, const string& marker, void **phandle) override {
iter_data *data = new iter_data;
list<string> sections;
mgr->get_sections(sections);
for (auto& s : sections) {
data->sections.insert(s);
}
data->iter = data->sections.lower_bound(marker);
*phandle = data;
return 0;
}
int list_keys_next(const DoutPrefixProvider *dpp, void *handle, int max, list<string>& keys, bool *truncated) override {
iter_data *data = static_cast<iter_data *>(handle);
for (int i = 0; i < max && data->iter != data->sections.end(); ++i, ++(data->iter)) {
keys.push_back(*data->iter);
}
*truncated = (data->iter != data->sections.end());
return 0;
}
void list_keys_complete(void *handle) override {
iter_data *data = static_cast<iter_data *>(handle);
delete data;
}
virtual string get_marker(void *handle) override {
iter_data *data = static_cast<iter_data *>(handle);
if (data->iter != data->sections.end()) {
return *(data->iter);
}
return string();
}
};
RGWMetadataHandlerPut_SObj::~RGWMetadataHandlerPut_SObj() {}
int RGWMetadataHandler::attach(RGWMetadataManager *manager)
{
return manager->register_handler(this);
}
RGWMetadataHandler::~RGWMetadataHandler() {}
obj_version& RGWMetadataObject::get_version()
{
return objv;
}
RGWMetadataManager::RGWMetadataManager(RGWSI_Meta *_meta_svc)
: cct(_meta_svc->ctx()), meta_svc(_meta_svc)
{
md_top_handler.reset(new RGWMetadataTopHandler(meta_svc, this));
}
RGWMetadataManager::~RGWMetadataManager()
{
}
int RGWMetadataManager::register_handler(RGWMetadataHandler *handler)
{
string type = handler->get_type();
if (handlers.find(type) != handlers.end())
return -EEXIST;
handlers[type] = handler;
return 0;
}
RGWMetadataHandler *RGWMetadataManager::get_handler(const string& type)
{
map<string, RGWMetadataHandler *>::iterator iter = handlers.find(type);
if (iter == handlers.end())
return NULL;
return iter->second;
}
void RGWMetadataManager::parse_metadata_key(const string& metadata_key, string& type, string& entry)
{
auto pos = metadata_key.find(':');
if (pos == string::npos) {
type = metadata_key;
} else {
type = metadata_key.substr(0, pos);
entry = metadata_key.substr(pos + 1);
}
}
int RGWMetadataManager::find_handler(const string& metadata_key, RGWMetadataHandler **handler, string& entry)
{
string type;
parse_metadata_key(metadata_key, type, entry);
if (type.empty()) {
*handler = md_top_handler.get();
return 0;
}
map<string, RGWMetadataHandler *>::iterator iter = handlers.find(type);
if (iter == handlers.end())
return -ENOENT;
*handler = iter->second;
return 0;
}
int RGWMetadataManager::get(string& metadata_key, Formatter *f, optional_yield y, const DoutPrefixProvider *dpp)
{
RGWMetadataHandler *handler;
string entry;
int ret = find_handler(metadata_key, &handler, entry);
if (ret < 0) {
return ret;
}
RGWMetadataObject *obj;
ret = handler->get(entry, &obj, y, dpp);
if (ret < 0) {
return ret;
}
f->open_object_section("metadata_info");
encode_json("key", metadata_key, f);
encode_json("ver", obj->get_version(), f);
real_time mtime = obj->get_mtime();
if (!real_clock::is_zero(mtime)) {
utime_t ut(mtime);
encode_json("mtime", ut, f);
}
encode_json("data", *obj, f);
f->close_section();
delete obj;
return 0;
}
int RGWMetadataManager::put(string& metadata_key, bufferlist& bl,
optional_yield y,
const DoutPrefixProvider *dpp,
RGWMDLogSyncType sync_type,
bool from_remote_zone,
obj_version *existing_version)
{
RGWMetadataHandler *handler;
string entry;
int ret = find_handler(metadata_key, &handler, entry);
if (ret < 0) {
return ret;
}
JSONParser parser;
if (!parser.parse(bl.c_str(), bl.length())) {
return -EINVAL;
}
RGWObjVersionTracker objv_tracker;
obj_version *objv = &objv_tracker.write_version;
utime_t mtime;
try {
JSONDecoder::decode_json("key", metadata_key, &parser);
JSONDecoder::decode_json("ver", *objv, &parser);
JSONDecoder::decode_json("mtime", mtime, &parser);
} catch (JSONDecoder::err& e) {
return -EINVAL;
}
JSONObj *jo = parser.find_obj("data");
if (!jo) {
return -EINVAL;
}
RGWMetadataObject *obj = handler->get_meta_obj(jo, *objv, mtime.to_real_time());
if (!obj) {
return -EINVAL;
}
ret = handler->put(entry, obj, objv_tracker, y, dpp, sync_type, from_remote_zone);
if (existing_version) {
*existing_version = objv_tracker.read_version;
}
delete obj;
return ret;
}
int RGWMetadataManager::remove(string& metadata_key, optional_yield y, const DoutPrefixProvider *dpp)
{
RGWMetadataHandler *handler;
string entry;
int ret = find_handler(metadata_key, &handler, entry);
if (ret < 0) {
return ret;
}
RGWMetadataObject *obj;
ret = handler->get(entry, &obj, y, dpp);
if (ret < 0) {
return ret;
}
RGWObjVersionTracker objv_tracker;
objv_tracker.read_version = obj->get_version();
delete obj;
return handler->remove(entry, objv_tracker, y, dpp);
}
int RGWMetadataManager::mutate(const string& metadata_key,
const ceph::real_time& mtime,
RGWObjVersionTracker *objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp,
RGWMDLogStatus op_type,
std::function<int()> f)
{
RGWMetadataHandler *handler;
string entry;
int ret = find_handler(metadata_key, &handler, entry);
if (ret < 0) {
return ret;
}
return handler->mutate(entry, mtime, objv_tracker, y, dpp, op_type, f);
}
int RGWMetadataManager::get_shard_id(const string& section, const string& entry, int *shard_id)
{
RGWMetadataHandler *handler = get_handler(section);
if (!handler) {
return -EINVAL;
}
return handler->get_shard_id(entry, shard_id);
}
struct list_keys_handle {
void *handle;
RGWMetadataHandler *handler;
};
int RGWMetadataManager::list_keys_init(const DoutPrefixProvider *dpp, const string& section, void **handle)
{
return list_keys_init(dpp, section, string(), handle);
}
int RGWMetadataManager::list_keys_init(const DoutPrefixProvider *dpp, const string& section,
const string& marker, void **handle)
{
string entry;
RGWMetadataHandler *handler;
int ret;
ret = find_handler(section, &handler, entry);
if (ret < 0) {
return -ENOENT;
}
list_keys_handle *h = new list_keys_handle;
h->handler = handler;
ret = handler->list_keys_init(dpp, marker, &h->handle);
if (ret < 0) {
delete h;
return ret;
}
*handle = (void *)h;
return 0;
}
int RGWMetadataManager::list_keys_next(const DoutPrefixProvider *dpp, void *handle, int max, list<string>& keys, bool *truncated)
{
list_keys_handle *h = static_cast<list_keys_handle *>(handle);
RGWMetadataHandler *handler = h->handler;
return handler->list_keys_next(dpp, h->handle, max, keys, truncated);
}
void RGWMetadataManager::list_keys_complete(void *handle)
{
list_keys_handle *h = static_cast<list_keys_handle *>(handle);
RGWMetadataHandler *handler = h->handler;
handler->list_keys_complete(h->handle);
delete h;
}
string RGWMetadataManager::get_marker(void *handle)
{
list_keys_handle *h = static_cast<list_keys_handle *>(handle);
return h->handler->get_marker(h->handle);
}
void RGWMetadataManager::dump_log_entry(cls_log_entry& entry, Formatter *f)
{
f->open_object_section("entry");
f->dump_string("id", entry.id);
f->dump_string("section", entry.section);
f->dump_string("name", entry.name);
entry.timestamp.gmtime_nsec(f->dump_stream("timestamp"));
try {
RGWMetadataLogData log_data;
auto iter = entry.data.cbegin();
decode(log_data, iter);
encode_json("data", log_data, f);
} catch (buffer::error& err) {
lderr(cct) << "failed to decode log entry: " << entry.section << ":" << entry.name<< " ts=" << entry.timestamp << dendl;
}
f->close_section();
}
void RGWMetadataManager::get_sections(list<string>& sections)
{
for (map<string, RGWMetadataHandler *>::iterator iter = handlers.begin(); iter != handlers.end(); ++iter) {
sections.push_back(iter->first);
}
}
| 18,662 | 25.891931 | 174 |
cc
|
null |
ceph-main/src/rgw/rgw_multi.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "rgw_xml.h"
#include "rgw_multi.h"
#include "rgw_op.h"
#include "rgw_sal.h"
#include "rgw_sal_rados.h"
#include "services/svc_sys_obj.h"
#include "services/svc_tier_rados.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
bool RGWMultiPart::xml_end(const char *el)
{
RGWMultiPartNumber *num_obj = static_cast<RGWMultiPartNumber *>(find_first("PartNumber"));
RGWMultiETag *etag_obj = static_cast<RGWMultiETag *>(find_first("ETag"));
if (!num_obj || !etag_obj)
return false;
string s = num_obj->get_data();
if (s.empty())
return false;
num = atoi(s.c_str());
s = etag_obj->get_data();
etag = s;
return true;
}
bool RGWMultiCompleteUpload::xml_end(const char *el) {
XMLObjIter iter = find("Part");
RGWMultiPart *part = static_cast<RGWMultiPart *>(iter.get_next());
while (part) {
int num = part->get_num();
string etag = part->get_etag();
parts[num] = etag;
part = static_cast<RGWMultiPart *>(iter.get_next());
}
return true;
}
RGWMultiXMLParser::~RGWMultiXMLParser() {}
XMLObj *RGWMultiXMLParser::alloc_obj(const char *el) {
XMLObj *obj = NULL;
// CompletedMultipartUpload is incorrect but some versions of some libraries use it, see PR #41700
if (strcmp(el, "CompleteMultipartUpload") == 0 ||
strcmp(el, "CompletedMultipartUpload") == 0 ||
strcmp(el, "MultipartUpload") == 0) {
obj = new RGWMultiCompleteUpload();
} else if (strcmp(el, "Part") == 0) {
obj = new RGWMultiPart();
} else if (strcmp(el, "PartNumber") == 0) {
obj = new RGWMultiPartNumber();
} else if (strcmp(el, "ETag") == 0) {
obj = new RGWMultiETag();
}
return obj;
}
bool is_v2_upload_id(const string& upload_id)
{
const char *uid = upload_id.c_str();
return (strncmp(uid, MULTIPART_UPLOAD_ID_PREFIX, sizeof(MULTIPART_UPLOAD_ID_PREFIX) - 1) == 0) ||
(strncmp(uid, MULTIPART_UPLOAD_ID_PREFIX_LEGACY, sizeof(MULTIPART_UPLOAD_ID_PREFIX_LEGACY) - 1) == 0);
}
void RGWUploadPartInfo::generate_test_instances(list<RGWUploadPartInfo*>& o)
{
RGWUploadPartInfo *i = new RGWUploadPartInfo;
i->num = 1;
i->size = 10 * 1024 * 1024;
i->etag = "etag";
o.push_back(i);
o.push_back(new RGWUploadPartInfo);
}
void RGWUploadPartInfo::dump(Formatter *f) const
{
encode_json("num", num, f);
encode_json("size", size, f);
encode_json("etag", etag, f);
utime_t ut(modified);
encode_json("modified", ut, f);
encode_json("past_prefixes", past_prefixes, f);
}
| 2,661 | 24.596154 | 111 |
cc
|
null |
ceph-main/src/rgw/rgw_multi.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include "rgw_xml.h"
#include "rgw_obj_types.h"
#include "rgw_obj_manifest.h"
#include "rgw_compression_types.h"
#include "common/dout.h"
#include "rgw_sal_fwd.h"
#define MULTIPART_UPLOAD_ID_PREFIX_LEGACY "2/"
#define MULTIPART_UPLOAD_ID_PREFIX "2~" // must contain a unique char that may not come up in gen_rand_alpha()
class RGWMultiCompleteUpload : public XMLObj
{
public:
RGWMultiCompleteUpload() {}
~RGWMultiCompleteUpload() override {}
bool xml_end(const char *el) override;
std::map<int, std::string> parts;
};
class RGWMultiPart : public XMLObj
{
std::string etag;
int num;
public:
RGWMultiPart() : num(0) {}
~RGWMultiPart() override {}
bool xml_end(const char *el) override;
std::string& get_etag() { return etag; }
int get_num() { return num; }
};
class RGWMultiPartNumber : public XMLObj
{
public:
RGWMultiPartNumber() {}
~RGWMultiPartNumber() override {}
};
class RGWMultiETag : public XMLObj
{
public:
RGWMultiETag() {}
~RGWMultiETag() override {}
};
class RGWMultiXMLParser : public RGWXMLParser
{
XMLObj *alloc_obj(const char *el) override;
public:
RGWMultiXMLParser() {}
virtual ~RGWMultiXMLParser() override;
};
extern bool is_v2_upload_id(const std::string& upload_id);
| 1,368 | 20.730159 | 110 |
h
|
null |
ceph-main/src/rgw/rgw_multi_del.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include "include/types.h"
#include "rgw_xml.h"
#include "rgw_multi_del.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
bool RGWMultiDelObject::xml_end(const char *el)
{
RGWMultiDelKey *key_obj = static_cast<RGWMultiDelKey *>(find_first("Key"));
RGWMultiDelVersionId *vid = static_cast<RGWMultiDelVersionId *>(find_first("VersionId"));
if (!key_obj)
return false;
string s = key_obj->get_data();
if (s.empty())
return false;
key = s;
if (vid) {
version_id = vid->get_data();
}
return true;
}
bool RGWMultiDelDelete::xml_end(const char *el) {
RGWMultiDelQuiet *quiet_set = static_cast<RGWMultiDelQuiet *>(find_first("Quiet"));
if (quiet_set) {
string quiet_val = quiet_set->get_data();
quiet = (strcasecmp(quiet_val.c_str(), "true") == 0);
}
XMLObjIter iter = find("Object");
RGWMultiDelObject *object = static_cast<RGWMultiDelObject *>(iter.get_next());
while (object) {
const string& key = object->get_key();
const string& instance = object->get_version_id();
rgw_obj_key k(key, instance);
objects.push_back(k);
object = static_cast<RGWMultiDelObject *>(iter.get_next());
}
return true;
}
XMLObj *RGWMultiDelXMLParser::alloc_obj(const char *el) {
XMLObj *obj = NULL;
if (strcmp(el, "Delete") == 0) {
obj = new RGWMultiDelDelete();
} else if (strcmp(el, "Quiet") == 0) {
obj = new RGWMultiDelQuiet();
} else if (strcmp(el, "Object") == 0) {
obj = new RGWMultiDelObject ();
} else if (strcmp(el, "Key") == 0) {
obj = new RGWMultiDelKey();
} else if (strcmp(el, "VersionId") == 0) {
obj = new RGWMultiDelVersionId();
}
return obj;
}
| 1,815 | 23.540541 | 91 |
cc
|
null |
ceph-main/src/rgw/rgw_multi_del.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <vector>
#include "rgw_xml.h"
#include "rgw_common.h"
class RGWMultiDelDelete : public XMLObj
{
public:
RGWMultiDelDelete() :quiet(false) {}
~RGWMultiDelDelete() override {}
bool xml_end(const char *el) override;
std::vector<rgw_obj_key> objects;
bool quiet;
bool is_quiet() { return quiet; }
};
class RGWMultiDelQuiet : public XMLObj
{
public:
RGWMultiDelQuiet() {}
~RGWMultiDelQuiet() override {}
};
class RGWMultiDelObject : public XMLObj
{
std::string key;
std::string version_id;
public:
RGWMultiDelObject() {}
~RGWMultiDelObject() override {}
bool xml_end(const char *el) override;
const std::string& get_key() { return key; }
const std::string& get_version_id() { return version_id; }
};
class RGWMultiDelKey : public XMLObj
{
public:
RGWMultiDelKey() {}
~RGWMultiDelKey() override {}
};
class RGWMultiDelVersionId : public XMLObj
{
public:
RGWMultiDelVersionId() {}
~RGWMultiDelVersionId() override {}
};
class RGWMultiDelXMLParser : public RGWXMLParser
{
XMLObj *alloc_obj(const char *el) override;
public:
RGWMultiDelXMLParser() {}
~RGWMultiDelXMLParser() override {}
};
| 1,262 | 19.047619 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_multiparser.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "rgw_multi.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
int main(int argc, char **argv) {
RGWMultiXMLParser parser;
if (!parser.init())
exit(1);
char buf[1024];
for (;;) {
int done;
int len;
len = fread(buf, 1, sizeof(buf), stdin);
if (ferror(stdin)) {
fprintf(stderr, "Read error\n");
exit(-1);
}
done = feof(stdin);
bool result = parser.parse(buf, len, done);
if (!result) {
cerr << "failed to parse!" << std::endl;
}
if (done)
break;
}
exit(0);
}
| 756 | 14.770833 | 70 |
cc
|
null |
ceph-main/src/rgw/rgw_multipart_meta_filter.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "svc_tier_rados.h"
using namespace std;
const std::string MP_META_SUFFIX = ".meta";
bool MultipartMetaFilter::filter(const string& name, string& key) {
// the length of the suffix so we can skip past it
static const size_t MP_META_SUFFIX_LEN = MP_META_SUFFIX.length();
size_t len = name.size();
// make sure there's room for suffix plus at least one more
// character
if (len <= MP_META_SUFFIX_LEN)
return false;
size_t pos = name.find(MP_META_SUFFIX, len - MP_META_SUFFIX_LEN);
if (pos == string::npos)
return false;
pos = name.rfind('.', pos - 1);
if (pos == string::npos)
return false;
key = name.substr(0, pos);
return true;
}
| 791 | 23 | 70 |
cc
|
null |
ceph-main/src/rgw/rgw_notify_event_type.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "rgw_notify_event_type.h"
#include "include/str_list.h"
namespace rgw::notify {
std::string to_string(EventType t) {
switch (t) {
case ObjectCreated:
return "s3:ObjectCreated:*";
case ObjectCreatedPut:
return "s3:ObjectCreated:Put";
case ObjectCreatedPost:
return "s3:ObjectCreated:Post";
case ObjectCreatedCopy:
return "s3:ObjectCreated:Copy";
case ObjectCreatedCompleteMultipartUpload:
return "s3:ObjectCreated:CompleteMultipartUpload";
case ObjectRemoved:
return "s3:ObjectRemoved:*";
case ObjectRemovedDelete:
return "s3:ObjectRemoved:Delete";
case ObjectRemovedDeleteMarkerCreated:
return "s3:ObjectRemoved:DeleteMarkerCreated";
case ObjectLifecycle:
return "s3:ObjectLifecycle:*";
case ObjectExpiration:
return "s3:ObjectLifecycle:Expiration:*";
case ObjectExpirationCurrent:
return "s3:ObjectLifecycle:Expiration:Current";
case ObjectExpirationNoncurrent:
return "s3:ObjectLifecycle:Expiration:Noncurrent";
case ObjectExpirationDeleteMarker:
return "s3:ObjectLifecycle:Expiration:DeleteMarker";
case ObjectExpirationAbortMPU:
return "s3:ObjectLifecycle:Expiration:AbortMPU";
case ObjectTransition:
return "s3:ObjectLifecycle:Transition:*";
case ObjectTransitionCurrent:
return "s3:ObjectLifecycle:Transition:Current";
case ObjectTransitionNoncurrent:
return "s3:ObjectLifecycle:Transition:Noncurrent";
case ObjectSynced:
return "s3:ObjectSynced:*";
case ObjectSyncedCreate:
return "s3:ObjectSynced:Create";
case ObjectSyncedDelete:
return "s3:ObjectSynced:Delete";
case ObjectSyncedDeletionMarkerCreated:
return "s3:ObjectSynced:DeletionMarkerCreated";
case UnknownEvent:
return "s3:UnknownEvent";
}
return "s3:UnknownEvent";
}
std::string to_event_string(EventType t) {
return to_string(t).substr(3);
}
EventType from_string(const std::string& s) {
if (s == "s3:ObjectCreated:*")
return ObjectCreated;
if (s == "s3:ObjectCreated:Put")
return ObjectCreatedPut;
if (s == "s3:ObjectCreated:Post")
return ObjectCreatedPost;
if (s == "s3:ObjectCreated:Copy")
return ObjectCreatedCopy;
if (s == "s3:ObjectCreated:CompleteMultipartUpload")
return ObjectCreatedCompleteMultipartUpload;
if (s == "s3:ObjectRemoved:*")
return ObjectRemoved;
if (s == "s3:ObjectRemoved:Delete")
return ObjectRemovedDelete;
if (s == "s3:ObjectRemoved:DeleteMarkerCreated")
return ObjectRemovedDeleteMarkerCreated;
if (s == "s3:ObjectLifecycle:*")
return ObjectLifecycle;
if (s == "s3:ObjectLifecycle:Expiration:*")
return ObjectExpiration;
if (s == "s3:ObjectLifecycle:Expiration:Current")
return ObjectExpirationCurrent;
if (s == "s3:ObjectLifecycle:Expiration:Noncurrent")
return ObjectExpirationNoncurrent;
if (s == "s3:ObjectLifecycle:Expiration:DeleteMarker")
return ObjectExpirationDeleteMarker;
if (s == "s3:ObjectLifecycle:Expiration:AbortMultipartUpload")
return ObjectExpirationAbortMPU;
if (s == "s3:ObjectLifecycle:Transition:*")
return ObjectTransition;
if (s == "s3:ObjectLifecycle:Transition:Current")
return ObjectTransitionCurrent;
if (s == "s3:ObjectLifecycle:Transition:Noncurrent")
return ObjectTransitionNoncurrent;
if (s == "s3:ObjectSynced:*")
return ObjectSynced;
if (s == "s3:ObjectSynced:Create")
return ObjectSyncedCreate;
if (s == "s3:ObjectSynced:Delete")
return ObjectSyncedDelete;
if (s == "s3:ObjectSynced:DeletionMarkerCreated")
return ObjectSyncedDeletionMarkerCreated;
return UnknownEvent;
}
bool operator==(EventType lhs, EventType rhs) {
return lhs & rhs;
}
void from_string_list(const std::string& string_list, EventTypeList& event_list) {
event_list.clear();
ceph::for_each_substr(string_list, ",", [&event_list] (auto token) {
event_list.push_back(rgw::notify::from_string(std::string(token.begin(), token.end())));
});
}
}
| 4,276 | 34.641667 | 92 |
cc
|
null |
ceph-main/src/rgw/rgw_notify_event_type.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <string>
#include <vector>
namespace rgw::notify {
enum EventType {
ObjectCreated = 0xF,
ObjectCreatedPut = 0x1,
ObjectCreatedPost = 0x2,
ObjectCreatedCopy = 0x4,
ObjectCreatedCompleteMultipartUpload = 0x8,
ObjectRemoved = 0xF0,
ObjectRemovedDelete = 0x10,
ObjectRemovedDeleteMarkerCreated = 0x20,
// lifecycle events (RGW extension)
ObjectLifecycle = 0xFF00,
ObjectExpiration = 0xF00,
ObjectExpirationCurrent = 0x100,
ObjectExpirationNoncurrent = 0x200,
ObjectExpirationDeleteMarker = 0x400,
ObjectExpirationAbortMPU = 0x800,
ObjectTransition = 0xF000,
ObjectTransitionCurrent = 0x1000,
ObjectTransitionNoncurrent = 0x2000,
ObjectSynced = 0xF0000,
ObjectSyncedCreate = 0x10000,
ObjectSyncedDelete = 0x20000,
ObjectSyncedDeletionMarkerCreated = 0x40000,
UnknownEvent = 0x100000
};
using EventTypeList = std::vector<EventType>;
// two event types are considered equal if their bits intersect
bool operator==(EventType lhs, EventType rhs);
std::string to_string(EventType t);
std::string to_event_string(EventType t);
EventType from_string(const std::string& s);
// create a vector of event types from comma separated list of event types
void from_string_list(const std::string& string_list, EventTypeList& event_list);
}
| 1,803 | 35.08 | 83 |
h
|
null |
ceph-main/src/rgw/rgw_obj_manifest.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_obj_manifest.h"
#include "rgw_rados.h" // RGW_OBJ_NS_SHADOW and RGW_OBJ_NS_MULTIPART
using namespace std;
void RGWObjManifest::obj_iterator::operator++()
{
if (manifest->explicit_objs) {
++explicit_iter;
if (explicit_iter == manifest->objs.end()) {
ofs = manifest->obj_size;
stripe_size = 0;
return;
}
update_explicit_pos();
update_location();
return;
}
uint64_t obj_size = manifest->get_obj_size();
uint64_t head_size = manifest->get_head_size();
if (ofs == obj_size) {
return;
}
if (manifest->rules.empty()) {
return;
}
/* are we still pointing at the head? */
if (ofs < head_size) {
rule_iter = manifest->rules.begin();
const RGWObjManifestRule *rule = &rule_iter->second;
ofs = std::min(head_size, obj_size);
stripe_ofs = ofs;
cur_stripe = 1;
stripe_size = std::min(obj_size - ofs, rule->stripe_max_size);
if (rule->part_size > 0) {
stripe_size = std::min(stripe_size, rule->part_size);
}
update_location();
return;
}
const RGWObjManifestRule *rule = &rule_iter->second;
stripe_ofs += rule->stripe_max_size;
cur_stripe++;
ldpp_dout(dpp, 20) << "RGWObjManifest::operator++(): rule->part_size=" << rule->part_size << " rules.size()=" << manifest->rules.size() << dendl;
if (rule->part_size > 0) {
/* multi part, multi stripes object */
ldpp_dout(dpp, 20) << "RGWObjManifest::operator++(): stripe_ofs=" << stripe_ofs << " part_ofs=" << part_ofs << " rule->part_size=" << rule->part_size << dendl;
if (stripe_ofs >= part_ofs + rule->part_size) {
/* moved to the next part */
cur_stripe = 0;
part_ofs += rule->part_size;
stripe_ofs = part_ofs;
bool last_rule = (next_rule_iter == manifest->rules.end());
/* move to the next rule? */
if (!last_rule && stripe_ofs >= next_rule_iter->second.start_ofs) {
rule_iter = next_rule_iter;
last_rule = (next_rule_iter == manifest->rules.end());
if (!last_rule) {
++next_rule_iter;
}
cur_part_id = rule_iter->second.start_part_num;
} else {
cur_part_id++;
}
rule = &rule_iter->second;
}
stripe_size = std::min(rule->part_size - (stripe_ofs - part_ofs), rule->stripe_max_size);
}
cur_override_prefix = rule->override_prefix;
ofs = stripe_ofs;
if (ofs > obj_size) {
ofs = obj_size;
stripe_ofs = ofs;
stripe_size = 0;
}
ldpp_dout(dpp, 20) << "RGWObjManifest::operator++(): result: ofs=" << ofs << " stripe_ofs=" << stripe_ofs << " part_ofs=" << part_ofs << " rule->part_size=" << rule->part_size << dendl;
update_location();
}
void RGWObjManifest::obj_iterator::seek(uint64_t o)
{
ofs = o;
if (manifest->explicit_objs) {
explicit_iter = manifest->objs.upper_bound(ofs);
if (explicit_iter != manifest->objs.begin()) {
--explicit_iter;
}
if (ofs < manifest->obj_size) {
update_explicit_pos();
} else {
ofs = manifest->obj_size;
}
update_location();
return;
}
if (o < manifest->get_head_size()) {
rule_iter = manifest->rules.begin();
stripe_ofs = 0;
stripe_size = manifest->get_head_size();
if (rule_iter != manifest->rules.end()) {
cur_part_id = rule_iter->second.start_part_num;
cur_override_prefix = rule_iter->second.override_prefix;
}
update_location();
return;
}
rule_iter = manifest->rules.upper_bound(ofs);
next_rule_iter = rule_iter;
if (rule_iter != manifest->rules.begin()) {
--rule_iter;
}
if (rule_iter == manifest->rules.end()) {
update_location();
return;
}
const RGWObjManifestRule& rule = rule_iter->second;
if (rule.part_size > 0) {
cur_part_id = rule.start_part_num + (ofs - rule.start_ofs) / rule.part_size;
} else {
cur_part_id = rule.start_part_num;
}
part_ofs = rule.start_ofs + (cur_part_id - rule.start_part_num) * rule.part_size;
if (rule.stripe_max_size > 0) {
cur_stripe = (ofs - part_ofs) / rule.stripe_max_size;
stripe_ofs = part_ofs + cur_stripe * rule.stripe_max_size;
if (!cur_part_id && manifest->get_head_size() > 0) {
cur_stripe++;
}
} else {
cur_stripe = 0;
stripe_ofs = part_ofs;
}
if (!rule.part_size) {
stripe_size = rule.stripe_max_size;
stripe_size = std::min(manifest->get_obj_size() - stripe_ofs, stripe_size);
} else {
uint64_t next = std::min(stripe_ofs + rule.stripe_max_size, part_ofs + rule.part_size);
stripe_size = next - stripe_ofs;
}
cur_override_prefix = rule.override_prefix;
update_location();
}
void RGWObjManifest::obj_iterator::update_explicit_pos()
{
ofs = explicit_iter->first;
stripe_ofs = ofs;
auto next_iter = explicit_iter;
++next_iter;
if (next_iter != manifest->objs.end()) {
stripe_size = next_iter->first - ofs;
} else {
stripe_size = manifest->obj_size - ofs;
}
}
void RGWObjManifest::obj_iterator::update_location()
{
if (manifest->explicit_objs) {
if (manifest->empty()) {
location = rgw_obj_select{};
} else {
location = explicit_iter->second.loc;
}
return;
}
if (ofs < manifest->get_head_size()) {
location = manifest->get_obj();
location.set_placement_rule(manifest->get_head_placement_rule());
return;
}
manifest->get_implicit_location(cur_part_id, cur_stripe, ofs, &cur_override_prefix, &location);
}
void RGWObjManifest::get_implicit_location(uint64_t cur_part_id, uint64_t cur_stripe,
uint64_t ofs, string *override_prefix, rgw_obj_select *location) const
{
rgw_obj loc;
string& oid = loc.key.name;
string& ns = loc.key.ns;
if (!override_prefix || override_prefix->empty()) {
oid = prefix;
} else {
oid = *override_prefix;
}
if (!cur_part_id) {
if (ofs < max_head_size) {
location->set_placement_rule(head_placement_rule);
*location = obj;
return;
} else {
char buf[16];
snprintf(buf, sizeof(buf), "%d", (int)cur_stripe);
oid += buf;
ns = RGW_OBJ_NS_SHADOW;
}
} else {
char buf[32];
if (cur_stripe == 0) {
snprintf(buf, sizeof(buf), ".%d", (int)cur_part_id);
oid += buf;
ns= RGW_OBJ_NS_MULTIPART;
} else {
snprintf(buf, sizeof(buf), ".%d_%d", (int)cur_part_id, (int)cur_stripe);
oid += buf;
ns = RGW_OBJ_NS_SHADOW;
}
}
if (!tail_placement.bucket.name.empty()) {
loc.bucket = tail_placement.bucket;
} else {
loc.bucket = obj.bucket;
}
// Always overwrite instance with tail_instance
// to get the right shadow object location
loc.key.set_instance(tail_instance);
location->set_placement_rule(tail_placement.placement_rule);
*location = loc;
}
| 6,883 | 25.375479 | 187 |
cc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.