repo
stringlengths 1
152
⌀ | file
stringlengths 15
205
| code
stringlengths 0
41.6M
| file_length
int64 0
41.6M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 90
values |
---|---|---|---|---|---|---|
null |
ceph-main/src/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
|
null |
ceph-main/src/rgw/rgw_obj_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.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* include files which can only be compiled in radosgw or OSD
* contexts (e.g., rgw_sal.h, rgw_common.h) */
#pragma once
#include <fmt/format.h>
#include "rgw_pool_types.h"
#include "rgw_bucket_types.h"
#include "rgw_user_types.h"
#include "common/dout.h"
#include "common/Formatter.h"
struct rgw_obj_index_key { // cls_rgw_obj_key now aliases this type
std::string name;
std::string instance;
rgw_obj_index_key() {}
rgw_obj_index_key(const std::string &_name) : name(_name) {}
rgw_obj_index_key(const std::string& n, const std::string& i) : name(n), instance(i) {}
std::string to_string() const {
return fmt::format("{}({})", name, instance);
}
bool empty() const {
return name.empty();
}
void set(const std::string& _name) {
name = _name;
instance.clear();
}
bool operator==(const rgw_obj_index_key& k) const {
return (name.compare(k.name) == 0) &&
(instance.compare(k.instance) == 0);
}
bool operator!=(const rgw_obj_index_key& k) const {
return (name.compare(k.name) != 0) ||
(instance.compare(k.instance) != 0);
}
bool operator<(const rgw_obj_index_key& k) const {
int r = name.compare(k.name);
if (r == 0) {
r = instance.compare(k.instance);
}
return (r < 0);
}
bool operator<=(const rgw_obj_index_key& k) const {
return !(k < *this);
}
void encode(ceph::buffer::list &bl) const {
ENCODE_START(1, 1, bl);
encode(name, bl);
encode(instance, bl);
ENCODE_FINISH(bl);
}
void decode(ceph::buffer::list::const_iterator &bl) {
DECODE_START(1, bl);
decode(name, bl);
decode(instance, bl);
DECODE_FINISH(bl);
}
void dump(ceph::Formatter *f) const {
f->dump_string("name", name);
f->dump_string("instance", instance);
}
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<rgw_obj_index_key*>& ls) {
ls.push_back(new rgw_obj_index_key);
ls.push_back(new rgw_obj_index_key);
ls.back()->name = "name";
ls.back()->instance = "instance";
}
size_t estimate_encoded_size() const {
constexpr size_t start_overhead = sizeof(__u8) + sizeof(__u8) + sizeof(ceph_le32); // version and length prefix
constexpr size_t string_overhead = sizeof(__u32); // strings are encoded with 32-bit length prefix
return start_overhead +
string_overhead + name.size() +
string_overhead + instance.size();
}
};
WRITE_CLASS_ENCODER(rgw_obj_index_key)
struct rgw_obj_key {
std::string name;
std::string instance;
std::string ns;
rgw_obj_key() {}
// cppcheck-suppress noExplicitConstructor
rgw_obj_key(const std::string& n) : name(n) {}
rgw_obj_key(const std::string& n, const std::string& i) : name(n), instance(i) {}
rgw_obj_key(const std::string& n, const std::string& i, const std::string& _ns) : name(n), instance(i), ns(_ns) {}
rgw_obj_key(const rgw_obj_index_key& k) {
parse_index_key(k.name, &name, &ns);
instance = k.instance;
}
static void parse_index_key(const std::string& key, std::string *name, std::string *ns) {
if (key[0] != '_') {
*name = key;
ns->clear();
return;
}
if (key[1] == '_') {
*name = key.substr(1);
ns->clear();
return;
}
ssize_t pos = key.find('_', 1);
if (pos < 0) {
/* shouldn't happen, just use key */
*name = key;
ns->clear();
return;
}
*name = key.substr(pos + 1);
*ns = key.substr(1, pos -1);
}
void set(const std::string& n) {
name = n;
instance.clear();
ns.clear();
}
void set(const std::string& n, const std::string& i) {
name = n;
instance = i;
ns.clear();
}
void set(const std::string& n, const std::string& i, const std::string& _ns) {
name = n;
instance = i;
ns = _ns;
}
bool set(const rgw_obj_index_key& index_key) {
if (!parse_raw_oid(index_key.name, this)) {
return false;
}
instance = index_key.instance;
return true;
}
void set_instance(const std::string& i) {
instance = i;
}
const std::string& get_instance() const {
return instance;
}
void set_ns(const std::string& _ns) {
ns = _ns;
}
const std::string& get_ns() const {
return ns;
}
std::string get_index_key_name() const {
if (ns.empty()) {
if (name.size() < 1 || name[0] != '_') {
return name;
}
return std::string("_") + name;
};
char buf[ns.size() + 16];
snprintf(buf, sizeof(buf), "_%s_", ns.c_str());
return std::string(buf) + name;
};
void get_index_key(rgw_obj_index_key* key) const {
key->name = get_index_key_name();
key->instance = instance;
}
std::string get_loc() const {
/*
* For backward compatibility. Older versions used to have object locator on all objects,
* however, the name was the effective object locator. This had the same effect as not
* having object locator at all for most objects but the ones that started with underscore as
* these were escaped.
*/
if (name[0] == '_' && ns.empty()) {
return name;
}
return {};
}
bool empty() const {
return name.empty();
}
bool have_null_instance() const {
return instance == "null";
}
bool have_instance() const {
return !instance.empty();
}
bool need_to_encode_instance() const {
return have_instance() && !have_null_instance();
}
std::string get_oid() const {
if (ns.empty() && !need_to_encode_instance()) {
if (name.size() < 1 || name[0] != '_') {
return name;
}
return std::string("_") + name;
}
std::string oid = "_";
oid.append(ns);
if (need_to_encode_instance()) {
oid.append(std::string(":") + instance);
}
oid.append("_");
oid.append(name);
return oid;
}
bool operator==(const rgw_obj_key& k) const {
return (name.compare(k.name) == 0) &&
(instance.compare(k.instance) == 0);
}
bool operator<(const rgw_obj_key& k) const {
int r = name.compare(k.name);
if (r == 0) {
r = instance.compare(k.instance);
}
return (r < 0);
}
bool operator<=(const rgw_obj_key& k) const {
return !(k < *this);
}
static void parse_ns_field(std::string& ns, std::string& instance) {
int pos = ns.find(':');
if (pos >= 0) {
instance = ns.substr(pos + 1);
ns = ns.substr(0, pos);
} else {
instance.clear();
}
}
// takes an oid and parses out the namespace (ns), name, and
// instance
static bool parse_raw_oid(const std::string& oid, rgw_obj_key *key) {
key->instance.clear();
key->ns.clear();
if (oid[0] != '_') {
key->name = oid;
return true;
}
if (oid.size() >= 2 && oid[1] == '_') {
key->name = oid.substr(1);
return true;
}
if (oid.size() < 3) // for namespace, min size would be 3: _x_
return false;
size_t pos = oid.find('_', 2); // oid must match ^_[^_].+$
if (pos == std::string::npos)
return false;
key->ns = oid.substr(1, pos - 1);
parse_ns_field(key->ns, key->instance);
key->name = oid.substr(pos + 1);
return true;
}
/**
* Translate a namespace-mangled object name to the user-facing name
* existing in the given namespace.
*
* If the object is part of the given namespace, it returns true
* and cuts down the name to the unmangled version. If it is not
* part of the given namespace, it returns false.
*/
static bool oid_to_key_in_ns(const std::string& oid, rgw_obj_key *key, const std::string& ns) {
bool ret = parse_raw_oid(oid, key);
if (!ret) {
return ret;
}
return (ns == key->ns);
}
/**
* Given a mangled object name and an empty namespace std::string, this
* function extracts the namespace into the std::string and sets the object
* name to be the unmangled version.
*
* It returns true after successfully doing so, or
* false if it fails.
*/
static bool strip_namespace_from_name(std::string& name, std::string& ns, std::string& instance) {
ns.clear();
instance.clear();
if (name[0] != '_') {
return true;
}
size_t pos = name.find('_', 1);
if (pos == std::string::npos) {
return false;
}
if (name[1] == '_') {
name = name.substr(1);
return true;
}
size_t period_pos = name.find('.');
if (period_pos < pos) {
return false;
}
ns = name.substr(1, pos-1);
name = name.substr(pos+1, std::string::npos);
parse_ns_field(ns, instance);
return true;
}
void encode(bufferlist& bl) const {
ENCODE_START(2, 1, bl);
encode(name, bl);
encode(instance, bl);
encode(ns, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(name, bl);
decode(instance, bl);
if (struct_v >= 2) {
decode(ns, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(rgw_obj_key)
#if FMT_VERSION >= 90000
template<> struct fmt::formatter<rgw_obj_key> : fmt::formatter<std::string_view> {
template <typename FormatContext>
auto format(const rgw_obj_key& key, FormatContext& ctx) const {
if (key.instance.empty()) {
return formatter<std::string_view>::format(key.name, ctx);
} else {
return fmt::format_to(ctx.out(), "{}[{}]", key.name, key.instance);
}
}
};
#endif
inline std::ostream& operator<<(std::ostream& out, const rgw_obj_key &key) {
#if FMT_VERSION >= 90000
return out << fmt::format("{}", key);
#else
if (key.instance.empty()) {
return out << fmt::format("{}", key.name);
} else {
return out << fmt::format("{}[{}]", key.name, key.instance);
}
#endif
}
struct rgw_raw_obj {
rgw_pool pool;
std::string oid;
std::string loc;
rgw_raw_obj() {}
rgw_raw_obj(const rgw_pool& _pool, const std::string& _oid) {
init(_pool, _oid);
}
rgw_raw_obj(const rgw_pool& _pool, const std::string& _oid, const std::string& _loc) : loc(_loc) {
init(_pool, _oid);
}
void init(const rgw_pool& _pool, const std::string& _oid) {
pool = _pool;
oid = _oid;
}
bool empty() const {
return oid.empty();
}
void encode(bufferlist& bl) const {
ENCODE_START(6, 6, bl);
encode(pool, bl);
encode(oid, bl);
encode(loc, bl);
ENCODE_FINISH(bl);
}
void decode_from_rgw_obj(bufferlist::const_iterator& bl);
void decode(bufferlist::const_iterator& bl) {
unsigned ofs = bl.get_off();
DECODE_START(6, bl);
if (struct_v < 6) {
/*
* this object was encoded as rgw_obj, prior to rgw_raw_obj been split out of it,
* let's decode it as rgw_obj and convert it
*/
bl.seek(ofs);
decode_from_rgw_obj(bl);
return;
}
decode(pool, bl);
decode(oid, bl);
decode(loc, bl);
DECODE_FINISH(bl);
}
bool operator<(const rgw_raw_obj& o) const {
int r = pool.compare(o.pool);
if (r == 0) {
r = oid.compare(o.oid);
if (r == 0) {
r = loc.compare(o.loc);
}
}
return (r < 0);
}
bool operator==(const rgw_raw_obj& o) const {
return (pool == o.pool && oid == o.oid && loc == o.loc);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(rgw_raw_obj)
inline std::ostream& operator<<(std::ostream& out, const rgw_raw_obj& o) {
out << o.pool << ":" << o.oid;
return out;
}
struct rgw_obj {
rgw_bucket bucket;
rgw_obj_key key;
bool in_extra_data{false}; /* in-memory only member, does not serialize */
// Represents the hash index source for this object once it is set (non-empty)
std::string index_hash_source;
rgw_obj() {}
rgw_obj(const rgw_bucket& b, const std::string& name) : bucket(b), key(name) {}
rgw_obj(const rgw_bucket& b, const rgw_obj_key& k) : bucket(b), key(k) {}
rgw_obj(const rgw_bucket& b, const rgw_obj_index_key& k) : bucket(b), key(k) {}
void init(const rgw_bucket& b, const rgw_obj_key& k) {
bucket = b;
key = k;
}
void init(const rgw_bucket& b, const std::string& name) {
bucket = b;
key.set(name);
}
void init(const rgw_bucket& b, const std::string& name, const std::string& i, const std::string& n) {
bucket = b;
key.set(name, i, n);
}
void init_ns(const rgw_bucket& b, const std::string& name, const std::string& n) {
bucket = b;
key.name = name;
key.instance.clear();
key.ns = n;
}
bool empty() const {
return key.empty();
}
void set_key(const rgw_obj_key& k) {
key = k;
}
std::string get_oid() const {
return key.get_oid();
}
const std::string& get_hash_object() const {
return index_hash_source.empty() ? key.name : index_hash_source;
}
void set_in_extra_data(bool val) {
in_extra_data = val;
}
bool is_in_extra_data() const {
return in_extra_data;
}
void encode(bufferlist& bl) const {
ENCODE_START(6, 6, bl);
encode(bucket, bl);
encode(key.ns, bl);
encode(key.name, bl);
encode(key.instance, bl);
// encode(placement_id, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(6, 3, 3, bl);
if (struct_v < 6) {
std::string s;
decode(bucket.name, bl); /* bucket.name */
decode(s, bl); /* loc */
decode(key.ns, bl);
decode(key.name, bl);
if (struct_v >= 2)
decode(bucket, bl);
if (struct_v >= 4)
decode(key.instance, bl);
if (key.ns.empty() && key.instance.empty()) {
if (key.name[0] == '_') {
key.name = key.name.substr(1);
}
} else {
if (struct_v >= 5) {
decode(key.name, bl);
} else {
ssize_t pos = key.name.find('_', 1);
if (pos < 0) {
throw buffer::malformed_input();
}
key.name = key.name.substr(pos + 1);
}
}
} else {
decode(bucket, bl);
decode(key.ns, bl);
decode(key.name, bl);
decode(key.instance, bl);
// decode(placement_id, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<rgw_obj*>& o);
bool operator==(const rgw_obj& o) const {
return (key == o.key) &&
(bucket == o.bucket);
}
bool operator<(const rgw_obj& o) const {
int r = key.name.compare(o.key.name);
if (r == 0) {
r = bucket.bucket_id.compare(o.bucket.bucket_id); /* not comparing bucket.name, if bucket_id is equal so will be bucket.name */
if (r == 0) {
r = key.ns.compare(o.key.ns);
if (r == 0) {
r = key.instance.compare(o.key.instance);
}
}
}
return (r < 0);
}
const rgw_pool& get_explicit_data_pool() {
if (!in_extra_data || bucket.explicit_placement.data_extra_pool.empty()) {
return bucket.explicit_placement.data_pool;
}
return bucket.explicit_placement.data_extra_pool;
}
};
WRITE_CLASS_ENCODER(rgw_obj)
| 15,543 | 23.950241 | 133 |
h
|
null |
ceph-main/src/rgw/rgw_object_expirer.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 <iostream>
#include <sstream>
#include <string>
#include "auth/Crypto.h"
#include "common/armor.h"
#include "common/ceph_json.h"
#include "common/config.h"
#include "common/ceph_argparse.h"
#include "common/Formatter.h"
#include "common/errno.h"
#include "global/global_init.h"
#include "include/utime.h"
#include "include/str_list.h"
#include "rgw_user.h"
#include "rgw_bucket.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_log.h"
#include "rgw_formats.h"
#include "rgw_usage.h"
#include "rgw_object_expirer_core.h"
#define dout_subsys ceph_subsys_rgw
static rgw::sal::Driver* driver = NULL;
class StoreDestructor {
rgw::sal::Driver* driver;
public:
explicit StoreDestructor(rgw::sal::Driver* _s) : driver(_s) {}
~StoreDestructor() {
if (driver) {
DriverManager::close_storage(driver);
}
}
};
static void usage()
{
generic_server_usage();
}
int main(const int argc, const char **argv)
{
auto args = argv_to_vec(argc, argv);
if (args.empty()) {
std::cerr << argv[0] << ": -h or --help for usage" << std::endl;
exit(1);
}
if (ceph_argparse_need_usage(args)) {
usage();
exit(0);
}
auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_DAEMON,
CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS);
for (std::vector<const char *>::iterator i = args.begin(); i != args.end(); ) {
if (ceph_argparse_double_dash(args, i)) {
break;
}
}
if (g_conf()->daemonize) {
global_init_daemonize(g_ceph_context);
}
common_init_finish(g_ceph_context);
const DoutPrefix dp(cct.get(), dout_subsys, "rgw object expirer: ");
DriverManager::Config cfg;
cfg.store_name = "rados";
cfg.filter_name = "none";
driver = DriverManager::get_storage(&dp, g_ceph_context, cfg, false, false, false, false, false, false, null_yield);
if (!driver) {
std::cerr << "couldn't init storage provider" << std::endl;
return EIO;
}
/* Guard to not forget about closing the rados driver. */
StoreDestructor store_dtor(driver);
RGWObjectExpirer objexp(driver);
objexp.start_processor();
const utime_t interval(g_ceph_context->_conf->rgw_objexp_gc_interval, 0);
while (true) {
interval.sleep();
}
/* unreachable */
return EXIT_SUCCESS;
}
| 2,403 | 21.46729 | 118 |
cc
|
null |
ceph-main/src/rgw/rgw_object_lock.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
//
#include "rgw_object_lock.h"
using namespace std;
void DefaultRetention::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Mode", mode, obj, true);
if (mode.compare("GOVERNANCE") != 0 && mode.compare("COMPLIANCE") != 0) {
throw RGWXMLDecoder::err("bad Mode in lock rule");
}
bool days_exist = RGWXMLDecoder::decode_xml("Days", days, obj);
bool years_exist = RGWXMLDecoder::decode_xml("Years", years, obj);
if ((days_exist && years_exist) || (!days_exist && !years_exist)) {
throw RGWXMLDecoder::err("either Days or Years must be specified, but not both");
}
}
void DefaultRetention::dump_xml(Formatter *f) const {
encode_xml("Mode", mode, f);
if (days > 0) {
encode_xml("Days", days, f);
} else {
encode_xml("Years", years, f);
}
}
void ObjectLockRule::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("DefaultRetention", defaultRetention, obj, true);
}
void ObjectLockRule::dump_xml(Formatter *f) const {
encode_xml("DefaultRetention", defaultRetention, f);
}
void RGWObjectLock::decode_xml(XMLObj *obj) {
string enabled_str;
RGWXMLDecoder::decode_xml("ObjectLockEnabled", enabled_str, obj, true);
if (enabled_str.compare("Enabled") != 0) {
throw RGWXMLDecoder::err("invalid ObjectLockEnabled value");
} else {
enabled = true;
}
rule_exist = RGWXMLDecoder::decode_xml("Rule", rule, obj);
}
void RGWObjectLock::dump_xml(Formatter *f) const {
if (enabled) {
encode_xml("ObjectLockEnabled", "Enabled", f);
}
if (rule_exist) {
encode_xml("Rule", rule, f);
}
}
ceph::real_time RGWObjectLock::get_lock_until_date(const ceph::real_time& mtime) const {
if (!rule_exist) {
return ceph::real_time();
}
int days = get_days();
if (days <= 0) {
days = get_years()*365;
}
return mtime + make_timespan(days*24*60*60);
}
void RGWObjectRetention::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Mode", mode, obj, true);
if (mode.compare("GOVERNANCE") != 0 && mode.compare("COMPLIANCE") != 0) {
throw RGWXMLDecoder::err("bad Mode in retention");
}
string date_str;
RGWXMLDecoder::decode_xml("RetainUntilDate", date_str, obj, true);
boost::optional<ceph::real_time> date = ceph::from_iso_8601(date_str);
if (boost::none == date) {
throw RGWXMLDecoder::err("invalid RetainUntilDate value");
}
retain_until_date = *date;
}
void RGWObjectRetention::dump_xml(Formatter *f) const {
encode_xml("Mode", mode, f);
string date = ceph::to_iso_8601(retain_until_date);
encode_xml("RetainUntilDate", date, f);
}
void RGWObjectLegalHold::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Status", status, obj, true);
if (status.compare("ON") != 0 && status.compare("OFF") != 0) {
throw RGWXMLDecoder::err("bad status in legal hold");
}
}
void RGWObjectLegalHold::dump_xml(Formatter *f) const {
encode_xml("Status", status, f);
}
bool RGWObjectLegalHold::is_enabled() const {
return status.compare("ON") == 0;
}
| 3,059 | 29 | 88 |
cc
|
null |
ceph-main/src/rgw/rgw_object_lock.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"
#include "common/iso_8601.h"
#include "rgw_xml.h"
class DefaultRetention
{
protected:
std::string mode;
int days;
int years;
public:
DefaultRetention(): days(0), years(0) {};
int get_days() const {
return days;
}
int get_years() const {
return years;
}
std::string get_mode() const {
return mode;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(mode, bl);
encode(days, bl);
encode(years, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(mode, bl);
decode(days, bl);
decode(years, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(DefaultRetention)
class ObjectLockRule
{
protected:
DefaultRetention defaultRetention;
public:
int get_days() const {
return defaultRetention.get_days();
}
int get_years() const {
return defaultRetention.get_years();
}
std::string get_mode() const {
return defaultRetention.get_mode();
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(defaultRetention, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(defaultRetention, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(ObjectLockRule)
class RGWObjectLock
{
protected:
bool enabled;
bool rule_exist;
ObjectLockRule rule;
public:
RGWObjectLock():enabled(true), rule_exist(false) {}
int get_days() const {
return rule.get_days();
}
int get_years() const {
return rule.get_years();
}
std::string get_mode() const {
return rule.get_mode();
}
bool retention_period_valid() const {
// DefaultRetention requires either Days or Years.
// You can't specify both at the same time.
// see https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTObjectLockConfiguration.html
return (get_years() > 0) != (get_days() > 0);
}
bool has_rule() const {
return rule_exist;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(enabled, bl);
encode(rule_exist, bl);
if (rule_exist) {
encode(rule, bl);
}
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(enabled, bl);
decode(rule_exist, bl);
if (rule_exist) {
decode(rule, bl);
}
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
ceph::real_time get_lock_until_date(const ceph::real_time& mtime) const;
};
WRITE_CLASS_ENCODER(RGWObjectLock)
class RGWObjectRetention
{
protected:
std::string mode;
ceph::real_time retain_until_date;
public:
RGWObjectRetention() {}
RGWObjectRetention(std::string _mode, ceph::real_time _date): mode(_mode), retain_until_date(_date) {}
void set_mode(std::string _mode) {
mode = _mode;
}
std::string get_mode() const {
return mode;
}
void set_retain_until_date(ceph::real_time _retain_until_date) {
retain_until_date = _retain_until_date;
}
ceph::real_time get_retain_until_date() const {
return retain_until_date;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(mode, bl);
encode(retain_until_date, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(mode, bl);
decode(retain_until_date, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(RGWObjectRetention)
class RGWObjectLegalHold
{
protected:
std::string status;
public:
RGWObjectLegalHold() {}
RGWObjectLegalHold(std::string _status): status(_status) {}
void set_status(std::string _status) {
status = _status;
}
std::string get_status() const {
return status;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(status, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(status, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
bool is_enabled() const;
};
WRITE_CLASS_ENCODER(RGWObjectLegalHold)
| 4,534 | 19.336323 | 104 |
h
|
null |
ceph-main/src/rgw/rgw_oidc_provider.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 <ctime>
#include <regex>
#include "common/errno.h"
#include "common/Formatter.h"
#include "common/ceph_json.h"
#include "common/ceph_time.h"
#include "rgw_rados.h"
#include "rgw_zone.h"
#include "include/types.h"
#include "rgw_string.h"
#include "rgw_common.h"
#include "rgw_tools.h"
#include "rgw_oidc_provider.h"
#include "services/svc_zone.h"
#include "services/svc_sys_obj.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw { namespace sal {
const string RGWOIDCProvider::oidc_url_oid_prefix = "oidc_url.";
const string RGWOIDCProvider::oidc_arn_prefix = "arn:aws:iam::";
int RGWOIDCProvider::get_tenant_url_from_arn(string& tenant, string& url)
{
auto provider_arn = rgw::ARN::parse(arn);
if (!provider_arn) {
return -EINVAL;
}
url = provider_arn->resource;
tenant = provider_arn->account;
auto pos = url.find("oidc-provider/");
if (pos != std::string::npos) {
url.erase(pos, 14);
}
return 0;
}
int RGWOIDCProvider::create(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y)
{
int ret;
if (! validate_input(dpp)) {
return -EINVAL;
}
string idp_url = url_remove_prefix(provider_url);
/* check to see the name is not used */
ret = read_url(dpp, idp_url, tenant, y);
if (exclusive && ret == 0) {
ldpp_dout(dpp, 0) << "ERROR: url " << provider_url << " already in use"
<< id << dendl;
return -EEXIST;
} else if ( ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 0) << "failed reading provider url " << provider_url << ": "
<< cpp_strerror(-ret) << dendl;
return ret;
}
//arn
arn = oidc_arn_prefix + tenant + ":oidc-provider/" + idp_url;
// Creation time
real_clock::time_point t = real_clock::now();
struct timeval tv;
real_clock::to_timeval(t, tv);
char buf[30];
struct tm result;
gmtime_r(&tv.tv_sec, &result);
strftime(buf,30,"%Y-%m-%dT%H:%M:%S", &result);
sprintf(buf + strlen(buf),".%dZ",(int)tv.tv_usec/1000);
creation_date.assign(buf, strlen(buf));
ret = store_url(dpp, idp_url, exclusive, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: storing role info in OIDC pool: "
<< provider_url << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
return 0;
}
int RGWOIDCProvider::get(const DoutPrefixProvider *dpp, optional_yield y)
{
string url, tenant;
auto ret = get_tenant_url_from_arn(tenant, url);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to parse arn" << dendl;
return -EINVAL;
}
if (this->tenant != tenant) {
ldpp_dout(dpp, 0) << "ERROR: tenant in arn doesn't match that of user " << this->tenant << ", "
<< tenant << ": " << dendl;
return -EINVAL;
}
ret = read_url(dpp, url, tenant, y);
if (ret < 0) {
return ret;
}
return 0;
}
void RGWOIDCProvider::dump(Formatter *f) const
{
encode_json("OpenIDConnectProviderArn", arn, f);
}
void RGWOIDCProvider::dump_all(Formatter *f) const
{
f->open_object_section("ClientIDList");
for (auto it : client_ids) {
encode_json("member", it, f);
}
f->close_section();
encode_json("CreateDate", creation_date, f);
f->open_object_section("ThumbprintList");
for (auto it : thumbprints) {
encode_json("member", it, f);
}
f->close_section();
encode_json("Url", provider_url, f);
}
void RGWOIDCProvider::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("OpenIDConnectProviderArn", arn, obj);
}
bool RGWOIDCProvider::validate_input(const DoutPrefixProvider *dpp)
{
if (provider_url.length() > MAX_OIDC_URL_LEN) {
ldpp_dout(dpp, 0) << "ERROR: Invalid length of url " << dendl;
return false;
}
if (client_ids.size() > MAX_OIDC_NUM_CLIENT_IDS) {
ldpp_dout(dpp, 0) << "ERROR: Invalid number of client ids " << dendl;
return false;
}
for (auto& it : client_ids) {
if (it.length() > MAX_OIDC_CLIENT_ID_LEN) {
return false;
}
}
if (thumbprints.size() > MAX_OIDC_NUM_THUMBPRINTS) {
ldpp_dout(dpp, 0) << "ERROR: Invalid number of thumbprints " << thumbprints.size() << dendl;
return false;
}
for (auto& it : thumbprints) {
if (it.length() > MAX_OIDC_THUMBPRINT_LEN) {
return false;
}
}
return true;
}
const string& RGWOIDCProvider::get_url_oid_prefix()
{
return oidc_url_oid_prefix;
}
} } // namespace rgw::sal
| 4,483 | 23.502732 | 99 |
cc
|
null |
ceph-main/src/rgw/rgw_oidc_provider.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_context.h"
#include "common/ceph_json.h"
#include "rgw/rgw_sal.h"
namespace rgw { namespace sal {
class RGWOIDCProvider
{
public:
static const std::string oidc_url_oid_prefix;
static const std::string oidc_arn_prefix;
static constexpr int MAX_OIDC_NUM_CLIENT_IDS = 100;
static constexpr int MAX_OIDC_CLIENT_ID_LEN = 255;
static constexpr int MAX_OIDC_NUM_THUMBPRINTS = 5;
static constexpr int MAX_OIDC_THUMBPRINT_LEN = 40;
static constexpr int MAX_OIDC_URL_LEN = 255;
protected:
std::string id;
std::string provider_url;
std::string arn;
std::string creation_date;
std::string tenant;
std::vector<std::string> client_ids;
std::vector<std::string> thumbprints;
int get_tenant_url_from_arn(std::string& tenant, std::string& url);
virtual int store_url(const DoutPrefixProvider *dpp, const std::string& url, bool exclusive, optional_yield y) = 0;
virtual int read_url(const DoutPrefixProvider *dpp, const std::string& url, const std::string& tenant, optional_yield y) = 0;
bool validate_input(const DoutPrefixProvider *dpp);
public:
void set_arn(std::string _arn) {
arn = _arn;
}
void set_url(std::string _provider_url) {
provider_url = _provider_url;
}
void set_tenant(std::string _tenant) {
tenant = _tenant;
}
void set_client_ids(std::vector<std::string>& _client_ids) {
client_ids = std::move(_client_ids);
}
void set_thumbprints(std::vector<std::string>& _thumbprints) {
thumbprints = std::move(_thumbprints);
}
RGWOIDCProvider(std::string provider_url,
std::string tenant,
std::vector<std::string> client_ids,
std::vector<std::string> thumbprints)
: provider_url(std::move(provider_url)),
tenant(std::move(tenant)),
client_ids(std::move(client_ids)),
thumbprints(std::move(thumbprints)) {
}
RGWOIDCProvider( std::string arn,
std::string tenant)
: arn(std::move(arn)),
tenant(std::move(tenant)) {
}
RGWOIDCProvider(std::string tenant)
: tenant(std::move(tenant)) {}
RGWOIDCProvider() {}
virtual ~RGWOIDCProvider() = default;
void encode(bufferlist& bl) const {
ENCODE_START(3, 1, bl);
encode(id, bl);
encode(provider_url, bl);
encode(arn, bl);
encode(creation_date, bl);
encode(tenant, bl);
encode(client_ids, bl);
encode(thumbprints, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(id, bl);
decode(provider_url, bl);
decode(arn, bl);
decode(creation_date, bl);
decode(tenant, bl);
decode(client_ids, bl);
decode(thumbprints, bl);
DECODE_FINISH(bl);
}
const std::string& get_provider_url() const { return provider_url; }
const std::string& get_arn() const { return arn; }
const std::string& get_create_date() const { return creation_date; }
const std::vector<std::string>& get_client_ids() const { return client_ids;}
const std::vector<std::string>& get_thumbprints() const { return thumbprints; }
int create(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y);
virtual int delete_obj(const DoutPrefixProvider *dpp, optional_yield y) = 0;
int get(const DoutPrefixProvider *dpp, optional_yield y);
void dump(Formatter *f) const;
void dump_all(Formatter *f) const;
void decode_json(JSONObj *obj);
static const std::string& get_url_oid_prefix();
};
WRITE_CLASS_ENCODER(RGWOIDCProvider)
} } // namespace rgw::sal
| 3,650 | 28.92623 | 127 |
h
|
null |
ceph-main/src/rgw/rgw_op.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 <stdlib.h>
#include <system_error>
#include <unistd.h>
#include <sstream>
#include <string_view>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include "include/scope_guard.h"
#include "common/Clock.h"
#include "common/armor.h"
#include "common/errno.h"
#include "common/mime.h"
#include "common/utf8.h"
#include "common/ceph_json.h"
#include "common/static_ptr.h"
#include "rgw_tracer.h"
#include "rgw_rados.h"
#include "rgw_zone.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_acl_swift.h"
#include "rgw_user.h"
#include "rgw_bucket.h"
#include "rgw_log.h"
#include "rgw_multi.h"
#include "rgw_multi_del.h"
#include "rgw_cors.h"
#include "rgw_cors_s3.h"
#include "rgw_rest_conn.h"
#include "rgw_rest_s3.h"
#include "rgw_tar.h"
#include "rgw_client_io.h"
#include "rgw_compression.h"
#include "rgw_role.h"
#include "rgw_tag_s3.h"
#include "rgw_putobj_processor.h"
#include "rgw_crypt.h"
#include "rgw_perf_counters.h"
#include "rgw_process_env.h"
#include "rgw_notify.h"
#include "rgw_notify_event_type.h"
#include "rgw_sal.h"
#include "rgw_sal_rados.h"
#include "rgw_torrent.h"
#include "rgw_lua_data_filter.h"
#include "rgw_lua.h"
#include "services/svc_zone.h"
#include "services/svc_quota.h"
#include "services/svc_sys_obj.h"
#include "cls/lock/cls_lock_client.h"
#include "cls/rgw/cls_rgw_client.h"
#include "include/ceph_assert.h"
#include "compressor/Compressor.h"
#ifdef WITH_ARROW_FLIGHT
#include "rgw_flight.h"
#include "rgw_flight_frontend.h"
#endif
#ifdef WITH_LTTNG
#define TRACEPOINT_DEFINE
#define TRACEPOINT_PROBE_DYNAMIC_LINKAGE
#include "tracing/rgw_op.h"
#undef TRACEPOINT_PROBE_DYNAMIC_LINKAGE
#undef TRACEPOINT_DEFINE
#else
#define tracepoint(...)
#endif
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
using namespace librados;
using ceph::crypto::MD5;
using boost::optional;
using boost::none;
using rgw::ARN;
using rgw::IAM::Effect;
using rgw::IAM::Policy;
static string mp_ns = RGW_OBJ_NS_MULTIPART;
static string shadow_ns = RGW_OBJ_NS_SHADOW;
static void forward_req_info(const DoutPrefixProvider *dpp, CephContext *cct, req_info& info, const std::string& bucket_name);
static MultipartMetaFilter mp_filter;
// this probably should belong in the rgw_iam_policy_keywords, I'll get it to it
// at some point
static constexpr auto S3_EXISTING_OBJTAG = "s3:ExistingObjectTag";
static constexpr auto S3_RESOURCE_TAG = "s3:ResourceTag";
static constexpr auto S3_RUNTIME_RESOURCE_VAL = "${s3:ResourceTag";
int RGWGetObj::parse_range(void)
{
int r = -ERANGE;
string rs(range_str);
string ofs_str;
string end_str;
ignore_invalid_range = s->cct->_conf->rgw_ignore_get_invalid_range;
partial_content = false;
size_t pos = rs.find("bytes=");
if (pos == string::npos) {
pos = 0;
while (isspace(rs[pos]))
pos++;
int end = pos;
while (isalpha(rs[end]))
end++;
if (strncasecmp(rs.c_str(), "bytes", end - pos) != 0)
return 0;
while (isspace(rs[end]))
end++;
if (rs[end] != '=')
return 0;
rs = rs.substr(end + 1);
} else {
rs = rs.substr(pos + 6); /* size of("bytes=") */
}
pos = rs.find('-');
if (pos == string::npos)
goto done;
partial_content = true;
ofs_str = rs.substr(0, pos);
end_str = rs.substr(pos + 1);
if (end_str.length()) {
end = atoll(end_str.c_str());
if (end < 0)
goto done;
}
if (ofs_str.length()) {
ofs = atoll(ofs_str.c_str());
} else { // RFC2616 suffix-byte-range-spec
ofs = -end;
end = -1;
}
if (end >= 0 && end < ofs)
goto done;
range_parsed = true;
return 0;
done:
if (ignore_invalid_range) {
partial_content = false;
ofs = 0;
end = -1;
range_parsed = false; // allow retry
r = 0;
}
return r;
}
static int decode_policy(const DoutPrefixProvider *dpp,
CephContext *cct,
bufferlist& bl,
RGWAccessControlPolicy *policy)
{
auto iter = bl.cbegin();
try {
policy->decode(iter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: could not decode policy, caught buffer::error" << dendl;
return -EIO;
}
if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
ldpp_dout(dpp, 15) << __func__ << " Read AccessControlPolicy";
RGWAccessControlPolicy_S3 *s3policy = static_cast<RGWAccessControlPolicy_S3 *>(policy);
s3policy->to_xml(*_dout);
*_dout << dendl;
}
return 0;
}
static int get_user_policy_from_attr(const DoutPrefixProvider *dpp,
CephContext * const cct,
map<string, bufferlist>& attrs,
RGWAccessControlPolicy& policy /* out */)
{
auto aiter = attrs.find(RGW_ATTR_ACL);
if (aiter != attrs.end()) {
int ret = decode_policy(dpp, cct, aiter->second, &policy);
if (ret < 0) {
return ret;
}
} else {
return -ENOENT;
}
return 0;
}
/**
* Get the AccessControlPolicy for an object off of disk.
* policy: must point to a valid RGWACL, and will be filled upon return.
* bucket: name of the bucket containing the object.
* object: name of the object to get the ACL for.
* Returns: 0 on success, -ERR# otherwise.
*/
int rgw_op_get_bucket_policy_from_attr(const DoutPrefixProvider *dpp,
CephContext *cct,
rgw::sal::Driver* driver,
RGWBucketInfo& bucket_info,
map<string, bufferlist>& bucket_attrs,
RGWAccessControlPolicy *policy,
optional_yield y)
{
map<string, bufferlist>::iterator aiter = bucket_attrs.find(RGW_ATTR_ACL);
if (aiter != bucket_attrs.end()) {
int ret = decode_policy(dpp, cct, aiter->second, policy);
if (ret < 0)
return ret;
} else {
ldpp_dout(dpp, 0) << "WARNING: couldn't find acl header for bucket, generating default" << dendl;
std::unique_ptr<rgw::sal::User> user = driver->get_user(bucket_info.owner);
/* object exists, but policy is broken */
int r = user->load_user(dpp, y);
if (r < 0)
return r;
policy->create_default(bucket_info.owner, user->get_display_name());
}
return 0;
}
static int get_obj_policy_from_attr(const DoutPrefixProvider *dpp,
CephContext *cct,
rgw::sal::Driver* driver,
RGWBucketInfo& bucket_info,
map<string, bufferlist>& bucket_attrs,
RGWAccessControlPolicy *policy,
string *storage_class,
rgw::sal::Object* obj,
optional_yield y)
{
bufferlist bl;
int ret = 0;
std::unique_ptr<rgw::sal::Object::ReadOp> rop = obj->get_read_op();
ret = rop->get_attr(dpp, RGW_ATTR_ACL, bl, y);
if (ret >= 0) {
ret = decode_policy(dpp, cct, bl, policy);
if (ret < 0)
return ret;
} else if (ret == -ENODATA) {
/* object exists, but policy is broken */
ldpp_dout(dpp, 0) << "WARNING: couldn't find acl header for object, generating default" << dendl;
std::unique_ptr<rgw::sal::User> user = driver->get_user(bucket_info.owner);
ret = user->load_user(dpp, y);
if (ret < 0)
return ret;
policy->create_default(bucket_info.owner, user->get_display_name());
}
if (storage_class) {
bufferlist scbl;
int r = rop->get_attr(dpp, RGW_ATTR_STORAGE_CLASS, scbl, y);
if (r >= 0) {
*storage_class = scbl.to_str();
} else {
storage_class->clear();
}
}
return ret;
}
static boost::optional<Policy> get_iam_policy_from_attr(CephContext* cct,
map<string, bufferlist>& attrs,
const string& tenant) {
auto i = attrs.find(RGW_ATTR_IAM_POLICY);
if (i != attrs.end()) {
return Policy(cct, tenant, i->second, false);
} else {
return none;
}
}
static boost::optional<PublicAccessBlockConfiguration>
get_public_access_conf_from_attr(const map<string, bufferlist>& attrs)
{
if (auto aiter = attrs.find(RGW_ATTR_PUBLIC_ACCESS);
aiter != attrs.end()) {
bufferlist::const_iterator iter{&aiter->second};
PublicAccessBlockConfiguration access_conf;
try {
access_conf.decode(iter);
} catch (const buffer::error& e) {
return boost::none;
}
return access_conf;
}
return boost::none;
}
vector<Policy> get_iam_user_policy_from_attr(CephContext* cct,
map<string, bufferlist>& attrs,
const string& tenant) {
vector<Policy> policies;
if (auto it = attrs.find(RGW_ATTR_USER_POLICY); it != attrs.end()) {
bufferlist out_bl = attrs[RGW_ATTR_USER_POLICY];
map<string, string> policy_map;
decode(policy_map, out_bl);
for (auto& it : policy_map) {
bufferlist bl = bufferlist::static_from_string(it.second);
Policy p(cct, tenant, bl, false);
policies.push_back(std::move(p));
}
}
return policies;
}
static int read_bucket_policy(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
req_state *s,
RGWBucketInfo& bucket_info,
map<string, bufferlist>& bucket_attrs,
RGWAccessControlPolicy *policy,
rgw_bucket& bucket,
optional_yield y)
{
if (!s->system_request && bucket_info.flags & BUCKET_SUSPENDED) {
ldpp_dout(dpp, 0) << "NOTICE: bucket " << bucket_info.bucket.name
<< " is suspended" << dendl;
return -ERR_USER_SUSPENDED;
}
if (bucket.name.empty()) {
return 0;
}
int ret = rgw_op_get_bucket_policy_from_attr(dpp, s->cct, driver, bucket_info, bucket_attrs, policy, y);
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_BUCKET;
}
return ret;
}
static int read_obj_policy(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
req_state *s,
RGWBucketInfo& bucket_info,
map<string, bufferlist>& bucket_attrs,
RGWAccessControlPolicy* acl,
string *storage_class,
boost::optional<Policy>& policy,
rgw::sal::Bucket* bucket,
rgw::sal::Object* object,
optional_yield y,
bool copy_src=false)
{
string upload_id;
upload_id = s->info.args.get("uploadId");
std::unique_ptr<rgw::sal::Object> mpobj;
rgw_obj obj;
if (!s->system_request && bucket_info.flags & BUCKET_SUSPENDED) {
ldpp_dout(dpp, 0) << "NOTICE: bucket " << bucket_info.bucket.name
<< " is suspended" << dendl;
return -ERR_USER_SUSPENDED;
}
// when getting policy info for copy-source obj, upload_id makes no sense.
// 'copy_src' is used to make this function backward compatible.
if (!upload_id.empty() && !copy_src) {
/* multipart upload */
std::unique_ptr<rgw::sal::MultipartUpload> upload;
upload = bucket->get_multipart_upload(object->get_name(), upload_id);
mpobj = upload->get_meta_obj();
mpobj->set_in_extra_data(true);
object = mpobj.get();
}
policy = get_iam_policy_from_attr(s->cct, bucket_attrs, bucket->get_tenant());
int ret = get_obj_policy_from_attr(dpp, s->cct, driver, bucket_info,
bucket_attrs, acl, storage_class, object,
s->yield);
if (ret == -ENOENT) {
/* object does not exist checking the bucket's ACL to make sure
that we send a proper error code */
RGWAccessControlPolicy bucket_policy(s->cct);
ret = rgw_op_get_bucket_policy_from_attr(dpp, s->cct, driver, bucket_info, bucket_attrs, &bucket_policy, y);
if (ret < 0) {
return ret;
}
const rgw_user& bucket_owner = bucket_policy.get_owner().get_id();
if (bucket_owner.compare(s->user->get_id()) != 0 &&
! s->auth.identity->is_admin_of(bucket_owner)) {
auto r = eval_identity_or_session_policies(dpp, s->iam_user_policies, s->env,
rgw::IAM::s3ListBucket, ARN(bucket->get_key()));
if (r == Effect::Allow)
return -ENOENT;
if (r == Effect::Deny)
return -EACCES;
if (policy) {
ARN b_arn(bucket->get_key());
r = policy->eval(s->env, *s->auth.identity, rgw::IAM::s3ListBucket, b_arn);
if (r == Effect::Allow)
return -ENOENT;
if (r == Effect::Deny)
return -EACCES;
}
if (! s->session_policies.empty()) {
r = eval_identity_or_session_policies(dpp, s->session_policies, s->env,
rgw::IAM::s3ListBucket, ARN(bucket->get_key()));
if (r == Effect::Allow)
return -ENOENT;
if (r == Effect::Deny)
return -EACCES;
}
if (! bucket_policy.verify_permission(s, *s->auth.identity, s->perm_mask, RGW_PERM_READ))
ret = -EACCES;
else
ret = -ENOENT;
} else {
ret = -ENOENT;
}
}
return ret;
}
/**
* Get the AccessControlPolicy for an user, bucket or object off of disk.
* s: The req_state to draw information from.
* only_bucket: If true, reads the user and bucket ACLs rather than the object ACL.
* Returns: 0 on success, -ERR# otherwise.
*/
int rgw_build_bucket_policies(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, req_state* s, optional_yield y)
{
int ret = 0;
string bi = s->info.args.get(RGW_SYS_PARAM_PREFIX "bucket-instance");
if (!bi.empty()) {
// note: overwrites s->bucket_name, may include a tenant/
ret = rgw_bucket_parse_bucket_instance(bi, &s->bucket_name, &s->bucket_instance_id, &s->bucket_instance_shard_id);
if (ret < 0) {
return ret;
}
}
if(s->dialect.compare("s3") == 0) {
s->bucket_acl = std::make_unique<RGWAccessControlPolicy_S3>(s->cct);
} else if(s->dialect.compare("swift") == 0) {
/* We aren't allocating the account policy for those operations using
* the Swift's infrastructure that don't really need req_state::user.
* Typical example here is the implementation of /info. */
if (!s->user->get_id().empty()) {
s->user_acl = std::make_unique<RGWAccessControlPolicy_SWIFTAcct>(s->cct);
}
s->bucket_acl = std::make_unique<RGWAccessControlPolicy_SWIFT>(s->cct);
} else {
s->bucket_acl = std::make_unique<RGWAccessControlPolicy>(s->cct);
}
/* check if copy source is within the current domain */
if (!s->src_bucket_name.empty()) {
std::unique_ptr<rgw::sal::Bucket> src_bucket;
ret = driver->get_bucket(dpp, nullptr,
rgw_bucket_key(s->src_tenant_name,
s->src_bucket_name),
&src_bucket, y);
if (ret == 0) {
string& zonegroup = src_bucket->get_info().zonegroup;
s->local_source = driver->get_zone()->get_zonegroup().equals(zonegroup);
}
}
struct {
rgw_user uid;
std::string display_name;
} acct_acl_user = {
s->user->get_id(),
s->user->get_display_name(),
};
if (!s->bucket_name.empty()) {
s->bucket_exists = true;
/* This is the only place that s->bucket is created. It should never be
* overwritten. */
ret = driver->get_bucket(dpp, s->user.get(), rgw_bucket(s->bucket_tenant, s->bucket_name, s->bucket_instance_id), &s->bucket, y);
if (ret < 0) {
if (ret != -ENOENT) {
string bucket_log;
bucket_log = rgw_make_bucket_entry_name(s->bucket_tenant, s->bucket_name);
ldpp_dout(dpp, 0) << "NOTICE: couldn't get bucket from bucket_name (name="
<< bucket_log << ")" << dendl;
return ret;
}
s->bucket_exists = false;
return -ERR_NO_SUCH_BUCKET;
}
if (!rgw::sal::Object::empty(s->object.get())) {
s->object->set_bucket(s->bucket.get());
}
s->bucket_mtime = s->bucket->get_modification_time();
s->bucket_attrs = s->bucket->get_attrs();
ret = read_bucket_policy(dpp, driver, s, s->bucket->get_info(),
s->bucket->get_attrs(),
s->bucket_acl.get(), s->bucket->get_key(), y);
acct_acl_user = {
s->bucket->get_info().owner,
s->bucket_acl->get_owner().get_display_name(),
};
s->bucket_owner = s->bucket_acl->get_owner();
std::unique_ptr<rgw::sal::ZoneGroup> zonegroup;
int r = driver->get_zonegroup(s->bucket->get_info().zonegroup, &zonegroup);
if (!r) {
s->zonegroup_endpoint = zonegroup->get_endpoint();
s->zonegroup_name = zonegroup->get_name();
}
if (r < 0 && ret == 0) {
ret = r;
}
if (!driver->get_zone()->get_zonegroup().equals(s->bucket->get_info().zonegroup)) {
ldpp_dout(dpp, 0) << "NOTICE: request for data in a different zonegroup ("
<< s->bucket->get_info().zonegroup << " != "
<< driver->get_zone()->get_zonegroup().get_id() << ")" << dendl;
/* we now need to make sure that the operation actually requires copy source, that is
* it's a copy operation
*/
if (driver->get_zone()->get_zonegroup().is_master_zonegroup() && s->system_request) {
/*If this is the master, don't redirect*/
} else if (s->op_type == RGW_OP_GET_BUCKET_LOCATION ) {
/* If op is get bucket location, don't redirect */
} else if (!s->local_source ||
(s->op != OP_PUT && s->op != OP_COPY) ||
rgw::sal::Object::empty(s->object.get())) {
return -ERR_PERMANENT_REDIRECT;
}
}
/* init dest placement */
s->dest_placement.storage_class = s->info.storage_class;
s->dest_placement.inherit_from(s->bucket->get_placement_rule());
if (!driver->valid_placement(s->dest_placement)) {
ldpp_dout(dpp, 0) << "NOTICE: invalid dest placement: " << s->dest_placement.to_str() << dendl;
return -EINVAL;
}
s->bucket_access_conf = get_public_access_conf_from_attr(s->bucket->get_attrs());
}
/* handle user ACL only for those APIs which support it */
if (s->user_acl) {
std::unique_ptr<rgw::sal::User> acl_user = driver->get_user(acct_acl_user.uid);
ret = acl_user->read_attrs(dpp, y);
if (!ret) {
ret = get_user_policy_from_attr(dpp, s->cct, acl_user->get_attrs(), *s->user_acl);
}
if (-ENOENT == ret) {
/* In already existing clusters users won't have ACL. In such case
* assuming that only account owner has the rights seems to be
* reasonable. That allows to have only one verification logic.
* NOTE: there is small compatibility kludge for global, empty tenant:
* 1. if we try to reach an existing bucket, its owner is considered
* as account owner.
* 2. otherwise account owner is identity stored in s->user->user_id. */
s->user_acl->create_default(acct_acl_user.uid,
acct_acl_user.display_name);
ret = 0;
} else if (ret < 0) {
ldpp_dout(dpp, 0) << "NOTICE: couldn't get user attrs for handling ACL "
"(user_id=" << s->user->get_id() << ", ret=" << ret << ")" << dendl;
return ret;
}
}
// We don't need user policies in case of STS token returned by AssumeRole,
// hence the check for user type
if (! s->user->get_id().empty() && s->auth.identity->get_identity_type() != TYPE_ROLE) {
try {
ret = s->user->read_attrs(dpp, y);
if (ret == 0) {
auto user_policies = get_iam_user_policy_from_attr(s->cct,
s->user->get_attrs(),
s->user->get_tenant());
s->iam_user_policies.insert(s->iam_user_policies.end(),
std::make_move_iterator(user_policies.begin()),
std::make_move_iterator(user_policies.end()));
} else {
if (ret == -ENOENT)
ret = 0;
else ret = -EACCES;
}
} catch (const std::exception& e) {
ldpp_dout(dpp, -1) << "Error reading IAM User Policy: " << e.what() << dendl;
ret = -EACCES;
}
}
try {
s->iam_policy = get_iam_policy_from_attr(s->cct, s->bucket_attrs, s->bucket_tenant);
} catch (const std::exception& e) {
// Really this is a can't happen condition. We parse the policy
// when it's given to us, so perhaps we should abort or otherwise
// raise bloody murder.
ldpp_dout(dpp, 0) << "Error reading IAM Policy: " << e.what() << dendl;
ret = -EACCES;
}
bool success = driver->get_zone()->get_redirect_endpoint(&s->redirect_zone_endpoint);
if (success) {
ldpp_dout(dpp, 20) << "redirect_zone_endpoint=" << s->redirect_zone_endpoint << dendl;
}
return ret;
}
/**
* Get the AccessControlPolicy for a bucket or object off of disk.
* s: The req_state to draw information from.
* only_bucket: If true, reads the bucket ACL rather than the object ACL.
* Returns: 0 on success, -ERR# otherwise.
*/
int rgw_build_object_policies(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
req_state *s, bool prefetch_data, optional_yield y)
{
int ret = 0;
if (!rgw::sal::Object::empty(s->object.get())) {
if (!s->bucket_exists) {
return -ERR_NO_SUCH_BUCKET;
}
s->object_acl = std::make_unique<RGWAccessControlPolicy>(s->cct);
s->object->set_atomic();
if (prefetch_data) {
s->object->set_prefetch_data();
}
ret = read_obj_policy(dpp, driver, s, s->bucket->get_info(), s->bucket_attrs,
s->object_acl.get(), nullptr, s->iam_policy, s->bucket.get(),
s->object.get(), y);
}
return ret;
}
static int rgw_iam_remove_objtags(const DoutPrefixProvider *dpp, req_state* s, rgw::sal::Object* object, bool has_existing_obj_tag, bool has_resource_tag) {
object->set_atomic();
int op_ret = object->get_obj_attrs(s->yield, dpp);
if (op_ret < 0)
return op_ret;
rgw::sal::Attrs attrs = object->get_attrs();
auto tags = attrs.find(RGW_ATTR_TAGS);
if (tags != attrs.end()) {
RGWObjTags tagset;
try {
auto bliter = tags->second.cbegin();
tagset.decode(bliter);
} catch (buffer::error& err) {
ldpp_dout(s, 0) << "ERROR: caught buffer::error, couldn't decode TagSet" << dendl;
return -EIO;
}
for (auto& tag: tagset.get_tags()) {
if (has_existing_obj_tag) {
vector<std::unordered_multimap<string, string>::iterator> iters;
string key = "s3:ExistingObjectTag/" + tag.first;
auto result = s->env.equal_range(key);
for (auto& it = result.first; it != result.second; ++it)
{
if (tag.second == it->second) {
iters.emplace_back(it);
}
}
for (auto& it : iters) {
s->env.erase(it);
}
}//end if has_existing_obj_tag
if (has_resource_tag) {
vector<std::unordered_multimap<string, string>::iterator> iters;
string key = "s3:ResourceTag/" + tag.first;
auto result = s->env.equal_range(key);
for (auto& it = result.first; it != result.second; ++it)
{
if (tag.second == it->second) {
iters.emplace_back(it);
}
}
for (auto& it : iters) {
s->env.erase(it);
}
}//end if has_resource_tag
}
}
return 0;
}
void rgw_add_to_iam_environment(rgw::IAM::Environment& e, std::string_view key, std::string_view val){
// This variant just adds non empty key pairs to IAM env., values can be empty
// in certain cases like tagging
if (!key.empty())
e.emplace(key,val);
}
static int rgw_iam_add_tags_from_bl(req_state* s, bufferlist& bl, bool has_existing_obj_tag=false, bool has_resource_tag=false){
RGWObjTags& tagset = s->tagset;
try {
auto bliter = bl.cbegin();
tagset.decode(bliter);
} catch (buffer::error& err) {
ldpp_dout(s, 0) << "ERROR: caught buffer::error, couldn't decode TagSet" << dendl;
return -EIO;
}
for (const auto& tag: tagset.get_tags()){
if (has_existing_obj_tag)
rgw_add_to_iam_environment(s->env, "s3:ExistingObjectTag/" + tag.first, tag.second);
if (has_resource_tag)
rgw_add_to_iam_environment(s->env, "s3:ResourceTag/" + tag.first, tag.second);
}
return 0;
}
static int rgw_iam_add_objtags(const DoutPrefixProvider *dpp, req_state* s, rgw::sal::Object* object, bool has_existing_obj_tag, bool has_resource_tag) {
object->set_atomic();
int op_ret = object->get_obj_attrs(s->yield, dpp);
if (op_ret < 0)
return op_ret;
rgw::sal::Attrs attrs = object->get_attrs();
auto tags = attrs.find(RGW_ATTR_TAGS);
if (tags != attrs.end()){
return rgw_iam_add_tags_from_bl(s, tags->second, has_existing_obj_tag, has_resource_tag);
}
return 0;
}
static int rgw_iam_add_objtags(const DoutPrefixProvider *dpp, req_state* s, bool has_existing_obj_tag, bool has_resource_tag) {
if (!rgw::sal::Object::empty(s->object.get())) {
return rgw_iam_add_objtags(dpp, s, s->object.get(), has_existing_obj_tag, has_resource_tag);
}
return 0;
}
static int rgw_iam_add_buckettags(const DoutPrefixProvider *dpp, req_state* s, rgw::sal::Bucket* bucket) {
rgw::sal::Attrs attrs = bucket->get_attrs();
auto tags = attrs.find(RGW_ATTR_TAGS);
if (tags != attrs.end()) {
return rgw_iam_add_tags_from_bl(s, tags->second, false, true);
}
return 0;
}
static int rgw_iam_add_buckettags(const DoutPrefixProvider *dpp, req_state* s) {
return rgw_iam_add_buckettags(dpp, s, s->bucket.get());
}
static void rgw_iam_add_crypt_attrs(rgw::IAM::Environment& e,
const meta_map_t& attrs)
{
constexpr auto encrypt_attr = "x-amz-server-side-encryption";
constexpr auto s3_encrypt_attr = "s3:x-amz-server-side-encryption";
if (auto h = attrs.find(encrypt_attr); h != attrs.end()) {
rgw_add_to_iam_environment(e, s3_encrypt_attr, h->second);
}
constexpr auto kms_attr = "x-amz-server-side-encryption-aws-kms-key-id";
constexpr auto s3_kms_attr = "s3:x-amz-server-side-encryption-aws-kms-key-id";
if (auto h = attrs.find(kms_attr); h != attrs.end()) {
rgw_add_to_iam_environment(e, s3_kms_attr, h->second);
}
}
static std::tuple<bool, bool> rgw_check_policy_condition(const DoutPrefixProvider *dpp,
boost::optional<rgw::IAM::Policy> iam_policy,
boost::optional<vector<rgw::IAM::Policy>> identity_policies,
boost::optional<vector<rgw::IAM::Policy>> session_policies,
bool check_obj_exist_tag=true) {
bool has_existing_obj_tag = false, has_resource_tag = false;
bool iam_policy_s3_exist_tag = false, iam_policy_s3_resource_tag = false;
if (iam_policy) {
if (check_obj_exist_tag) {
iam_policy_s3_exist_tag = iam_policy->has_partial_conditional(S3_EXISTING_OBJTAG);
}
iam_policy_s3_resource_tag = iam_policy->has_partial_conditional(S3_RESOURCE_TAG) || iam_policy->has_partial_conditional_value(S3_RUNTIME_RESOURCE_VAL);
}
bool identity_policy_s3_exist_tag = false, identity_policy_s3_resource_tag = false;
if (identity_policies) {
for (auto& identity_policy : identity_policies.get()) {
if (check_obj_exist_tag) {
if (identity_policy.has_partial_conditional(S3_EXISTING_OBJTAG))
identity_policy_s3_exist_tag = true;
}
if (identity_policy.has_partial_conditional(S3_RESOURCE_TAG) || identity_policy.has_partial_conditional_value(S3_RUNTIME_RESOURCE_VAL))
identity_policy_s3_resource_tag = true;
if (identity_policy_s3_exist_tag && identity_policy_s3_resource_tag) // check all policies till both are set to true
break;
}
}
bool session_policy_s3_exist_tag = false, session_policy_s3_resource_flag = false;
if (session_policies) {
for (auto& session_policy : session_policies.get()) {
if (check_obj_exist_tag) {
if (session_policy.has_partial_conditional(S3_EXISTING_OBJTAG))
session_policy_s3_exist_tag = true;
}
if (session_policy.has_partial_conditional(S3_RESOURCE_TAG) || session_policy.has_partial_conditional_value(S3_RUNTIME_RESOURCE_VAL))
session_policy_s3_resource_flag = true;
if (session_policy_s3_exist_tag && session_policy_s3_resource_flag)
break;
}
}
has_existing_obj_tag = iam_policy_s3_exist_tag || identity_policy_s3_exist_tag || session_policy_s3_exist_tag;
has_resource_tag = iam_policy_s3_resource_tag || identity_policy_s3_resource_tag || session_policy_s3_resource_flag;
return make_tuple(has_existing_obj_tag, has_resource_tag);
}
static std::tuple<bool, bool> rgw_check_policy_condition(const DoutPrefixProvider *dpp, req_state* s, bool check_obj_exist_tag=true) {
return rgw_check_policy_condition(dpp, s->iam_policy, s->iam_user_policies, s->session_policies, check_obj_exist_tag);
}
static void rgw_add_grant_to_iam_environment(rgw::IAM::Environment& e, req_state *s){
using header_pair_t = std::pair <const char*, const char*>;
static const std::initializer_list <header_pair_t> acl_header_conditionals {
{"HTTP_X_AMZ_GRANT_READ", "s3:x-amz-grant-read"},
{"HTTP_X_AMZ_GRANT_WRITE", "s3:x-amz-grant-write"},
{"HTTP_X_AMZ_GRANT_READ_ACP", "s3:x-amz-grant-read-acp"},
{"HTTP_X_AMZ_GRANT_WRITE_ACP", "s3:x-amz-grant-write-acp"},
{"HTTP_X_AMZ_GRANT_FULL_CONTROL", "s3:x-amz-grant-full-control"}
};
if (s->has_acl_header){
for (const auto& c: acl_header_conditionals){
auto hdr = s->info.env->get(c.first);
if(hdr) {
e.emplace(c.second, hdr);
}
}
}
}
void rgw_build_iam_environment(rgw::sal::Driver* driver,
req_state* s)
{
const auto& m = s->info.env->get_map();
auto t = ceph::real_clock::now();
s->env.emplace("aws:CurrentTime", std::to_string(ceph::real_clock::to_time_t(t)));
s->env.emplace("aws:EpochTime", ceph::to_iso_8601(t));
// TODO: This is fine for now, but once we have STS we'll need to
// look and see. Also this won't work with the IdentityApplier
// model, since we need to know the actual credential.
s->env.emplace("aws:PrincipalType", "User");
auto i = m.find("HTTP_REFERER");
if (i != m.end()) {
s->env.emplace("aws:Referer", i->second);
}
if (rgw_transport_is_secure(s->cct, *s->info.env)) {
s->env.emplace("aws:SecureTransport", "true");
}
const auto remote_addr_param = s->cct->_conf->rgw_remote_addr_param;
if (remote_addr_param.length()) {
i = m.find(remote_addr_param);
} else {
i = m.find("REMOTE_ADDR");
}
if (i != m.end()) {
const string* ip = &(i->second);
string temp;
if (remote_addr_param == "HTTP_X_FORWARDED_FOR") {
const auto comma = ip->find(',');
if (comma != string::npos) {
temp.assign(*ip, 0, comma);
ip = &temp;
}
}
s->env.emplace("aws:SourceIp", *ip);
}
i = m.find("HTTP_USER_AGENT"); {
if (i != m.end())
s->env.emplace("aws:UserAgent", i->second);
}
if (s->user) {
// What to do about aws::userid? One can have multiple access
// keys so that isn't really suitable. Do we have a durable
// identifier that can persist through name changes?
s->env.emplace("aws:username", s->user->get_id().id);
}
i = m.find("HTTP_X_AMZ_SECURITY_TOKEN");
if (i != m.end()) {
s->env.emplace("sts:authentication", "true");
} else {
s->env.emplace("sts:authentication", "false");
}
}
/*
* GET on CloudTiered objects is processed only when sent from the sync client.
* In all other cases, fail with `ERR_INVALID_OBJECT_STATE`.
*/
int handle_cloudtier_obj(rgw::sal::Attrs& attrs, bool sync_cloudtiered) {
int op_ret = 0;
auto attr_iter = attrs.find(RGW_ATTR_MANIFEST);
if (attr_iter != attrs.end()) {
RGWObjManifest m;
try {
decode(m, attr_iter->second);
if (m.get_tier_type() == "cloud-s3") {
if (!sync_cloudtiered) {
/* XXX: Instead send presigned redirect or read-through */
op_ret = -ERR_INVALID_OBJECT_STATE;
} else { // fetch object for sync and set cloud_tier attrs
bufferlist t, t_tier;
RGWObjTier tier_config;
m.get_tier_config(&tier_config);
t.append("cloud-s3");
attrs[RGW_ATTR_CLOUD_TIER_TYPE] = t;
encode(tier_config, t_tier);
attrs[RGW_ATTR_CLOUD_TIER_CONFIG] = t_tier;
}
}
} catch (const buffer::end_of_buffer&) {
// ignore empty manifest; it's not cloud-tiered
} catch (const std::exception& e) {
}
}
return op_ret;
}
void rgw_bucket_object_pre_exec(req_state *s)
{
if (s->expect_cont)
dump_continue(s);
dump_bucket_from_state(s);
}
// So! Now and then when we try to update bucket information, the
// bucket has changed during the course of the operation. (Or we have
// a cache consistency problem that Watch/Notify isn't ruling out
// completely.)
//
// When this happens, we need to update the bucket info and try
// again. We have, however, to try the right *part* again. We can't
// simply re-send, since that will obliterate the previous update.
//
// Thus, callers of this function should include everything that
// merges information to be changed into the bucket information as
// well as the call to set it.
//
// The called function must return an integer, negative on error. In
// general, they should just return op_ret.
namespace {
template<typename F>
int retry_raced_bucket_write(const DoutPrefixProvider *dpp, rgw::sal::Bucket* b, const F& f, optional_yield y) {
auto r = f();
for (auto i = 0u; i < 15u && r == -ECANCELED; ++i) {
r = b->try_refresh_info(dpp, nullptr, y);
if (r >= 0) {
r = f();
}
}
return r;
}
}
int RGWGetObj::verify_permission(optional_yield y)
{
s->object->set_atomic();
if (prefetch_data()) {
s->object->set_prefetch_data();
}
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (get_torrent) {
if (s->object->get_instance().empty()) {
action = rgw::IAM::s3GetObjectTorrent;
} else {
action = rgw::IAM::s3GetObjectVersionTorrent;
}
} else {
if (s->object->get_instance().empty()) {
action = rgw::IAM::s3GetObject;
} else {
action = rgw::IAM::s3GetObjectVersion;
}
}
if (!verify_object_permission(this, s, action)) {
return -EACCES;
}
if (s->bucket->get_info().obj_lock_enabled()) {
get_retention = verify_object_permission(this, s, rgw::IAM::s3GetObjectRetention);
get_legal_hold = verify_object_permission(this, s, rgw::IAM::s3GetObjectLegalHold);
}
return 0;
}
RGWOp::~RGWOp(){};
int RGWOp::verify_op_mask()
{
uint32_t required_mask = op_mask();
ldpp_dout(this, 20) << "required_mask= " << required_mask
<< " user.op_mask=" << s->user->get_info().op_mask << dendl;
if ((s->user->get_info().op_mask & required_mask) != required_mask) {
return -EPERM;
}
if (!s->system_request && (required_mask & RGW_OP_TYPE_MODIFY) && !driver->get_zone()->is_writeable()) {
ldpp_dout(this, 5) << "NOTICE: modify request to a read-only zone by a "
"non-system user, permission denied" << dendl;
return -EPERM;
}
return 0;
}
int RGWGetObjTags::verify_permission(optional_yield y)
{
auto iam_action = s->object->get_instance().empty()?
rgw::IAM::s3GetObjectTagging:
rgw::IAM::s3GetObjectVersionTagging;
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s,iam_action))
return -EACCES;
return 0;
}
void RGWGetObjTags::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetObjTags::execute(optional_yield y)
{
rgw::sal::Attrs attrs;
s->object->set_atomic();
op_ret = s->object->get_obj_attrs(y, this);
if (op_ret == 0){
attrs = s->object->get_attrs();
auto tags = attrs.find(RGW_ATTR_TAGS);
if(tags != attrs.end()){
has_tags = true;
tags_bl.append(tags->second);
}
}
send_response_data(tags_bl);
}
int RGWPutObjTags::verify_permission(optional_yield y)
{
auto iam_action = s->object->get_instance().empty() ?
rgw::IAM::s3PutObjectTagging:
rgw::IAM::s3PutObjectVersionTagging;
//Using buckets tags for authorization makes more sense.
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, true);
if (has_s3_existing_tag)
rgw_iam_add_objtags(this, s, true, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_object_permission(this, s,iam_action))
return -EACCES;
return 0;
}
void RGWPutObjTags::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
if (rgw::sal::Object::empty(s->object.get())){
op_ret= -EINVAL; // we only support tagging on existing objects
return;
}
s->object->set_atomic();
op_ret = s->object->modify_obj_attrs(RGW_ATTR_TAGS, tags_bl, y, this);
if (op_ret == -ECANCELED){
op_ret = -ERR_TAG_CONFLICT;
}
}
void RGWDeleteObjTags::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
int RGWDeleteObjTags::verify_permission(optional_yield y)
{
if (!rgw::sal::Object::empty(s->object.get())) {
auto iam_action = s->object->get_instance().empty() ?
rgw::IAM::s3DeleteObjectTagging:
rgw::IAM::s3DeleteObjectVersionTagging;
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s, iam_action))
return -EACCES;
}
return 0;
}
void RGWDeleteObjTags::execute(optional_yield y)
{
if (rgw::sal::Object::empty(s->object.get()))
return;
op_ret = s->object->delete_obj_attrs(this, RGW_ATTR_TAGS, y);
}
int RGWGetBucketTags::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetBucketTagging)) {
return -EACCES;
}
return 0;
}
void RGWGetBucketTags::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetBucketTags::execute(optional_yield y)
{
auto iter = s->bucket_attrs.find(RGW_ATTR_TAGS);
if (iter != s->bucket_attrs.end()) {
has_tags = true;
tags_bl.append(iter->second);
} else {
op_ret = -ERR_NO_SUCH_TAG_SET;
}
send_response_data(tags_bl);
}
int RGWPutBucketTags::verify_permission(optional_yield y) {
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketTagging);
}
void RGWPutBucketTags::execute(optional_yield y)
{
op_ret = get_params(this, y);
if (op_ret < 0)
return;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
rgw::sal::Attrs attrs = s->bucket->get_attrs();
attrs[RGW_ATTR_TAGS] = tags_bl;
return s->bucket->merge_and_store_attrs(this, attrs, y);
}, y);
}
void RGWDeleteBucketTags::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
int RGWDeleteBucketTags::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketTagging);
}
void RGWDeleteBucketTags::execute(optional_yield y)
{
bufferlist in_data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
rgw::sal::Attrs attrs = s->bucket->get_attrs();
attrs.erase(RGW_ATTR_TAGS);
op_ret = s->bucket->merge_and_store_attrs(this, attrs, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "RGWDeleteBucketTags() failed to remove RGW_ATTR_TAGS on bucket="
<< s->bucket->get_name()
<< " returned err= " << op_ret << dendl;
}
return op_ret;
}, y);
}
int RGWGetBucketReplication::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetReplicationConfiguration)) {
return -EACCES;
}
return 0;
}
void RGWGetBucketReplication::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetBucketReplication::execute(optional_yield y)
{
send_response_data();
}
int RGWPutBucketReplication::verify_permission(optional_yield y) {
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutReplicationConfiguration);
}
void RGWPutBucketReplication::execute(optional_yield y) {
op_ret = get_params(y);
if (op_ret < 0)
return;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
auto sync_policy = (s->bucket->get_info().sync_policy ? *s->bucket->get_info().sync_policy : rgw_sync_policy_info());
for (auto& group : sync_policy_groups) {
sync_policy.groups[group.id] = group;
}
s->bucket->get_info().set_sync_policy(std::move(sync_policy));
int ret = s->bucket->put_info(this, false, real_time(), y);
if (ret < 0) {
ldpp_dout(this, 0) << "ERROR: put_bucket_instance_info (bucket=" << s->bucket << ") returned ret=" << ret << dendl;
return ret;
}
return 0;
}, y);
}
void RGWDeleteBucketReplication::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
int RGWDeleteBucketReplication::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3DeleteReplicationConfiguration);
}
void RGWDeleteBucketReplication::execute(optional_yield y)
{
bufferlist in_data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
if (!s->bucket->get_info().sync_policy) {
return 0;
}
rgw_sync_policy_info sync_policy = *s->bucket->get_info().sync_policy;
update_sync_policy(&sync_policy);
s->bucket->get_info().set_sync_policy(std::move(sync_policy));
int ret = s->bucket->put_info(this, false, real_time(), y);
if (ret < 0) {
ldpp_dout(this, 0) << "ERROR: put_bucket_instance_info (bucket=" << s->bucket << ") returned ret=" << ret << dendl;
return ret;
}
return 0;
}, y);
}
int RGWOp::do_aws4_auth_completion()
{
ldpp_dout(this, 5) << "NOTICE: call to do_aws4_auth_completion" << dendl;
if (s->auth.completer) {
if (!s->auth.completer->complete()) {
return -ERR_AMZ_CONTENT_SHA256_MISMATCH;
} else {
ldpp_dout(this, 10) << "v4 auth ok -- do_aws4_auth_completion" << dendl;
}
/* TODO(rzarzynski): yes, we're really called twice on PUTs. Only first
* call passes, so we disable second one. This is old behaviour, sorry!
* Plan for tomorrow: seek and destroy. */
s->auth.completer = nullptr;
}
return 0;
}
int RGWOp::init_quota()
{
/* no quota enforcement for system requests */
if (s->system_request)
return 0;
/* init quota related stuff */
if (!(s->user->get_info().op_mask & RGW_OP_TYPE_MODIFY)) {
return 0;
}
/* Need a bucket to get quota */
if (rgw::sal::Bucket::empty(s->bucket.get())) {
return 0;
}
std::unique_ptr<rgw::sal::User> owner_user =
driver->get_user(s->bucket->get_info().owner);
rgw::sal::User* user;
if (s->user->get_id() == s->bucket_owner.get_id()) {
user = s->user.get();
} else {
int r = owner_user->load_user(this, s->yield);
if (r < 0)
return r;
user = owner_user.get();
}
driver->get_quota(quota);
if (s->bucket->get_info().quota.enabled) {
quota.bucket_quota = s->bucket->get_info().quota;
} else if (user->get_info().quota.bucket_quota.enabled) {
quota.bucket_quota = user->get_info().quota.bucket_quota;
}
if (user->get_info().quota.user_quota.enabled) {
quota.user_quota = user->get_info().quota.user_quota;
}
return 0;
}
static bool validate_cors_rule_method(const DoutPrefixProvider *dpp, RGWCORSRule *rule, const char *req_meth) {
uint8_t flags = 0;
if (!req_meth) {
ldpp_dout(dpp, 5) << "req_meth is null" << dendl;
return false;
}
if (strcmp(req_meth, "GET") == 0) flags = RGW_CORS_GET;
else if (strcmp(req_meth, "POST") == 0) flags = RGW_CORS_POST;
else if (strcmp(req_meth, "PUT") == 0) flags = RGW_CORS_PUT;
else if (strcmp(req_meth, "DELETE") == 0) flags = RGW_CORS_DELETE;
else if (strcmp(req_meth, "HEAD") == 0) flags = RGW_CORS_HEAD;
if (rule->get_allowed_methods() & flags) {
ldpp_dout(dpp, 10) << "Method " << req_meth << " is supported" << dendl;
} else {
ldpp_dout(dpp, 5) << "Method " << req_meth << " is not supported" << dendl;
return false;
}
return true;
}
static bool validate_cors_rule_header(const DoutPrefixProvider *dpp, RGWCORSRule *rule, const char *req_hdrs) {
if (req_hdrs) {
vector<string> hdrs;
get_str_vec(req_hdrs, hdrs);
for (const auto& hdr : hdrs) {
if (!rule->is_header_allowed(hdr.c_str(), hdr.length())) {
ldpp_dout(dpp, 5) << "Header " << hdr << " is not registered in this rule" << dendl;
return false;
}
}
}
return true;
}
int RGWOp::read_bucket_cors()
{
bufferlist bl;
map<string, bufferlist>::iterator aiter = s->bucket_attrs.find(RGW_ATTR_CORS);
if (aiter == s->bucket_attrs.end()) {
ldpp_dout(this, 20) << "no CORS configuration attr found" << dendl;
cors_exist = false;
return 0; /* no CORS configuration found */
}
cors_exist = true;
bl = aiter->second;
auto iter = bl.cbegin();
try {
bucket_cors.decode(iter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: could not decode CORS, caught buffer::error" << dendl;
return -EIO;
}
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
RGWCORSConfiguration_S3 *s3cors = static_cast<RGWCORSConfiguration_S3 *>(&bucket_cors);
ldpp_dout(this, 15) << "Read RGWCORSConfiguration";
s3cors->to_xml(*_dout);
*_dout << dendl;
}
return 0;
}
/** CORS 6.2.6.
* If any of the header field-names is not a ASCII case-insensitive match for
* any of the values in list of headers do not set any additional headers and
* terminate this set of steps.
* */
static void get_cors_response_headers(const DoutPrefixProvider *dpp, RGWCORSRule *rule, const char *req_hdrs, string& hdrs, string& exp_hdrs, unsigned *max_age) {
if (req_hdrs) {
list<string> hl;
get_str_list(req_hdrs, hl);
for(list<string>::iterator it = hl.begin(); it != hl.end(); ++it) {
if (!rule->is_header_allowed((*it).c_str(), (*it).length())) {
ldpp_dout(dpp, 5) << "Header " << (*it) << " is not registered in this rule" << dendl;
} else {
if (hdrs.length() > 0) hdrs.append(",");
hdrs.append((*it));
}
}
}
rule->format_exp_headers(exp_hdrs);
*max_age = rule->get_max_age();
}
/**
* Generate the CORS header response
*
* This is described in the CORS standard, section 6.2.
*/
bool RGWOp::generate_cors_headers(string& origin, string& method, string& headers, string& exp_headers, unsigned *max_age)
{
/* CORS 6.2.1. */
const char *orig = s->info.env->get("HTTP_ORIGIN");
if (!orig) {
return false;
}
/* Custom: */
origin = orig;
int temp_op_ret = read_bucket_cors();
if (temp_op_ret < 0) {
op_ret = temp_op_ret;
return false;
}
if (!cors_exist) {
ldpp_dout(this, 2) << "No CORS configuration set yet for this bucket" << dendl;
return false;
}
/* CORS 6.2.2. */
RGWCORSRule *rule = bucket_cors.host_name_rule(orig);
if (!rule)
return false;
/*
* Set the Allowed-Origin header to a asterisk if this is allowed in the rule
* and no Authorization was send by the client
*
* The origin parameter specifies a URI that may access the resource. The browser must enforce this.
* For requests without credentials, the server may specify "*" as a wildcard,
* thereby allowing any origin to access the resource.
*/
const char *authorization = s->info.env->get("HTTP_AUTHORIZATION");
if (!authorization && rule->has_wildcard_origin())
origin = "*";
/* CORS 6.2.3. */
const char *req_meth = s->info.env->get("HTTP_ACCESS_CONTROL_REQUEST_METHOD");
if (!req_meth) {
req_meth = s->info.method;
}
if (req_meth) {
method = req_meth;
/* CORS 6.2.5. */
if (!validate_cors_rule_method(this, rule, req_meth)) {
return false;
}
}
/* CORS 6.2.4. */
const char *req_hdrs = s->info.env->get("HTTP_ACCESS_CONTROL_REQUEST_HEADERS");
/* CORS 6.2.6. */
get_cors_response_headers(this, rule, req_hdrs, headers, exp_headers, max_age);
return true;
}
int rgw_policy_from_attrset(const DoutPrefixProvider *dpp, CephContext *cct, map<string, bufferlist>& attrset, RGWAccessControlPolicy *policy)
{
map<string, bufferlist>::iterator aiter = attrset.find(RGW_ATTR_ACL);
if (aiter == attrset.end())
return -EIO;
bufferlist& bl = aiter->second;
auto iter = bl.cbegin();
try {
policy->decode(iter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: could not decode policy, caught buffer::error" << dendl;
return -EIO;
}
if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
RGWAccessControlPolicy_S3 *s3policy = static_cast<RGWAccessControlPolicy_S3 *>(policy);
ldpp_dout(dpp, 15) << __func__ << " Read AccessControlPolicy";
s3policy->to_xml(*_dout);
*_dout << dendl;
}
return 0;
}
int RGWGetObj::read_user_manifest_part(rgw::sal::Bucket* bucket,
const rgw_bucket_dir_entry& ent,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
const off_t start_ofs,
const off_t end_ofs,
bool swift_slo)
{
ldpp_dout(this, 20) << "user manifest obj=" << ent.key.name
<< "[" << ent.key.instance << "]" << dendl;
RGWGetObj_CB cb(this);
RGWGetObj_Filter* filter = &cb;
boost::optional<RGWGetObj_Decompress> decompress;
int64_t cur_ofs = start_ofs;
int64_t cur_end = end_ofs;
std::unique_ptr<rgw::sal::Object> part = bucket->get_object(ent.key);
RGWAccessControlPolicy obj_policy(s->cct);
ldpp_dout(this, 20) << "reading obj=" << part << " ofs=" << cur_ofs
<< " end=" << cur_end << dendl;
part->set_atomic();
part->set_prefetch_data();
std::unique_ptr<rgw::sal::Object::ReadOp> read_op = part->get_read_op();
if (!swift_slo) {
/* SLO etag is optional */
read_op->params.if_match = ent.meta.etag.c_str();
}
op_ret = read_op->prepare(s->yield, this);
if (op_ret < 0)
return op_ret;
op_ret = part->range_to_ofs(ent.meta.accounted_size, cur_ofs, cur_end);
if (op_ret < 0)
return op_ret;
bool need_decompress;
op_ret = rgw_compression_info_from_attrset(part->get_attrs(), need_decompress, cs_info);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to decode compression info" << dendl;
return -EIO;
}
if (need_decompress)
{
if (cs_info.orig_size != ent.meta.accounted_size) {
// hmm.. something wrong, object not as expected, abort!
ldpp_dout(this, 0) << "ERROR: expected cs_info.orig_size=" << cs_info.orig_size
<< ", actual read size=" << ent.meta.size << dendl;
return -EIO;
}
decompress.emplace(s->cct, &cs_info, partial_content, filter);
filter = &*decompress;
}
else
{
if (part->get_obj_size() != ent.meta.size) {
// hmm.. something wrong, object not as expected, abort!
ldpp_dout(this, 0) << "ERROR: expected obj_size=" << part->get_obj_size()
<< ", actual read size=" << ent.meta.size << dendl;
return -EIO;
}
}
op_ret = rgw_policy_from_attrset(s, s->cct, part->get_attrs(), &obj_policy);
if (op_ret < 0)
return op_ret;
/* We can use global user_acl because LOs cannot have segments
* stored inside different accounts. */
if (s->system_request) {
ldpp_dout(this, 2) << "overriding permissions due to system operation" << dendl;
} else if (s->auth.identity->is_admin_of(s->user->get_id())) {
ldpp_dout(this, 2) << "overriding permissions due to admin operation" << dendl;
} else if (!verify_object_permission(this, s, part->get_obj(), s->user_acl.get(),
bucket_acl, &obj_policy, bucket_policy,
s->iam_user_policies, s->session_policies, action)) {
return -EPERM;
}
if (ent.meta.size == 0) {
return 0;
}
perfcounter->inc(l_rgw_get_b, cur_end - cur_ofs);
filter->fixup_range(cur_ofs, cur_end);
op_ret = read_op->iterate(this, cur_ofs, cur_end, filter, s->yield);
if (op_ret >= 0)
op_ret = filter->flush();
return op_ret;
}
static int iterate_user_manifest_parts(const DoutPrefixProvider *dpp,
CephContext * const cct,
rgw::sal::Driver* const driver,
const off_t ofs,
const off_t end,
rgw::sal::Bucket* bucket,
const string& obj_prefix,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
uint64_t * const ptotal_len,
uint64_t * const pobj_size,
string * const pobj_sum,
int (*cb)(rgw::sal::Bucket* bucket,
const rgw_bucket_dir_entry& ent,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
off_t start_ofs,
off_t end_ofs,
void *param,
bool swift_slo),
void * const cb_param,
optional_yield y)
{
uint64_t obj_ofs = 0, len_count = 0;
bool found_start = false, found_end = false, handled_end = false;
string delim;
utime_t start_time = ceph_clock_now();
rgw::sal::Bucket::ListParams params;
params.prefix = obj_prefix;
params.delim = delim;
rgw::sal::Bucket::ListResults results;
MD5 etag_sum;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
etag_sum.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
do {
static constexpr auto MAX_LIST_OBJS = 100u;
int r = bucket->list(dpp, params, MAX_LIST_OBJS, results, y);
if (r < 0) {
return r;
}
for (rgw_bucket_dir_entry& ent : results.objs) {
const uint64_t cur_total_len = obj_ofs;
const uint64_t obj_size = ent.meta.accounted_size;
uint64_t start_ofs = 0, end_ofs = obj_size;
if ((ptotal_len || cb) && !found_start && cur_total_len + obj_size > (uint64_t)ofs) {
start_ofs = ofs - obj_ofs;
found_start = true;
}
obj_ofs += obj_size;
if (pobj_sum) {
etag_sum.Update((const unsigned char *)ent.meta.etag.c_str(),
ent.meta.etag.length());
}
if ((ptotal_len || cb) && !found_end && obj_ofs > (uint64_t)end) {
end_ofs = end - cur_total_len + 1;
found_end = true;
}
perfcounter->tinc(l_rgw_get_lat,
(ceph_clock_now() - start_time));
if (found_start && !handled_end) {
len_count += end_ofs - start_ofs;
if (cb) {
r = cb(bucket, ent, bucket_acl, bucket_policy, start_ofs, end_ofs,
cb_param, false /* swift_slo */);
if (r < 0) {
return r;
}
}
}
handled_end = found_end;
start_time = ceph_clock_now();
}
} while (results.is_truncated);
if (ptotal_len) {
*ptotal_len = len_count;
}
if (pobj_size) {
*pobj_size = obj_ofs;
}
if (pobj_sum) {
complete_etag(etag_sum, pobj_sum);
}
return 0;
}
struct rgw_slo_part {
RGWAccessControlPolicy *bucket_acl = nullptr;
Policy* bucket_policy = nullptr;
rgw::sal::Bucket* bucket;
string obj_name;
uint64_t size = 0;
string etag;
};
static int iterate_slo_parts(const DoutPrefixProvider *dpp,
CephContext *cct,
rgw::sal::Driver* driver,
off_t ofs,
off_t end,
map<uint64_t, rgw_slo_part>& slo_parts,
int (*cb)(rgw::sal::Bucket* bucket,
const rgw_bucket_dir_entry& ent,
RGWAccessControlPolicy *bucket_acl,
const boost::optional<Policy>& bucket_policy,
off_t start_ofs,
off_t end_ofs,
void *param,
bool swift_slo),
void *cb_param)
{
bool found_start = false, found_end = false;
if (slo_parts.empty()) {
return 0;
}
utime_t start_time = ceph_clock_now();
map<uint64_t, rgw_slo_part>::iterator iter = slo_parts.upper_bound(ofs);
if (iter != slo_parts.begin()) {
--iter;
}
uint64_t obj_ofs = iter->first;
for (; iter != slo_parts.end() && !found_end; ++iter) {
rgw_slo_part& part = iter->second;
rgw_bucket_dir_entry ent;
ent.key.name = part.obj_name;
ent.meta.accounted_size = ent.meta.size = part.size;
ent.meta.etag = part.etag;
uint64_t cur_total_len = obj_ofs;
uint64_t start_ofs = 0, end_ofs = ent.meta.size - 1;
if (!found_start && cur_total_len + ent.meta.size > (uint64_t)ofs) {
start_ofs = ofs - obj_ofs;
found_start = true;
}
obj_ofs += ent.meta.size;
if (!found_end && obj_ofs > (uint64_t)end) {
end_ofs = end - cur_total_len;
found_end = true;
}
perfcounter->tinc(l_rgw_get_lat,
(ceph_clock_now() - start_time));
if (found_start) {
if (cb) {
ldpp_dout(dpp, 20) << "iterate_slo_parts()"
<< " obj=" << part.obj_name
<< " start_ofs=" << start_ofs
<< " end_ofs=" << end_ofs
<< dendl;
// SLO is a Swift thing, and Swift has no knowledge of S3 Policies.
int r = cb(part.bucket, ent, part.bucket_acl,
(part.bucket_policy ?
boost::optional<Policy>(*part.bucket_policy) : none),
start_ofs, end_ofs, cb_param, true /* swift_slo */);
if (r < 0)
return r;
}
}
start_time = ceph_clock_now();
}
return 0;
}
static int get_obj_user_manifest_iterate_cb(rgw::sal::Bucket* bucket,
const rgw_bucket_dir_entry& ent,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
const off_t start_ofs,
const off_t end_ofs,
void * const param,
bool swift_slo = false)
{
RGWGetObj *op = static_cast<RGWGetObj *>(param);
return op->read_user_manifest_part(
bucket, ent, bucket_acl, bucket_policy, start_ofs, end_ofs, swift_slo);
}
int RGWGetObj::handle_user_manifest(const char *prefix, optional_yield y)
{
const std::string_view prefix_view(prefix);
ldpp_dout(this, 2) << "RGWGetObj::handle_user_manifest() prefix="
<< prefix_view << dendl;
const size_t pos = prefix_view.find('/');
if (pos == string::npos) {
return -EINVAL;
}
const std::string bucket_name = url_decode(prefix_view.substr(0, pos));
const std::string obj_prefix = url_decode(prefix_view.substr(pos + 1));
RGWAccessControlPolicy _bucket_acl(s->cct);
RGWAccessControlPolicy *bucket_acl;
boost::optional<Policy> _bucket_policy;
boost::optional<Policy>* bucket_policy;
RGWBucketInfo bucket_info;
std::unique_ptr<rgw::sal::Bucket> ubucket;
rgw::sal::Bucket* pbucket = NULL;
int r = 0;
if (bucket_name.compare(s->bucket->get_name()) != 0) {
map<string, bufferlist> bucket_attrs;
r = driver->get_bucket(this, s->user.get(), s->user->get_tenant(), bucket_name, &ubucket, y);
if (r < 0) {
ldpp_dout(this, 0) << "could not get bucket info for bucket="
<< bucket_name << dendl;
return r;
}
bucket_acl = &_bucket_acl;
r = read_bucket_policy(this, driver, s, ubucket->get_info(), bucket_attrs, bucket_acl, ubucket->get_key(), y);
if (r < 0) {
ldpp_dout(this, 0) << "failed to read bucket policy" << dendl;
return r;
}
_bucket_policy = get_iam_policy_from_attr(s->cct, bucket_attrs, s->user->get_tenant());
bucket_policy = &_bucket_policy;
pbucket = ubucket.get();
} else {
pbucket = s->bucket.get();
bucket_acl = s->bucket_acl.get();
bucket_policy = &s->iam_policy;
}
/* dry run to find out:
* - total length (of the parts we are going to send to client),
* - overall DLO's content size,
* - md5 sum of overall DLO's content (for etag of Swift API). */
r = iterate_user_manifest_parts(this, s->cct, driver, ofs, end,
pbucket, obj_prefix, bucket_acl, *bucket_policy,
nullptr, &s->obj_size, &lo_etag,
nullptr /* cb */, nullptr /* cb arg */, y);
if (r < 0) {
return r;
}
s->object->set_obj_size(s->obj_size);
r = s->object->range_to_ofs(s->obj_size, ofs, end);
if (r < 0) {
return r;
}
r = iterate_user_manifest_parts(this, s->cct, driver, ofs, end,
pbucket, obj_prefix, bucket_acl, *bucket_policy,
&total_len, nullptr, nullptr,
nullptr, nullptr, y);
if (r < 0) {
return r;
}
if (!get_data) {
bufferlist bl;
send_response_data(bl, 0, 0);
return 0;
}
r = iterate_user_manifest_parts(this, s->cct, driver, ofs, end,
pbucket, obj_prefix, bucket_acl, *bucket_policy,
nullptr, nullptr, nullptr,
get_obj_user_manifest_iterate_cb, (void *)this, y);
if (r < 0) {
return r;
}
if (!total_len) {
bufferlist bl;
send_response_data(bl, 0, 0);
}
return r;
}
int RGWGetObj::handle_slo_manifest(bufferlist& bl, optional_yield y)
{
RGWSLOInfo slo_info;
auto bliter = bl.cbegin();
try {
decode(slo_info, bliter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode slo manifest" << dendl;
return -EIO;
}
ldpp_dout(this, 2) << "RGWGetObj::handle_slo_manifest()" << dendl;
vector<RGWAccessControlPolicy> allocated_acls;
map<string, pair<RGWAccessControlPolicy *, boost::optional<Policy>>> policies;
map<string, std::unique_ptr<rgw::sal::Bucket>> buckets;
map<uint64_t, rgw_slo_part> slo_parts;
MD5 etag_sum;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
etag_sum.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
total_len = 0;
for (const auto& entry : slo_info.entries) {
const string& path = entry.path;
/* If the path starts with slashes, strip them all. */
const size_t pos_init = path.find_first_not_of('/');
/* According to the documentation of std::string::find following check
* is not necessary as we should get the std::string::npos propagation
* here. This might be true with the accuracy to implementation's bugs.
* See following question on SO:
* http://stackoverflow.com/questions/1011790/why-does-stdstring-findtext-stdstringnpos-not-return-npos
*/
if (pos_init == string::npos) {
return -EINVAL;
}
const size_t pos_sep = path.find('/', pos_init);
if (pos_sep == string::npos) {
return -EINVAL;
}
string bucket_name = path.substr(pos_init, pos_sep - pos_init);
string obj_name = path.substr(pos_sep + 1);
rgw::sal::Bucket* bucket;
RGWAccessControlPolicy *bucket_acl;
Policy* bucket_policy;
if (bucket_name.compare(s->bucket->get_name()) != 0) {
const auto& piter = policies.find(bucket_name);
if (piter != policies.end()) {
bucket_acl = piter->second.first;
bucket_policy = piter->second.second.get_ptr();
bucket = buckets[bucket_name].get();
} else {
allocated_acls.push_back(RGWAccessControlPolicy(s->cct));
RGWAccessControlPolicy& _bucket_acl = allocated_acls.back();
std::unique_ptr<rgw::sal::Bucket> tmp_bucket;
int r = driver->get_bucket(this, s->user.get(), s->user->get_tenant(), bucket_name, &tmp_bucket, y);
if (r < 0) {
ldpp_dout(this, 0) << "could not get bucket info for bucket="
<< bucket_name << dendl;
return r;
}
bucket = tmp_bucket.get();
bucket_acl = &_bucket_acl;
r = read_bucket_policy(this, driver, s, tmp_bucket->get_info(), tmp_bucket->get_attrs(), bucket_acl,
tmp_bucket->get_key(), y);
if (r < 0) {
ldpp_dout(this, 0) << "failed to read bucket ACL for bucket "
<< bucket << dendl;
return r;
}
auto _bucket_policy = get_iam_policy_from_attr(
s->cct, tmp_bucket->get_attrs(), tmp_bucket->get_tenant());
bucket_policy = _bucket_policy.get_ptr();
buckets[bucket_name].swap(tmp_bucket);
policies[bucket_name] = make_pair(bucket_acl, _bucket_policy);
}
} else {
bucket = s->bucket.get();
bucket_acl = s->bucket_acl.get();
bucket_policy = s->iam_policy.get_ptr();
}
rgw_slo_part part;
part.bucket_acl = bucket_acl;
part.bucket_policy = bucket_policy;
part.bucket = bucket;
part.obj_name = obj_name;
part.size = entry.size_bytes;
part.etag = entry.etag;
ldpp_dout(this, 20) << "slo_part: bucket=" << part.bucket
<< " obj=" << part.obj_name
<< " size=" << part.size
<< " etag=" << part.etag
<< dendl;
etag_sum.Update((const unsigned char *)entry.etag.c_str(),
entry.etag.length());
slo_parts[total_len] = part;
total_len += part.size;
} /* foreach entry */
complete_etag(etag_sum, &lo_etag);
s->obj_size = slo_info.total_size;
s->object->set_obj_size(slo_info.total_size);
ldpp_dout(this, 20) << "s->obj_size=" << s->obj_size << dendl;
int r = s->object->range_to_ofs(total_len, ofs, end);
if (r < 0) {
return r;
}
total_len = end - ofs + 1;
ldpp_dout(this, 20) << "Requested: ofs=" << ofs
<< " end=" << end
<< " total=" << total_len
<< dendl;
r = iterate_slo_parts(this, s->cct, driver, ofs, end, slo_parts,
get_obj_user_manifest_iterate_cb, (void *)this);
if (r < 0) {
return r;
}
return 0;
}
int RGWGetObj::get_data_cb(bufferlist& bl, off_t bl_ofs, off_t bl_len)
{
/* garbage collection related handling:
* defer_gc disabled for https://tracker.ceph.com/issues/47866 */
return send_response_data(bl, bl_ofs, bl_len);
}
int RGWGetObj::get_lua_filter(std::unique_ptr<RGWGetObj_Filter>* filter, RGWGetObj_Filter* cb) {
std::string script;
const auto rc = rgw::lua::read_script(s, s->penv.lua.manager.get(), s->bucket_tenant, s->yield, rgw::lua::context::getData, script);
if (rc == -ENOENT) {
// no script, nothing to do
return 0;
} else if (rc < 0) {
ldpp_dout(this, 5) << "WARNING: failed to read data script. error: " << rc << dendl;
return rc;
}
filter->reset(new rgw::lua::RGWGetObjFilter(s, script, cb));
return 0;
}
bool RGWGetObj::prefetch_data()
{
/* HEAD request, stop prefetch*/
if (!get_data || s->info.env->exists("HTTP_X_RGW_AUTH")) {
return false;
}
range_str = s->info.env->get("HTTP_RANGE");
// TODO: add range prefetch
if (range_str) {
parse_range();
return false;
}
return get_data;
}
void RGWGetObj::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
static inline void rgw_cond_decode_objtags(
req_state *s,
const std::map<std::string, buffer::list> &attrs)
{
const auto& tags = attrs.find(RGW_ATTR_TAGS);
if (tags != attrs.end()) {
try {
bufferlist::const_iterator iter{&tags->second};
s->tagset.decode(iter);
} catch (buffer::error& err) {
ldpp_dout(s, 0)
<< "ERROR: caught buffer::error, couldn't decode TagSet" << dendl;
}
}
}
void RGWGetObj::execute(optional_yield y)
{
bufferlist bl;
gc_invalidate_time = ceph_clock_now();
gc_invalidate_time += (s->cct->_conf->rgw_gc_obj_min_wait / 2);
bool need_decompress = false;
int64_t ofs_x = 0, end_x = 0;
bool encrypted = false;
RGWGetObj_CB cb(this);
RGWGetObj_Filter* filter = (RGWGetObj_Filter *)&cb;
boost::optional<RGWGetObj_Decompress> decompress;
#ifdef WITH_ARROW_FLIGHT
boost::optional<rgw::flight::FlightGetObj_Filter> flight_filter;
#endif
std::unique_ptr<RGWGetObj_Filter> decrypt;
std::unique_ptr<RGWGetObj_Filter> run_lua;
map<string, bufferlist>::iterator attr_iter;
perfcounter->inc(l_rgw_get);
std::unique_ptr<rgw::sal::Object::ReadOp> read_op(s->object->get_read_op());
op_ret = get_params(y);
if (op_ret < 0)
goto done_err;
op_ret = init_common();
if (op_ret < 0)
goto done_err;
read_op->params.mod_ptr = mod_ptr;
read_op->params.unmod_ptr = unmod_ptr;
read_op->params.high_precision_time = s->system_request; /* system request need to use high precision time */
read_op->params.mod_zone_id = mod_zone_id;
read_op->params.mod_pg_ver = mod_pg_ver;
read_op->params.if_match = if_match;
read_op->params.if_nomatch = if_nomatch;
read_op->params.lastmod = &lastmod;
op_ret = read_op->prepare(s->yield, this);
if (op_ret < 0)
goto done_err;
version_id = s->object->get_instance();
s->obj_size = s->object->get_obj_size();
attrs = s->object->get_attrs();
/* STAT ops don't need data, and do no i/o */
if (get_type() == RGW_OP_STAT_OBJ) {
return;
}
if (s->info.env->exists("HTTP_X_RGW_AUTH")) {
op_ret = 0;
goto done_err;
}
/* start gettorrent */
if (get_torrent) {
attr_iter = attrs.find(RGW_ATTR_CRYPT_MODE);
if (attr_iter != attrs.end() && attr_iter->second.to_str() == "SSE-C-AES256") {
ldpp_dout(this, 0) << "ERROR: torrents are not supported for objects "
"encrypted with SSE-C" << dendl;
op_ret = -EINVAL;
goto done_err;
}
// read torrent info from attr
bufferlist torrentbl;
op_ret = rgw_read_torrent_file(this, s->object.get(), torrentbl, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get_torrent_file ret= " << op_ret
<< dendl;
goto done_err;
}
op_ret = send_response_data(torrentbl, 0, torrentbl.length());
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to send_response_data ret= " << op_ret << dendl;
goto done_err;
}
return;
}
/* end gettorrent */
// run lua script on decompressed and decrypted data - first filter runs last
op_ret = get_lua_filter(&run_lua, filter);
if (run_lua != nullptr) {
filter = run_lua.get();
}
if (op_ret < 0) {
goto done_err;
}
#ifdef WITH_ARROW_FLIGHT
if (s->penv.flight_store) {
if (ofs == 0) {
// insert a GetObj_Filter to monitor and create flight
flight_filter.emplace(s, filter);
filter = &*flight_filter;
}
} else {
ldpp_dout(this, 0) << "ERROR: flight_store not created in " << __func__ << dendl;
}
#endif
op_ret = rgw_compression_info_from_attrset(attrs, need_decompress, cs_info);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to decode compression info, cannot decompress" << dendl;
goto done_err;
}
// where encryption and compression are combined, compression was applied to
// the data before encryption. if the system header rgwx-skip-decrypt is
// present, we have to skip the decompression filter too
encrypted = attrs.count(RGW_ATTR_CRYPT_MODE);
if (need_decompress && (!encrypted || !skip_decrypt)) {
s->obj_size = cs_info.orig_size;
s->object->set_obj_size(cs_info.orig_size);
decompress.emplace(s->cct, &cs_info, partial_content, filter);
filter = &*decompress;
}
attr_iter = attrs.find(RGW_ATTR_OBJ_REPLICATION_TRACE);
if (attr_iter != attrs.end()) {
try {
std::vector<rgw_zone_set_entry> zones;
auto p = attr_iter->second.cbegin();
decode(zones, p);
for (const auto& zone: zones) {
if (zone == dst_zone_trace) {
op_ret = -ERR_NOT_MODIFIED;
ldpp_dout(this, 4) << "Object already has been copied to this destination. Returning "
<< op_ret << dendl;
goto done_err;
}
}
} catch (const buffer::error&) {}
}
if (get_type() == RGW_OP_GET_OBJ && get_data) {
op_ret = handle_cloudtier_obj(attrs, sync_cloudtiered);
if (op_ret < 0) {
ldpp_dout(this, 4) << "Cannot get cloud tiered object: " << *s->object
<<". Failing with " << op_ret << dendl;
if (op_ret == -ERR_INVALID_OBJECT_STATE) {
s->err.message = "This object was transitioned to cloud-s3";
}
goto done_err;
}
}
attr_iter = attrs.find(RGW_ATTR_USER_MANIFEST);
if (attr_iter != attrs.end() && !skip_manifest) {
op_ret = handle_user_manifest(attr_iter->second.c_str(), y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to handle user manifest ret="
<< op_ret << dendl;
goto done_err;
}
return;
}
attr_iter = attrs.find(RGW_ATTR_SLO_MANIFEST);
if (attr_iter != attrs.end() && !skip_manifest) {
is_slo = true;
op_ret = handle_slo_manifest(attr_iter->second, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to handle slo manifest ret=" << op_ret
<< dendl;
goto done_err;
}
return;
}
// for range requests with obj size 0
if (range_str && !(s->obj_size)) {
total_len = 0;
op_ret = -ERANGE;
goto done_err;
}
op_ret = s->object->range_to_ofs(s->obj_size, ofs, end);
if (op_ret < 0)
goto done_err;
total_len = (ofs <= end ? end + 1 - ofs : 0);
ofs_x = ofs;
end_x = end;
filter->fixup_range(ofs_x, end_x);
/* Check whether the object has expired. Swift API documentation
* stands that we should return 404 Not Found in such case. */
if (need_object_expiration() && s->object->is_expired()) {
op_ret = -ENOENT;
goto done_err;
}
/* Decode S3 objtags, if any */
rgw_cond_decode_objtags(s, attrs);
start = ofs;
attr_iter = attrs.find(RGW_ATTR_MANIFEST);
op_ret = this->get_decrypt_filter(&decrypt, filter,
attr_iter != attrs.end() ? &(attr_iter->second) : nullptr);
if (decrypt != nullptr) {
filter = decrypt.get();
filter->fixup_range(ofs_x, end_x);
}
if (op_ret < 0) {
goto done_err;
}
if (!get_data || ofs > end) {
send_response_data(bl, 0, 0);
return;
}
perfcounter->inc(l_rgw_get_b, end - ofs);
op_ret = read_op->iterate(this, ofs_x, end_x, filter, s->yield);
if (op_ret >= 0)
op_ret = filter->flush();
perfcounter->tinc(l_rgw_get_lat, s->time_elapsed());
if (op_ret < 0) {
goto done_err;
}
op_ret = send_response_data(bl, 0, 0);
if (op_ret < 0) {
goto done_err;
}
return;
done_err:
send_response_data_error(y);
}
int RGWGetObj::init_common()
{
if (range_str) {
/* range parsed error when prefetch */
if (!range_parsed) {
int r = parse_range();
if (r < 0)
return r;
}
}
if (if_mod) {
if (parse_time(if_mod, &mod_time) < 0)
return -EINVAL;
mod_ptr = &mod_time;
}
if (if_unmod) {
if (parse_time(if_unmod, &unmod_time) < 0)
return -EINVAL;
unmod_ptr = &unmod_time;
}
return 0;
}
int RGWListBuckets::verify_permission(optional_yield y)
{
rgw::Partition partition = rgw::Partition::aws;
rgw::Service service = rgw::Service::s3;
string tenant;
if (s->auth.identity->get_identity_type() == TYPE_ROLE) {
tenant = s->auth.identity->get_role_tenant();
} else {
tenant = s->user->get_tenant();
}
if (!verify_user_permission(this, s, ARN(partition, service, "", tenant, "*"), rgw::IAM::s3ListAllMyBuckets, false)) {
return -EACCES;
}
return 0;
}
int RGWGetUsage::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
return 0;
}
void RGWListBuckets::execute(optional_yield y)
{
bool done;
bool started = false;
uint64_t total_count = 0;
const uint64_t max_buckets = s->cct->_conf->rgw_list_buckets_max_chunk;
op_ret = get_params(y);
if (op_ret < 0) {
goto send_end;
}
if (supports_account_metadata()) {
op_ret = s->user->read_attrs(this, s->yield);
if (op_ret < 0) {
goto send_end;
}
}
is_truncated = false;
do {
rgw::sal::BucketList buckets;
uint64_t read_count;
if (limit >= 0) {
read_count = min(limit - total_count, max_buckets);
} else {
read_count = max_buckets;
}
op_ret = s->user->list_buckets(this, marker, end_marker, read_count, should_get_stats(), buckets, y);
if (op_ret < 0) {
/* hmm.. something wrong here.. the user was authenticated, so it
should exist */
ldpp_dout(this, 10) << "WARNING: failed on rgw_get_user_buckets uid="
<< s->user->get_id() << dendl;
break;
}
is_truncated = buckets.is_truncated();
/* We need to have stats for all our policies - even if a given policy
* isn't actually used in a given account. In such situation its usage
* stats would be simply full of zeros. */
std::set<std::string> targets;
if (driver->get_zone()->get_zonegroup().get_placement_target_names(targets)) {
for (const auto& policy : targets) {
policies_stats.emplace(policy, decltype(policies_stats)::mapped_type());
}
}
std::map<std::string, std::unique_ptr<rgw::sal::Bucket>>& m = buckets.get_buckets();
for (const auto& kv : m) {
const auto& bucket = kv.second;
global_stats.bytes_used += bucket->get_size();
global_stats.bytes_used_rounded += bucket->get_size_rounded();
global_stats.objects_count += bucket->get_count();
/* operator[] still can create a new entry for storage policy seen
* for first time. */
auto& policy_stats = policies_stats[bucket->get_placement_rule().to_str()];
policy_stats.bytes_used += bucket->get_size();
policy_stats.bytes_used_rounded += bucket->get_size_rounded();
policy_stats.buckets_count++;
policy_stats.objects_count += bucket->get_count();
}
global_stats.buckets_count += m.size();
total_count += m.size();
done = (m.size() < read_count || (limit >= 0 && total_count >= (uint64_t)limit));
if (!started) {
send_response_begin(buckets.count() > 0);
started = true;
}
if (read_count > 0 &&
!m.empty()) {
auto riter = m.rbegin();
marker = riter->first;
handle_listing_chunk(std::move(buckets));
}
} while (is_truncated && !done);
send_end:
if (!started) {
send_response_begin(false);
}
send_response_end();
}
void RGWGetUsage::execute(optional_yield y)
{
uint64_t start_epoch = 0;
uint64_t end_epoch = (uint64_t)-1;
op_ret = get_params(y);
if (op_ret < 0)
return;
if (!start_date.empty()) {
op_ret = utime_t::parse_date(start_date, &start_epoch, NULL);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to parse start date" << dendl;
return;
}
}
if (!end_date.empty()) {
op_ret = utime_t::parse_date(end_date, &end_epoch, NULL);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to parse end date" << dendl;
return;
}
}
uint32_t max_entries = 1000;
bool is_truncated = true;
RGWUsageIter usage_iter;
while (s->bucket && is_truncated) {
op_ret = s->bucket->read_usage(this, start_epoch, end_epoch, max_entries, &is_truncated,
usage_iter, usage);
if (op_ret == -ENOENT) {
op_ret = 0;
is_truncated = false;
}
if (op_ret < 0) {
return;
}
}
op_ret = rgw_user_sync_all_stats(this, driver, s->user.get(), y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to sync user stats" << dendl;
return;
}
op_ret = rgw_user_get_all_buckets_stats(this, driver, s->user.get(), buckets_usage, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get user's buckets stats" << dendl;
return;
}
op_ret = s->user->read_stats(this, y, &stats);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: can't read user header" << dendl;
return;
}
return;
}
int RGWStatAccount::verify_permission(optional_yield y)
{
if (!verify_user_permission_no_policy(this, s, RGW_PERM_READ)) {
return -EACCES;
}
return 0;
}
void RGWStatAccount::execute(optional_yield y)
{
string marker;
rgw::sal::BucketList buckets;
uint64_t max_buckets = s->cct->_conf->rgw_list_buckets_max_chunk;
const string *lastmarker;
do {
lastmarker = nullptr;
op_ret = s->user->list_buckets(this, marker, string(), max_buckets, true, buckets, y);
if (op_ret < 0) {
/* hmm.. something wrong here.. the user was authenticated, so it
should exist */
ldpp_dout(this, 10) << "WARNING: failed on list_buckets uid="
<< s->user->get_id() << " ret=" << op_ret << dendl;
break;
} else {
/* We need to have stats for all our policies - even if a given policy
* isn't actually used in a given account. In such situation its usage
* stats would be simply full of zeros. */
std::set<std::string> names;
driver->get_zone()->get_zonegroup().get_placement_target_names(names);
for (const auto& policy : names) {
policies_stats.emplace(policy, decltype(policies_stats)::mapped_type());
}
std::map<std::string, std::unique_ptr<rgw::sal::Bucket>>& m = buckets.get_buckets();
for (const auto& kv : m) {
const auto& bucket = kv.second;
lastmarker = &kv.first;
global_stats.bytes_used += bucket->get_size();
global_stats.bytes_used_rounded += bucket->get_size_rounded();
global_stats.objects_count += bucket->get_count();
/* operator[] still can create a new entry for storage policy seen
* for first time. */
auto& policy_stats = policies_stats[bucket->get_placement_rule().to_str()];
policy_stats.bytes_used += bucket->get_size();
policy_stats.bytes_used_rounded += bucket->get_size_rounded();
policy_stats.buckets_count++;
policy_stats.objects_count += bucket->get_count();
}
global_stats.buckets_count += m.size();
}
if (!lastmarker) {
ldpp_dout(this, -1) << "ERROR: rgw_read_user_buckets, stasis at marker="
<< marker << " uid=" << s->user->get_id() << dendl;
break;
}
marker = *lastmarker;
} while (buckets.is_truncated());
}
int RGWGetBucketVersioning::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketVersioning);
}
void RGWGetBucketVersioning::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetBucketVersioning::execute(optional_yield y)
{
if (! s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
versioned = s->bucket->versioned();
versioning_enabled = s->bucket->versioning_enabled();
mfa_enabled = s->bucket->get_info().mfa_enabled();
}
int RGWSetBucketVersioning::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketVersioning);
}
void RGWSetBucketVersioning::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWSetBucketVersioning::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
if (! s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
if (s->bucket->get_info().obj_lock_enabled() && versioning_status != VersioningEnabled) {
s->err.message = "bucket versioning cannot be disabled on buckets with object lock enabled";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_BUCKET_STATE;
return;
}
bool cur_mfa_status = s->bucket->get_info().mfa_enabled();
mfa_set_status &= (mfa_status != cur_mfa_status);
if (mfa_set_status &&
!s->mfa_verified) {
op_ret = -ERR_MFA_REQUIRED;
return;
}
//if mfa is enabled for bucket, make sure mfa code is validated in case versioned status gets changed
if (cur_mfa_status) {
bool req_versioning_status = false;
//if requested versioning status is not the same as the one set for the bucket, return error
if (versioning_status == VersioningEnabled) {
req_versioning_status = (s->bucket->get_info().flags & BUCKET_VERSIONS_SUSPENDED) != 0;
} else if (versioning_status == VersioningSuspended) {
req_versioning_status = (s->bucket->get_info().flags & BUCKET_VERSIONS_SUSPENDED) == 0;
}
if (req_versioning_status && !s->mfa_verified) {
op_ret = -ERR_MFA_REQUIRED;
return;
}
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
bool modified = mfa_set_status;
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [&] {
if (mfa_set_status) {
if (mfa_status) {
s->bucket->get_info().flags |= BUCKET_MFA_ENABLED;
} else {
s->bucket->get_info().flags &= ~BUCKET_MFA_ENABLED;
}
}
if (versioning_status == VersioningEnabled) {
s->bucket->get_info().flags |= BUCKET_VERSIONED;
s->bucket->get_info().flags &= ~BUCKET_VERSIONS_SUSPENDED;
modified = true;
} else if (versioning_status == VersioningSuspended) {
s->bucket->get_info().flags |= (BUCKET_VERSIONED | BUCKET_VERSIONS_SUSPENDED);
modified = true;
} else {
return op_ret;
}
s->bucket->set_attrs(rgw::sal::Attrs(s->bucket_attrs));
return s->bucket->put_info(this, false, real_time(), y);
}, y);
if (!modified) {
return;
}
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket->get_name()
<< " returned err=" << op_ret << dendl;
return;
}
}
int RGWGetBucketWebsite::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketWebsite);
}
void RGWGetBucketWebsite::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetBucketWebsite::execute(optional_yield y)
{
if (!s->bucket->get_info().has_website) {
op_ret = -ERR_NO_SUCH_WEBSITE_CONFIGURATION;
}
}
int RGWSetBucketWebsite::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketWebsite);
}
void RGWSetBucketWebsite::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWSetBucketWebsite::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
if (!s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << " forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
s->bucket->get_info().has_website = true;
s->bucket->get_info().website_conf = website_conf;
op_ret = s->bucket->put_info(this, false, real_time(), y);
return op_ret;
}, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket->get_name()
<< " returned err=" << op_ret << dendl;
return;
}
}
int RGWDeleteBucketWebsite::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3DeleteBucketWebsite);
}
void RGWDeleteBucketWebsite::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWDeleteBucketWebsite::execute(optional_yield y)
{
if (!s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
bufferlist in_data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: forward_to_master failed on bucket=" << s->bucket->get_name()
<< "returned err=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
s->bucket->get_info().has_website = false;
s->bucket->get_info().website_conf = RGWBucketWebsiteConf();
op_ret = s->bucket->put_info(this, false, real_time(), y);
return op_ret;
}, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket
<< " returned err=" << op_ret << dendl;
return;
}
}
int RGWStatBucket::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
// This (a HEAD request on a bucket) is governed by the s3:ListBucket permission.
if (!verify_bucket_permission(this, s, rgw::IAM::s3ListBucket)) {
return -EACCES;
}
return 0;
}
void RGWStatBucket::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWStatBucket::execute(optional_yield y)
{
if (!s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
op_ret = driver->get_bucket(this, s->user.get(), s->bucket->get_key(), &bucket, y);
if (op_ret) {
return;
}
op_ret = bucket->update_container_stats(s, y);
}
int RGWListBucket::verify_permission(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0) {
return op_ret;
}
if (!prefix.empty())
s->env.emplace("s3:prefix", prefix);
if (!delimiter.empty())
s->env.emplace("s3:delimiter", delimiter);
s->env.emplace("s3:max-keys", std::to_string(max));
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this,
s,
list_versions ?
rgw::IAM::s3ListBucketVersions :
rgw::IAM::s3ListBucket)) {
return -EACCES;
}
return 0;
}
int RGWListBucket::parse_max_keys()
{
// Bound max value of max-keys to configured value for security
// Bound min value of max-keys to '0'
// Some S3 clients explicitly send max-keys=0 to detect if the bucket is
// empty without listing any items.
return parse_value_and_bound(max_keys, max, 0,
g_conf().get_val<uint64_t>("rgw_max_listing_results"),
default_max);
}
void RGWListBucket::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWListBucket::execute(optional_yield y)
{
if (!s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
if (allow_unordered && !delimiter.empty()) {
ldpp_dout(this, 0) <<
"ERROR: unordered bucket listing requested with a delimiter" << dendl;
op_ret = -EINVAL;
return;
}
if (need_container_stats()) {
op_ret = s->bucket->update_container_stats(s, y);
}
rgw::sal::Bucket::ListParams params;
params.prefix = prefix;
params.delim = delimiter;
params.marker = marker;
params.end_marker = end_marker;
params.list_versions = list_versions;
params.allow_unordered = allow_unordered;
params.shard_id = shard_id;
rgw::sal::Bucket::ListResults results;
op_ret = s->bucket->list(this, params, max, results, y);
if (op_ret >= 0) {
next_marker = results.next_marker;
is_truncated = results.is_truncated;
objs = std::move(results.objs);
common_prefixes = std::move(results.common_prefixes);
}
}
int RGWGetBucketLogging::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketLogging);
}
int RGWGetBucketLocation::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketLocation);
}
int RGWCreateBucket::verify_permission(optional_yield y)
{
/* This check is mostly needed for S3 that doesn't support account ACL.
* Swift doesn't allow to delegate any permission to an anonymous user,
* so it will become an early exit in such case. */
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
rgw_bucket bucket;
bucket.name = s->bucket_name;
bucket.tenant = s->bucket_tenant;
ARN arn = ARN(bucket);
if (!verify_user_permission(this, s, arn, rgw::IAM::s3CreateBucket, false)) {
return -EACCES;
}
if (s->user->get_tenant() != s->bucket_tenant) {
//AssumeRole is meant for cross account access
if (s->auth.identity->get_identity_type() != TYPE_ROLE) {
ldpp_dout(this, 10) << "user cannot create a bucket in a different tenant"
<< " (user_id.tenant=" << s->user->get_tenant()
<< " requested=" << s->bucket_tenant << ")"
<< dendl;
return -EACCES;
}
}
if (s->user->get_max_buckets() < 0) {
return -EPERM;
}
if (s->user->get_max_buckets()) {
rgw::sal::BucketList buckets;
string marker;
op_ret = s->user->list_buckets(this, marker, string(), s->user->get_max_buckets(),
false, buckets, y);
if (op_ret < 0) {
return op_ret;
}
if ((int)buckets.count() >= s->user->get_max_buckets()) {
return -ERR_TOO_MANY_BUCKETS;
}
}
return 0;
}
void RGWCreateBucket::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
static void prepare_add_del_attrs(const map<string, bufferlist>& orig_attrs,
map<string, bufferlist>& out_attrs,
map<string, bufferlist>& out_rmattrs)
{
for (const auto& kv : orig_attrs) {
const string& name = kv.first;
/* Check if the attr is user-defined metadata item. */
if (name.compare(0, sizeof(RGW_ATTR_META_PREFIX) - 1,
RGW_ATTR_META_PREFIX) == 0) {
/* For the objects all existing meta attrs have to be removed. */
out_rmattrs[name] = kv.second;
} else if (out_attrs.find(name) == std::end(out_attrs)) {
out_attrs[name] = kv.second;
}
}
}
/* Fuse resource metadata basing on original attributes in @orig_attrs, set
* of _custom_ attribute names to remove in @rmattr_names and attributes in
* @out_attrs. Place results in @out_attrs.
*
* NOTE: it's supposed that all special attrs already present in @out_attrs
* will be preserved without any change. Special attributes are those which
* names start with RGW_ATTR_META_PREFIX. They're complement to custom ones
* used for X-Account-Meta-*, X-Container-Meta-*, X-Amz-Meta and so on. */
static void prepare_add_del_attrs(const map<string, bufferlist>& orig_attrs,
const set<string>& rmattr_names,
map<string, bufferlist>& out_attrs)
{
for (const auto& kv : orig_attrs) {
const string& name = kv.first;
/* Check if the attr is user-defined metadata item. */
if (name.compare(0, strlen(RGW_ATTR_META_PREFIX),
RGW_ATTR_META_PREFIX) == 0) {
/* For the buckets all existing meta attrs are preserved,
except those that are listed in rmattr_names. */
if (rmattr_names.find(name) != std::end(rmattr_names)) {
const auto aiter = out_attrs.find(name);
if (aiter != std::end(out_attrs)) {
out_attrs.erase(aiter);
}
} else {
/* emplace() won't alter the map if the key is already present.
* This behaviour is fully intensional here. */
out_attrs.emplace(kv);
}
} else if (out_attrs.find(name) == std::end(out_attrs)) {
out_attrs[name] = kv.second;
}
}
}
static void populate_with_generic_attrs(const req_state * const s,
map<string, bufferlist>& out_attrs)
{
for (const auto& kv : s->generic_attrs) {
bufferlist& attrbl = out_attrs[kv.first];
const string& val = kv.second;
attrbl.clear();
attrbl.append(val.c_str(), val.size() + 1);
}
}
static int filter_out_quota_info(std::map<std::string, bufferlist>& add_attrs,
const std::set<std::string>& rmattr_names,
RGWQuotaInfo& quota,
bool * quota_extracted = nullptr)
{
bool extracted = false;
/* Put new limit on max objects. */
auto iter = add_attrs.find(RGW_ATTR_QUOTA_NOBJS);
std::string err;
if (std::end(add_attrs) != iter) {
quota.max_objects =
static_cast<int64_t>(strict_strtoll(iter->second.c_str(), 10, &err));
if (!err.empty()) {
return -EINVAL;
}
add_attrs.erase(iter);
extracted = true;
}
/* Put new limit on bucket (container) size. */
iter = add_attrs.find(RGW_ATTR_QUOTA_MSIZE);
if (iter != add_attrs.end()) {
quota.max_size =
static_cast<int64_t>(strict_strtoll(iter->second.c_str(), 10, &err));
if (!err.empty()) {
return -EINVAL;
}
add_attrs.erase(iter);
extracted = true;
}
for (const auto& name : rmattr_names) {
/* Remove limit on max objects. */
if (name.compare(RGW_ATTR_QUOTA_NOBJS) == 0) {
quota.max_objects = -1;
extracted = true;
}
/* Remove limit on max bucket size. */
if (name.compare(RGW_ATTR_QUOTA_MSIZE) == 0) {
quota.max_size = -1;
extracted = true;
}
}
/* Swift requries checking on raw usage instead of the 4 KiB rounded one. */
quota.check_on_raw = true;
quota.enabled = quota.max_size > 0 || quota.max_objects > 0;
if (quota_extracted) {
*quota_extracted = extracted;
}
return 0;
}
static void filter_out_website(std::map<std::string, ceph::bufferlist>& add_attrs,
const std::set<std::string>& rmattr_names,
RGWBucketWebsiteConf& ws_conf)
{
std::string lstval;
/* Let's define a mapping between each custom attribute and the memory where
* attribute's value should be stored. The memory location is expressed by
* a non-const reference. */
const auto mapping = {
std::make_pair(RGW_ATTR_WEB_INDEX, std::ref(ws_conf.index_doc_suffix)),
std::make_pair(RGW_ATTR_WEB_ERROR, std::ref(ws_conf.error_doc)),
std::make_pair(RGW_ATTR_WEB_LISTINGS, std::ref(lstval)),
std::make_pair(RGW_ATTR_WEB_LIST_CSS, std::ref(ws_conf.listing_css_doc)),
std::make_pair(RGW_ATTR_SUBDIR_MARKER, std::ref(ws_conf.subdir_marker))
};
for (const auto& kv : mapping) {
const char * const key = kv.first;
auto& target = kv.second;
auto iter = add_attrs.find(key);
if (std::end(add_attrs) != iter) {
/* The "target" is a reference to ws_conf. */
target = iter->second.c_str();
add_attrs.erase(iter);
}
if (rmattr_names.count(key)) {
target = std::string();
}
}
if (! lstval.empty()) {
ws_conf.listing_enabled = boost::algorithm::iequals(lstval, "true");
}
}
void RGWCreateBucket::execute(optional_yield y)
{
buffer::list aclbl;
buffer::list corsbl;
string bucket_name = rgw_make_bucket_entry_name(s->bucket_tenant, s->bucket_name);
op_ret = get_params(y);
if (op_ret < 0)
return;
if (!relaxed_region_enforcement &&
!location_constraint.empty() &&
!driver->get_zone()->has_zonegroup_api(location_constraint)) {
ldpp_dout(this, 0) << "location constraint (" << location_constraint << ")"
<< " can't be found." << dendl;
op_ret = -ERR_INVALID_LOCATION_CONSTRAINT;
s->err.message = "The specified location-constraint is not valid";
return;
}
if (!relaxed_region_enforcement && !driver->get_zone()->get_zonegroup().is_master_zonegroup() && !location_constraint.empty() &&
driver->get_zone()->get_zonegroup().get_api_name() != location_constraint) {
ldpp_dout(this, 0) << "location constraint (" << location_constraint << ")"
<< " doesn't match zonegroup" << " (" << driver->get_zone()->get_zonegroup().get_api_name() << ")"
<< dendl;
op_ret = -ERR_INVALID_LOCATION_CONSTRAINT;
s->err.message = "The specified location-constraint is not valid";
return;
}
std::set<std::string> names;
driver->get_zone()->get_zonegroup().get_placement_target_names(names);
if (!placement_rule.name.empty() &&
!names.count(placement_rule.name)) {
ldpp_dout(this, 0) << "placement target (" << placement_rule.name << ")"
<< " doesn't exist in the placement targets of zonegroup"
<< " (" << driver->get_zone()->get_zonegroup().get_api_name() << ")" << dendl;
op_ret = -ERR_INVALID_LOCATION_CONSTRAINT;
s->err.message = "The specified placement target does not exist";
return;
}
/* we need to make sure we read bucket info, it's not read before for this
* specific request */
{
std::unique_ptr<rgw::sal::Bucket> tmp_bucket;
op_ret = driver->get_bucket(this, s->user.get(), s->bucket_tenant,
s->bucket_name, &tmp_bucket, y);
if (op_ret < 0 && op_ret != -ENOENT)
return;
s->bucket_exists = (op_ret != -ENOENT);
if (s->bucket_exists) {
if (!s->system_request &&
driver->get_zone()->get_zonegroup().get_id() !=
tmp_bucket->get_info().zonegroup) {
op_ret = -EEXIST;
return;
}
/* Initialize info from req_state */
info = tmp_bucket->get_info();
}
}
s->bucket_owner.set_id(s->user->get_id()); /* XXX dang use s->bucket->owner */
s->bucket_owner.set_name(s->user->get_display_name());
string zonegroup_id;
if (s->system_request) {
zonegroup_id = s->info.args.get(RGW_SYS_PARAM_PREFIX "zonegroup");
if (zonegroup_id.empty()) {
zonegroup_id = driver->get_zone()->get_zonegroup().get_id();
}
} else {
zonegroup_id = driver->get_zone()->get_zonegroup().get_id();
}
/* Encode special metadata first as we're using std::map::emplace under
* the hood. This method will add the new items only if the map doesn't
* contain such keys yet. */
policy.encode(aclbl);
emplace_attr(RGW_ATTR_ACL, std::move(aclbl));
if (has_cors) {
cors_config.encode(corsbl);
emplace_attr(RGW_ATTR_CORS, std::move(corsbl));
}
RGWQuotaInfo quota_info;
const RGWQuotaInfo * pquota_info = nullptr;
if (need_metadata_upload()) {
/* It's supposed that following functions WILL NOT change any special
* attributes (like RGW_ATTR_ACL) if they are already present in attrs. */
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs, false);
if (op_ret < 0) {
return;
}
prepare_add_del_attrs(s->bucket_attrs, rmattr_names, attrs);
populate_with_generic_attrs(s, attrs);
op_ret = filter_out_quota_info(attrs, rmattr_names, quota_info);
if (op_ret < 0) {
return;
} else {
pquota_info = "a_info;
}
/* Web site of Swift API. */
filter_out_website(attrs, rmattr_names, info.website_conf);
info.has_website = !info.website_conf.is_empty();
}
rgw_bucket tmp_bucket;
tmp_bucket.tenant = s->bucket_tenant; /* ignored if bucket exists */
tmp_bucket.name = s->bucket_name;
/* Handle updates of the metadata for Swift's object versioning. */
if (swift_ver_location) {
info.swift_ver_location = *swift_ver_location;
info.swift_versioning = (! swift_ver_location->empty());
}
/* We're replacing bucket with the newly created one */
ldpp_dout(this, 10) << "user=" << s->user << " bucket=" << tmp_bucket << dendl;
op_ret = s->user->create_bucket(this, tmp_bucket, zonegroup_id,
placement_rule,
info.swift_ver_location,
pquota_info, policy, attrs, info, ep_objv,
true, obj_lock_enabled, &s->bucket_exists, s->info,
&s->bucket, y);
/* continue if EEXIST and create_bucket will fail below. this way we can
* recover from a partial create by retrying it. */
ldpp_dout(this, 20) << "rgw_create_bucket returned ret=" << op_ret << " bucket=" << s->bucket.get() << dendl;
if (op_ret)
return;
const bool existed = s->bucket_exists;
if (need_metadata_upload() && existed) {
/* OK, it looks we lost race with another request. As it's required to
* handle metadata fusion and upload, the whole operation becomes very
* similar in nature to PutMetadataBucket. However, as the attrs may
* changed in the meantime, we have to refresh. */
short tries = 0;
do {
map<string, bufferlist> battrs;
op_ret = s->bucket->load_bucket(this, y);
if (op_ret < 0) {
return;
} else if (!s->bucket->is_owner(s->user.get())) {
/* New bucket doesn't belong to the account we're operating on. */
op_ret = -EEXIST;
return;
} else {
s->bucket_attrs = s->bucket->get_attrs();
}
attrs.clear();
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs, false);
if (op_ret < 0) {
return;
}
prepare_add_del_attrs(s->bucket_attrs, rmattr_names, attrs);
populate_with_generic_attrs(s, attrs);
op_ret = filter_out_quota_info(attrs, rmattr_names, s->bucket->get_info().quota);
if (op_ret < 0) {
return;
}
/* Handle updates of the metadata for Swift's object versioning. */
if (swift_ver_location) {
s->bucket->get_info().swift_ver_location = *swift_ver_location;
s->bucket->get_info().swift_versioning = (! swift_ver_location->empty());
}
/* Web site of Swift API. */
filter_out_website(attrs, rmattr_names, s->bucket->get_info().website_conf);
s->bucket->get_info().has_website = !s->bucket->get_info().website_conf.is_empty();
/* This will also set the quota on the bucket. */
op_ret = s->bucket->merge_and_store_attrs(this, attrs, y);
} while (op_ret == -ECANCELED && tries++ < 20);
/* Restore the proper return code. */
if (op_ret >= 0) {
op_ret = -ERR_BUCKET_EXISTS;
}
}
}
int RGWDeleteBucket::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3DeleteBucket)) {
return -EACCES;
}
return 0;
}
void RGWDeleteBucket::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWDeleteBucket::execute(optional_yield y)
{
if (s->bucket_name.empty()) {
op_ret = -EINVAL;
return;
}
if (!s->bucket_exists) {
ldpp_dout(this, 0) << "ERROR: bucket " << s->bucket_name << " not found" << dendl;
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
RGWObjVersionTracker ot;
ot.read_version = s->bucket->get_version();
if (s->system_request) {
string tag = s->info.args.get(RGW_SYS_PARAM_PREFIX "tag");
string ver_str = s->info.args.get(RGW_SYS_PARAM_PREFIX "ver");
if (!tag.empty()) {
ot.read_version.tag = tag;
uint64_t ver;
string err;
ver = strict_strtol(ver_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(this, 0) << "failed to parse ver param" << dendl;
op_ret = -EINVAL;
return;
}
ot.read_version.ver = ver;
}
}
op_ret = s->bucket->sync_user_stats(this, y);
if ( op_ret < 0) {
ldpp_dout(this, 1) << "WARNING: failed to sync user stats before bucket delete: op_ret= " << op_ret << dendl;
}
op_ret = s->bucket->check_empty(this, y);
if (op_ret < 0) {
return;
}
bufferlist in_data;
op_ret = driver->forward_request_to_master(this, s->user.get(), &ot.read_version, in_data, nullptr, s->info, y);
if (op_ret < 0) {
if (op_ret == -ENOENT) {
/* adjust error, we want to return with NoSuchBucket and not
* NoSuchKey */
op_ret = -ERR_NO_SUCH_BUCKET;
}
return;
}
op_ret = rgw_remove_sse_s3_bucket_key(s);
if (op_ret != 0) {
// do nothing; it will already have been logged
}
op_ret = s->bucket->remove_bucket(this, false, false, nullptr, y);
if (op_ret < 0 && op_ret == -ECANCELED) {
// lost a race, either with mdlog sync or another delete bucket operation.
// in either case, we've already called ctl.bucket->unlink_bucket()
op_ret = 0;
}
return;
}
int RGWPutObj::init_processing(optional_yield y) {
copy_source = url_decode(s->info.env->get("HTTP_X_AMZ_COPY_SOURCE", ""));
copy_source_range = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE_RANGE");
size_t pos;
int ret;
/* handle x-amz-copy-source */
std::string_view cs_view(copy_source);
if (! cs_view.empty()) {
if (cs_view[0] == '/')
cs_view.remove_prefix(1);
copy_source_bucket_name = std::string(cs_view);
pos = copy_source_bucket_name.find("/");
if (pos == std::string::npos) {
ret = -EINVAL;
ldpp_dout(this, 5) << "x-amz-copy-source bad format" << dendl;
return ret;
}
copy_source_object_name =
copy_source_bucket_name.substr(pos + 1, copy_source_bucket_name.size());
copy_source_bucket_name = copy_source_bucket_name.substr(0, pos);
#define VERSION_ID_STR "?versionId="
pos = copy_source_object_name.find(VERSION_ID_STR);
if (pos == std::string::npos) {
copy_source_object_name = url_decode(copy_source_object_name);
} else {
copy_source_version_id =
copy_source_object_name.substr(pos + sizeof(VERSION_ID_STR) - 1);
copy_source_object_name =
url_decode(copy_source_object_name.substr(0, pos));
}
pos = copy_source_bucket_name.find(":");
if (pos == std::string::npos) {
// if tenant is not specified in x-amz-copy-source, use tenant of the requester
copy_source_tenant_name = s->user->get_tenant();
} else {
copy_source_tenant_name = copy_source_bucket_name.substr(0, pos);
copy_source_bucket_name = copy_source_bucket_name.substr(pos + 1, copy_source_bucket_name.size());
if (copy_source_bucket_name.empty()) {
ret = -EINVAL;
ldpp_dout(this, 5) << "source bucket name is empty" << dendl;
return ret;
}
}
std::unique_ptr<rgw::sal::Bucket> bucket;
ret = driver->get_bucket(this, s->user.get(), copy_source_tenant_name, copy_source_bucket_name,
&bucket, y);
if (ret < 0) {
ldpp_dout(this, 5) << __func__ << "(): get_bucket() returned ret=" << ret << dendl;
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_BUCKET;
}
return ret;
}
ret = bucket->load_bucket(this, y);
if (ret < 0) {
ldpp_dout(this, 5) << __func__ << "(): load_bucket() returned ret=" << ret << dendl;
return ret;
}
copy_source_bucket_info = bucket->get_info();
/* handle x-amz-copy-source-range */
if (copy_source_range) {
string range = copy_source_range;
pos = range.find("bytes=");
if (pos == std::string::npos || pos != 0) {
ret = -EINVAL;
ldpp_dout(this, 5) << "x-amz-copy-source-range bad format" << dendl;
return ret;
}
/* 6 is the length of "bytes=" */
range = range.substr(pos + 6);
pos = range.find("-");
if (pos == std::string::npos) {
ret = -EINVAL;
ldpp_dout(this, 5) << "x-amz-copy-source-range bad format" << dendl;
return ret;
}
string first = range.substr(0, pos);
string last = range.substr(pos + 1);
if (first.find_first_not_of("0123456789") != std::string::npos ||
last.find_first_not_of("0123456789") != std::string::npos) {
ldpp_dout(this, 5) << "x-amz-copy-source-range bad format not an integer" << dendl;
ret = -EINVAL;
return ret;
}
copy_source_range_fst = strtoull(first.c_str(), NULL, 10);
copy_source_range_lst = strtoull(last.c_str(), NULL, 10);
if (copy_source_range_fst > copy_source_range_lst) {
ret = -ERANGE;
ldpp_dout(this, 5) << "x-amz-copy-source-range bad format first number bigger than second" << dendl;
return ret;
}
}
} /* copy_source */
return RGWOp::init_processing(y);
}
int RGWPutObj::verify_permission(optional_yield y)
{
if (! copy_source.empty()) {
RGWAccessControlPolicy cs_acl(s->cct);
boost::optional<Policy> policy;
map<string, bufferlist> cs_attrs;
std::unique_ptr<rgw::sal::Bucket> cs_bucket;
int ret = driver->get_bucket(NULL, copy_source_bucket_info, &cs_bucket);
if (ret < 0)
return ret;
std::unique_ptr<rgw::sal::Object> cs_object =
cs_bucket->get_object(rgw_obj_key(copy_source_object_name, copy_source_version_id));
cs_object->set_atomic();
cs_object->set_prefetch_data();
/* check source object permissions */
if (ret = read_obj_policy(this, driver, s, copy_source_bucket_info, cs_attrs, &cs_acl, nullptr,
policy, cs_bucket.get(), cs_object.get(), y, true); ret < 0) {
return ret;
}
/* admin request overrides permission checks */
if (! s->auth.identity->is_admin_of(cs_acl.get_owner().get_id())) {
if (policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
//add source object tags for permission evaluation
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, policy, s->iam_user_policies, s->session_policies);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, cs_object.get(), has_s3_existing_tag, has_s3_resource_tag);
auto usr_policy_res = Effect::Pass;
rgw::ARN obj_arn(cs_object->get_obj());
for (auto& user_policy : s->iam_user_policies) {
if (usr_policy_res = user_policy.eval(s->env, boost::none,
cs_object->get_instance().empty() ?
rgw::IAM::s3GetObject :
rgw::IAM::s3GetObjectVersion,
obj_arn); usr_policy_res == Effect::Deny)
return -EACCES;
else if (usr_policy_res == Effect::Allow)
break;
}
rgw::IAM::Effect e = Effect::Pass;
if (policy) {
rgw::ARN obj_arn(cs_object->get_obj());
e = policy->eval(s->env, *s->auth.identity,
cs_object->get_instance().empty() ?
rgw::IAM::s3GetObject :
rgw::IAM::s3GetObjectVersion,
obj_arn);
}
if (e == Effect::Deny) {
return -EACCES;
} else if (usr_policy_res == Effect::Pass && e == Effect::Pass &&
!cs_acl.verify_permission(this, *s->auth.identity, s->perm_mask,
RGW_PERM_READ)) {
return -EACCES;
}
rgw_iam_remove_objtags(this, s, cs_object.get(), has_s3_existing_tag, has_s3_resource_tag);
} else if (!cs_acl.verify_permission(this, *s->auth.identity, s->perm_mask,
RGW_PERM_READ)) {
return -EACCES;
}
}
}
if (s->bucket_access_conf && s->bucket_access_conf->block_public_acls()) {
if (s->canned_acl.compare("public-read") ||
s->canned_acl.compare("public-read-write") ||
s->canned_acl.compare("authenticated-read"))
return -EACCES;
}
auto op_ret = get_params(y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "get_params() returned ret=" << op_ret << dendl;
return op_ret;
}
if (s->iam_policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
rgw_add_grant_to_iam_environment(s->env, s);
rgw_add_to_iam_environment(s->env, "s3:x-amz-acl", s->canned_acl);
if (obj_tags != nullptr && obj_tags->count() > 0){
auto tags = obj_tags->get_tags();
for (const auto& kv: tags){
rgw_add_to_iam_environment(s->env, "s3:RequestObjectTag/"+kv.first, kv.second);
}
}
// add server-side encryption headers
rgw_iam_add_crypt_attrs(s->env, s->info.crypt_attribute_map);
// Add bucket tags for authorization
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (identity_policy_res == Effect::Deny)
return -EACCES;
rgw::IAM::Effect e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
if (s->iam_policy) {
ARN obj_arn(s->object->get_obj());
e = s->iam_policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3PutObject,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow))
return 0;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow)
return 0;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow)
return 0;
}
return -EACCES;
}
if (e == Effect::Allow || identity_policy_res == Effect::Allow) {
return 0;
}
}
if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
return 0;
}
void RGWPutObj::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
class RGWPutObj_CB : public RGWGetObj_Filter
{
RGWPutObj *op;
public:
explicit RGWPutObj_CB(RGWPutObj *_op) : op(_op) {}
~RGWPutObj_CB() override {}
int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override {
return op->get_data_cb(bl, bl_ofs, bl_len);
}
};
int RGWPutObj::get_data_cb(bufferlist& bl, off_t bl_ofs, off_t bl_len)
{
bufferlist bl_tmp;
bl.begin(bl_ofs).copy(bl_len, bl_tmp);
bl_aux.append(bl_tmp);
return bl_len;
}
int RGWPutObj::get_data(const off_t fst, const off_t lst, bufferlist& bl)
{
RGWPutObj_CB cb(this);
RGWGetObj_Filter* filter = &cb;
boost::optional<RGWGetObj_Decompress> decompress;
std::unique_ptr<RGWGetObj_Filter> decrypt;
RGWCompressionInfo cs_info;
map<string, bufferlist> attrs;
int ret = 0;
uint64_t obj_size;
int64_t new_ofs, new_end;
new_ofs = fst;
new_end = lst;
std::unique_ptr<rgw::sal::Bucket> bucket;
ret = driver->get_bucket(nullptr, copy_source_bucket_info, &bucket);
if (ret < 0)
return ret;
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(rgw_obj_key(copy_source_object_name, copy_source_version_id));
std::unique_ptr<rgw::sal::Object::ReadOp> read_op(obj->get_read_op());
ret = read_op->prepare(s->yield, this);
if (ret < 0)
return ret;
obj_size = obj->get_obj_size();
bool need_decompress;
op_ret = rgw_compression_info_from_attrset(obj->get_attrs(), need_decompress, cs_info);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to decode compression info" << dendl;
return -EIO;
}
bool partial_content = true;
if (need_decompress)
{
obj_size = cs_info.orig_size;
decompress.emplace(s->cct, &cs_info, partial_content, filter);
filter = &*decompress;
}
auto attr_iter = obj->get_attrs().find(RGW_ATTR_MANIFEST);
op_ret = this->get_decrypt_filter(&decrypt,
filter,
obj->get_attrs(),
attr_iter != obj->get_attrs().end() ? &(attr_iter->second) : nullptr);
if (decrypt != nullptr) {
filter = decrypt.get();
}
if (op_ret < 0) {
return op_ret;
}
ret = obj->range_to_ofs(obj_size, new_ofs, new_end);
if (ret < 0)
return ret;
filter->fixup_range(new_ofs, new_end);
ret = read_op->iterate(this, new_ofs, new_end, filter, s->yield);
if (ret >= 0)
ret = filter->flush();
bl.claim_append(bl_aux);
return ret;
}
// special handling for compression type = "random" with multipart uploads
static CompressorRef get_compressor_plugin(const req_state *s,
const std::string& compression_type)
{
if (compression_type != "random") {
return Compressor::create(s->cct, compression_type);
}
bool is_multipart{false};
const auto& upload_id = s->info.args.get("uploadId", &is_multipart);
if (!is_multipart) {
return Compressor::create(s->cct, compression_type);
}
// use a hash of the multipart upload id so all parts use the same plugin
const auto alg = std::hash<std::string>{}(upload_id) % Compressor::COMP_ALG_LAST;
if (alg == Compressor::COMP_ALG_NONE) {
return nullptr;
}
return Compressor::create(s->cct, alg);
}
auto RGWPutObj::get_torrent_filter(rgw::sal::DataProcessor* cb)
-> std::optional<RGWPutObj_Torrent>
{
auto& conf = get_cct()->_conf;
if (!conf->rgw_torrent_flag) {
return std::nullopt; // torrent generation disabled
}
const auto max_len = conf->rgw_torrent_max_size;
const auto piece_len = conf->rgw_torrent_sha_unit;
if (!max_len || !piece_len) {
return std::nullopt; // invalid configuration
}
if (crypt_http_responses.count("x-amz-server-side-encryption-customer-algorithm")) {
return std::nullopt; // downloading the torrent would require customer keys
}
return RGWPutObj_Torrent{cb, max_len, piece_len};
}
int RGWPutObj::get_lua_filter(std::unique_ptr<rgw::sal::DataProcessor>* filter, rgw::sal::DataProcessor* cb) {
std::string script;
const auto rc = rgw::lua::read_script(s, s->penv.lua.manager.get(), s->bucket_tenant, s->yield, rgw::lua::context::putData, script);
if (rc == -ENOENT) {
// no script, nothing to do
return 0;
} else if (rc < 0) {
ldpp_dout(this, 5) << "WARNING: failed to read data script. error: " << rc << dendl;
return rc;
}
filter->reset(new rgw::lua::RGWPutObjFilter(s, script, cb));
return 0;
}
void RGWPutObj::execute(optional_yield y)
{
char supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1];
char supplied_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
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);
bufferlist bl, aclbl, bs;
int len;
off_t fst;
off_t lst;
bool need_calc_md5 = (dlo_manifest == NULL) && (slo_info == NULL);
perfcounter->inc(l_rgw_put);
// report latency on return
auto put_lat = make_scope_guard([&] {
perfcounter->tinc(l_rgw_put_lat, s->time_elapsed());
});
op_ret = -EINVAL;
if (rgw::sal::Object::empty(s->object.get())) {
return;
}
if (!s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
op_ret = get_system_versioning_params(s, &olh_epoch, &version_id);
if (op_ret < 0) {
ldpp_dout(this, 20) << "get_system_versioning_params() returned ret="
<< op_ret << dendl;
return;
}
if (supplied_md5_b64) {
need_calc_md5 = true;
ldpp_dout(this, 15) << "supplied_md5_b64=" << supplied_md5_b64 << dendl;
op_ret = ceph_unarmor(supplied_md5_bin, &supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1],
supplied_md5_b64, supplied_md5_b64 + strlen(supplied_md5_b64));
ldpp_dout(this, 15) << "ceph_armor ret=" << op_ret << dendl;
if (op_ret != CEPH_CRYPTO_MD5_DIGESTSIZE) {
op_ret = -ERR_INVALID_DIGEST;
return;
}
buf_to_hex((const unsigned char *)supplied_md5_bin, CEPH_CRYPTO_MD5_DIGESTSIZE, supplied_md5);
ldpp_dout(this, 15) << "supplied_md5=" << supplied_md5 << dendl;
}
if (!chunked_upload) { /* with chunked upload we don't know how big is the upload.
we also check sizes at the end anyway */
op_ret = s->bucket->check_quota(this, quota, s->content_length, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "check_quota() returned ret=" << op_ret << dendl;
return;
}
}
if (supplied_etag) {
strncpy(supplied_md5, supplied_etag, sizeof(supplied_md5) - 1);
supplied_md5[sizeof(supplied_md5) - 1] = '\0';
}
const bool multipart = !multipart_upload_id.empty();
/* Handle object versioning of Swift API. */
if (! multipart) {
op_ret = s->object->swift_versioning_copy(this, s->yield);
if (op_ret < 0) {
return;
}
}
// make reservation for notification if needed
std::unique_ptr<rgw::sal::Notification> res
= driver->get_notification(
s->object.get(), s->src_object.get(), s,
rgw::notify::ObjectCreatedPut, y);
if(!multipart) {
op_ret = res->publish_reserve(this, obj_tags.get());
if (op_ret < 0) {
return;
}
}
// create the object processor
std::unique_ptr<rgw::sal::Writer> processor;
rgw_placement_rule *pdest_placement = &s->dest_placement;
if (multipart) {
std::unique_ptr<rgw::sal::MultipartUpload> upload;
upload = s->bucket->get_multipart_upload(s->object->get_name(),
multipart_upload_id);
op_ret = upload->get_info(this, s->yield, &pdest_placement);
s->trace->SetAttribute(tracing::rgw::UPLOAD_ID, multipart_upload_id);
multipart_trace = tracing::rgw::tracer.add_span(name(), upload->get_trace());
if (op_ret < 0) {
if (op_ret != -ENOENT) {
ldpp_dout(this, 0) << "ERROR: get_multipart_info returned " << op_ret << ": " << cpp_strerror(-op_ret) << dendl;
} else {// -ENOENT: raced with upload complete/cancel, no need to spam log
ldpp_dout(this, 20) << "failed to get multipart info (returned " << op_ret << ": " << cpp_strerror(-op_ret) << "): probably raced with upload complete / cancel" << dendl;
}
return;
}
/* upload will go out of scope, so copy the dest placement for later use */
s->dest_placement = *pdest_placement;
pdest_placement = &s->dest_placement;
ldpp_dout(this, 20) << "dest_placement for part=" << *pdest_placement << dendl;
processor = upload->get_writer(this, s->yield, s->object.get(),
s->user->get_id(), pdest_placement,
multipart_part_num, multipart_part_str);
} else if(append) {
if (s->bucket->versioned()) {
op_ret = -ERR_INVALID_BUCKET_STATE;
return;
}
processor = driver->get_append_writer(this, s->yield, s->object.get(),
s->bucket_owner.get_id(),
pdest_placement, s->req_id, position,
&cur_accounted_size);
} else {
if (s->bucket->versioning_enabled()) {
if (!version_id.empty()) {
s->object->set_instance(version_id);
} else {
s->object->gen_rand_obj_instance_name();
version_id = s->object->get_instance();
}
}
processor = driver->get_atomic_writer(this, s->yield, s->object.get(),
s->bucket_owner.get_id(),
pdest_placement, olh_epoch, s->req_id);
}
op_ret = processor->prepare(s->yield);
if (op_ret < 0) {
ldpp_dout(this, 20) << "processor->prepare() returned ret=" << op_ret
<< dendl;
return;
}
if ((! copy_source.empty()) && !copy_source_range) {
std::unique_ptr<rgw::sal::Bucket> bucket;
op_ret = driver->get_bucket(nullptr, copy_source_bucket_info, &bucket);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get bucket with error" << op_ret << dendl;
return;
}
std::unique_ptr<rgw::sal::Object> obj =
bucket->get_object(rgw_obj_key(copy_source_object_name, copy_source_version_id));
RGWObjState *astate;
op_ret = obj->get_obj_state(this, &astate, s->yield);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: get copy source obj state returned with error" << op_ret << dendl;
return;
}
bufferlist bl;
if (astate->get_attr(RGW_ATTR_MANIFEST, bl)) {
RGWObjManifest m;
try{
decode(m, bl);
if (m.get_tier_type() == "cloud-s3") {
op_ret = -ERR_INVALID_OBJECT_STATE;
s->err.message = "This object was transitioned to cloud-s3";
ldpp_dout(this, 4) << "Cannot copy cloud tiered object. Failing with "
<< op_ret << dendl;
return;
}
} catch (const buffer::end_of_buffer&) {
// ignore empty manifest; it's not cloud-tiered
} catch (const std::exception& e) {
ldpp_dout(this, 1) << "WARNING: failed to decode object manifest for "
<< *s->object << ": " << e.what() << dendl;
}
}
if (!astate->exists){
op_ret = -ENOENT;
return;
}
lst = astate->accounted_size - 1;
} else {
lst = copy_source_range_lst;
}
fst = copy_source_range_fst;
// no filters by default
rgw::sal::DataProcessor *filter = processor.get();
const auto& compression_type = driver->get_compression_type(*pdest_placement);
CompressorRef plugin;
std::optional<RGWPutObj_Compress> compressor;
std::optional<RGWPutObj_Torrent> torrent;
std::unique_ptr<rgw::sal::DataProcessor> encrypt;
std::unique_ptr<rgw::sal::DataProcessor> run_lua;
if (!append) { // compression and encryption only apply to full object uploads
op_ret = get_encrypt_filter(&encrypt, filter);
if (op_ret < 0) {
return;
}
if (encrypt != nullptr) {
filter = &*encrypt;
}
// a zonegroup feature is required to combine compression and encryption
const RGWZoneGroup& zonegroup = s->penv.site->get_zonegroup();
const bool compress_encrypted = zonegroup.supports(rgw::zone_features::compress_encrypted);
if (compression_type != "none" &&
(encrypt == nullptr || compress_encrypted)) {
plugin = get_compressor_plugin(s, compression_type);
if (!plugin) {
ldpp_dout(this, 1) << "Cannot load plugin for compression type "
<< compression_type << dendl;
} else {
compressor.emplace(s->cct, plugin, filter);
filter = &*compressor;
// always send incompressible hint when rgw is itself doing compression
s->object->set_compressed();
}
}
if (torrent = get_torrent_filter(filter); torrent) {
filter = &*torrent;
}
// run lua script before data is compressed and encrypted - last filter runs first
op_ret = get_lua_filter(&run_lua, filter);
if (op_ret < 0) {
return;
}
if (run_lua) {
filter = &*run_lua;
}
}
tracepoint(rgw_op, before_data_transfer, s->req_id.c_str());
do {
bufferlist data;
if (fst > lst)
break;
if (copy_source.empty()) {
len = get_data(data);
} else {
off_t cur_lst = min<off_t>(fst + s->cct->_conf->rgw_max_chunk_size - 1, lst);
op_ret = get_data(fst, cur_lst, data);
if (op_ret < 0)
return;
len = data.length();
s->content_length += len;
fst += len;
}
if (len < 0) {
op_ret = len;
ldpp_dout(this, 20) << "get_data() returned ret=" << op_ret << dendl;
return;
} else if (len == 0) {
break;
}
if (need_calc_md5) {
hash.Update((const unsigned char *)data.c_str(), data.length());
}
op_ret = filter->process(std::move(data), ofs);
if (op_ret < 0) {
ldpp_dout(this, 20) << "processor->process() returned ret="
<< op_ret << dendl;
return;
}
ofs += len;
} while (len > 0);
tracepoint(rgw_op, after_data_transfer, s->req_id.c_str(), ofs);
// flush any data in filters
op_ret = filter->process({}, ofs);
if (op_ret < 0) {
return;
}
if (!chunked_upload && ofs != s->content_length) {
op_ret = -ERR_REQUEST_TIMEOUT;
return;
}
s->obj_size = ofs;
s->object->set_obj_size(ofs);
perfcounter->inc(l_rgw_put_b, s->obj_size);
op_ret = do_aws4_auth_completion();
if (op_ret < 0) {
return;
}
op_ret = s->bucket->check_quota(this, quota, s->obj_size, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "second check_quota() returned op_ret=" << op_ret << dendl;
return;
}
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 = s->obj_size;
cs_info.compressor_message = compressor->get_compressor_message();
cs_info.blocks = 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;
}
if (torrent) {
auto bl = torrent->bencode_torrent(s->object->get_name());
if (bl.length()) {
ldpp_dout(this, 20) << "storing " << bl.length()
<< " bytes of torrent info in " << RGW_ATTR_TORRENT << dendl;
attrs[RGW_ATTR_TORRENT] = std::move(bl);
}
}
buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);
etag = calc_md5;
if (supplied_md5_b64 && strcmp(calc_md5, supplied_md5)) {
op_ret = -ERR_BAD_DIGEST;
return;
}
policy.encode(aclbl);
emplace_attr(RGW_ATTR_ACL, std::move(aclbl));
if (dlo_manifest) {
op_ret = encode_dlo_manifest_attr(dlo_manifest, attrs);
if (op_ret < 0) {
ldpp_dout(this, 0) << "bad user manifest: " << dlo_manifest << dendl;
return;
}
}
if (slo_info) {
bufferlist manifest_bl;
encode(*slo_info, manifest_bl);
emplace_attr(RGW_ATTR_SLO_MANIFEST, std::move(manifest_bl));
}
if (supplied_etag && etag.compare(supplied_etag) != 0) {
op_ret = -ERR_UNPROCESSABLE_ENTITY;
return;
}
bl.append(etag.c_str(), etag.size());
emplace_attr(RGW_ATTR_ETAG, std::move(bl));
populate_with_generic_attrs(s, attrs);
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs);
if (op_ret < 0) {
return;
}
encode_delete_at_attr(delete_at, attrs);
encode_obj_tags_attr(obj_tags.get(), attrs);
rgw_cond_decode_objtags(s, 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 (slo_info) {
bufferlist slo_userindicator_bl;
slo_userindicator_bl.append("True", 4);
emplace_attr(RGW_ATTR_SLO_UINDICATOR, std::move(slo_userindicator_bl));
}
if (obj_legal_hold) {
bufferlist obj_legal_hold_bl;
obj_legal_hold->encode(obj_legal_hold_bl);
emplace_attr(RGW_ATTR_OBJECT_LEGAL_HOLD, std::move(obj_legal_hold_bl));
}
if (obj_retention) {
bufferlist obj_retention_bl;
obj_retention->encode(obj_retention_bl);
emplace_attr(RGW_ATTR_OBJECT_RETENTION, std::move(obj_retention_bl));
}
tracepoint(rgw_op, processor_complete_enter, s->req_id.c_str());
op_ret = processor->complete(s->obj_size, etag, &mtime, real_time(), attrs,
(delete_at ? *delete_at : real_time()), if_match, if_nomatch,
(user_data.empty() ? nullptr : &user_data), nullptr, nullptr,
s->yield);
tracepoint(rgw_op, processor_complete_exit, s->req_id.c_str());
// send request to notification manager
int ret = res->publish_commit(this, s->obj_size, mtime, etag, s->object->get_instance());
if (ret < 0) {
ldpp_dout(this, 1) << "ERROR: publishing notification failed, with error: " << ret << dendl;
// too late to rollback operation, hence op_ret is not set here
}
}
int RGWPostObj::verify_permission(optional_yield y)
{
return 0;
}
void RGWPostObj::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPostObj::execute(optional_yield y)
{
boost::optional<RGWPutObj_Compress> compressor;
CompressorRef plugin;
char supplied_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
/* Read in the data from the POST form. */
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
op_ret = verify_params();
if (op_ret < 0) {
return;
}
// add server-side encryption headers
rgw_iam_add_crypt_attrs(s->env, s->info.crypt_attribute_map);
if (s->iam_policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (identity_policy_res == Effect::Deny) {
op_ret = -EACCES;
return;
}
rgw::IAM::Effect e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
if (s->iam_policy) {
ARN obj_arn(s->object->get_obj());
e = s->iam_policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3PutObject,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
op_ret = -EACCES;
return;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (session_policy_res == Effect::Deny) {
op_ret = -EACCES;
return;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow)) {
op_ret = 0;
return;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow) {
op_ret = 0;
return;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
op_ret = 0;
return;
}
}
op_ret = -EACCES;
return;
}
if (identity_policy_res == Effect::Pass && e == Effect::Pass && !verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
op_ret = -EACCES;
return;
}
} else if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
op_ret = -EACCES;
return;
}
// make reservation for notification if needed
std::unique_ptr<rgw::sal::Notification> res
= driver->get_notification(s->object.get(), s->src_object.get(), s, rgw::notify::ObjectCreatedPost, y);
op_ret = res->publish_reserve(this);
if (op_ret < 0) {
return;
}
/* Start iteration over data fields. It's necessary as Swift's FormPost
* is capable to handle multiple files in single form. */
do {
char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
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);
ceph::buffer::list bl, aclbl;
op_ret = s->bucket->check_quota(this, quota, s->content_length, y);
if (op_ret < 0) {
return;
}
if (supplied_md5_b64) {
char supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1];
ldpp_dout(this, 15) << "supplied_md5_b64=" << supplied_md5_b64 << dendl;
op_ret = ceph_unarmor(supplied_md5_bin, &supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1],
supplied_md5_b64, supplied_md5_b64 + strlen(supplied_md5_b64));
ldpp_dout(this, 15) << "ceph_armor ret=" << op_ret << dendl;
if (op_ret != CEPH_CRYPTO_MD5_DIGESTSIZE) {
op_ret = -ERR_INVALID_DIGEST;
return;
}
buf_to_hex((const unsigned char *)supplied_md5_bin, CEPH_CRYPTO_MD5_DIGESTSIZE, supplied_md5);
ldpp_dout(this, 15) << "supplied_md5=" << supplied_md5 << dendl;
}
std::unique_ptr<rgw::sal::Object> obj =
s->bucket->get_object(rgw_obj_key(get_current_filename()));
if (s->bucket->versioning_enabled()) {
obj->gen_rand_obj_instance_name();
}
std::unique_ptr<rgw::sal::Writer> processor;
processor = driver->get_atomic_writer(this, s->yield, obj.get(),
s->bucket_owner.get_id(),
&s->dest_placement, 0, s->req_id);
op_ret = processor->prepare(s->yield);
if (op_ret < 0) {
return;
}
/* No filters by default. */
rgw::sal::DataProcessor *filter = processor.get();
std::unique_ptr<rgw::sal::DataProcessor> encrypt;
op_ret = get_encrypt_filter(&encrypt, filter);
if (op_ret < 0) {
return;
}
if (encrypt != nullptr) {
filter = encrypt.get();
} else {
const auto& compression_type = driver->get_compression_type(s->dest_placement);
if (compression_type != "none") {
plugin = Compressor::create(s->cct, compression_type);
if (!plugin) {
ldpp_dout(this, 1) << "Cannot load plugin for compression type "
<< compression_type << dendl;
} else {
compressor.emplace(s->cct, plugin, filter);
filter = &*compressor;
}
}
}
bool again;
do {
ceph::bufferlist data;
int len = get_data(data, again);
if (len < 0) {
op_ret = len;
return;
}
if (!len) {
break;
}
hash.Update((const unsigned char *)data.c_str(), data.length());
op_ret = filter->process(std::move(data), ofs);
if (op_ret < 0) {
return;
}
ofs += len;
if (ofs > max_len) {
op_ret = -ERR_TOO_LARGE;
return;
}
} while (again);
// flush
op_ret = filter->process({}, ofs);
if (op_ret < 0) {
return;
}
if (ofs < min_len) {
op_ret = -ERR_TOO_SMALL;
return;
}
s->obj_size = ofs;
s->object->set_obj_size(ofs);
op_ret = s->bucket->check_quota(this, quota, s->obj_size, y);
if (op_ret < 0) {
return;
}
hash.Final(m);
buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);
etag = calc_md5;
if (supplied_md5_b64 && strcmp(calc_md5, supplied_md5)) {
op_ret = -ERR_BAD_DIGEST;
return;
}
bl.append(etag.c_str(), etag.size());
emplace_attr(RGW_ATTR_ETAG, std::move(bl));
policy.encode(aclbl);
emplace_attr(RGW_ATTR_ACL, std::move(aclbl));
const std::string content_type = get_current_content_type();
if (! content_type.empty()) {
ceph::bufferlist ct_bl;
ct_bl.append(content_type.c_str(), content_type.size() + 1);
emplace_attr(RGW_ATTR_CONTENT_TYPE, std::move(ct_bl));
}
if (compressor && compressor->is_compressed()) {
ceph::bufferlist tmp;
RGWCompressionInfo cs_info;
cs_info.compression_type = plugin->get_type_name();
cs_info.orig_size = s->obj_size;
cs_info.compressor_message = compressor->get_compressor_message();
cs_info.blocks = move(compressor->get_compression_blocks());
encode(cs_info, tmp);
emplace_attr(RGW_ATTR_COMPRESSION, std::move(tmp));
}
op_ret = processor->complete(s->obj_size, etag, nullptr, real_time(), attrs,
(delete_at ? *delete_at : real_time()),
nullptr, nullptr, nullptr, nullptr, nullptr,
s->yield);
if (op_ret < 0) {
return;
}
} while (is_next_file_to_upload());
// send request to notification manager
int ret = res->publish_commit(this, ofs, s->object->get_mtime(), etag, s->object->get_instance());
if (ret < 0) {
ldpp_dout(this, 1) << "ERROR: publishing notification failed, with error: " << ret << dendl;
// too late to rollback operation, hence op_ret is not set here
}
}
void RGWPutMetadataAccount::filter_out_temp_url(map<string, bufferlist>& add_attrs,
const set<string>& rmattr_names,
map<int, string>& temp_url_keys)
{
map<string, bufferlist>::iterator iter;
iter = add_attrs.find(RGW_ATTR_TEMPURL_KEY1);
if (iter != add_attrs.end()) {
temp_url_keys[0] = iter->second.c_str();
add_attrs.erase(iter);
}
iter = add_attrs.find(RGW_ATTR_TEMPURL_KEY2);
if (iter != add_attrs.end()) {
temp_url_keys[1] = iter->second.c_str();
add_attrs.erase(iter);
}
for (const string& name : rmattr_names) {
if (name.compare(RGW_ATTR_TEMPURL_KEY1) == 0) {
temp_url_keys[0] = string();
}
if (name.compare(RGW_ATTR_TEMPURL_KEY2) == 0) {
temp_url_keys[1] = string();
}
}
}
int RGWPutMetadataAccount::init_processing(optional_yield y)
{
/* First, go to the base class. At the time of writing the method was
* responsible only for initializing the quota. This isn't necessary
* here as we are touching metadata only. I'm putting this call only
* for the future. */
op_ret = RGWOp::init_processing(y);
if (op_ret < 0) {
return op_ret;
}
op_ret = get_params(y);
if (op_ret < 0) {
return op_ret;
}
op_ret = s->user->read_attrs(this, y);
if (op_ret < 0) {
return op_ret;
}
orig_attrs = s->user->get_attrs();
if (has_policy) {
bufferlist acl_bl;
policy.encode(acl_bl);
attrs.emplace(RGW_ATTR_ACL, std::move(acl_bl));
}
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs, false);
if (op_ret < 0) {
return op_ret;
}
prepare_add_del_attrs(orig_attrs, rmattr_names, attrs);
populate_with_generic_attrs(s, attrs);
/* Try extract the TempURL-related stuff now to allow verify_permission
* evaluate whether we need FULL_CONTROL or not. */
filter_out_temp_url(attrs, rmattr_names, temp_url_keys);
/* The same with quota except a client needs to be reseller admin. */
op_ret = filter_out_quota_info(attrs, rmattr_names, new_quota,
&new_quota_extracted);
if (op_ret < 0) {
return op_ret;
}
return 0;
}
int RGWPutMetadataAccount::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if (!verify_user_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
/* Altering TempURL keys requires FULL_CONTROL. */
if (!temp_url_keys.empty() && s->perm_mask != RGW_PERM_FULL_CONTROL) {
return -EPERM;
}
/* We are failing this intensionally to allow system user/reseller admin
* override in rgw_process.cc. This is the way to specify a given RGWOp
* expect extra privileges. */
if (new_quota_extracted) {
return -EACCES;
}
return 0;
}
void RGWPutMetadataAccount::execute(optional_yield y)
{
/* Params have been extracted earlier. See init_processing(). */
op_ret = s->user->load_user(this, y);
if (op_ret < 0) {
return;
}
/* Handle the TempURL-related stuff. */
if (!temp_url_keys.empty()) {
for (auto& pair : temp_url_keys) {
s->user->get_info().temp_url_keys[pair.first] = std::move(pair.second);
}
}
/* Handle the quota extracted at the verify_permission step. */
if (new_quota_extracted) {
s->user->get_info().quota.user_quota = std::move(new_quota);
}
/* We are passing here the current (old) user info to allow the function
* optimize-out some operations. */
s->user->set_attrs(attrs);
op_ret = s->user->store_user(this, y, false, &s->user->get_info());
}
int RGWPutMetadataBucket::verify_permission(optional_yield y)
{
if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
return 0;
}
void RGWPutMetadataBucket::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPutMetadataBucket::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs, false);
if (op_ret < 0) {
return;
}
if (!placement_rule.empty() &&
placement_rule != s->bucket->get_placement_rule()) {
op_ret = -EEXIST;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this] {
/* Encode special metadata first as we're using std::map::emplace under
* the hood. This method will add the new items only if the map doesn't
* contain such keys yet. */
if (has_policy) {
if (s->dialect.compare("swift") == 0) {
auto old_policy = \
static_cast<RGWAccessControlPolicy_SWIFT*>(s->bucket_acl.get());
auto new_policy = static_cast<RGWAccessControlPolicy_SWIFT*>(&policy);
new_policy->filter_merge(policy_rw_mask, old_policy);
policy = *new_policy;
}
buffer::list bl;
policy.encode(bl);
emplace_attr(RGW_ATTR_ACL, std::move(bl));
}
if (has_cors) {
buffer::list bl;
cors_config.encode(bl);
emplace_attr(RGW_ATTR_CORS, std::move(bl));
}
/* It's supposed that following functions WILL NOT change any
* special attributes (like RGW_ATTR_ACL) if they are already
* present in attrs. */
prepare_add_del_attrs(s->bucket_attrs, rmattr_names, attrs);
populate_with_generic_attrs(s, attrs);
/* According to the Swift's behaviour and its container_quota
* WSGI middleware implementation: anyone with write permissions
* is able to set the bucket quota. This stays in contrast to
* account quotas that can be set only by clients holding
* reseller admin privileges. */
op_ret = filter_out_quota_info(attrs, rmattr_names, s->bucket->get_info().quota);
if (op_ret < 0) {
return op_ret;
}
if (swift_ver_location) {
s->bucket->get_info().swift_ver_location = *swift_ver_location;
s->bucket->get_info().swift_versioning = (!swift_ver_location->empty());
}
/* Web site of Swift API. */
filter_out_website(attrs, rmattr_names, s->bucket->get_info().website_conf);
s->bucket->get_info().has_website = !s->bucket->get_info().website_conf.is_empty();
/* Setting attributes also stores the provided bucket info. Due
* to this fact, the new quota settings can be serialized with
* the same call. */
op_ret = s->bucket->merge_and_store_attrs(this, attrs, s->yield);
return op_ret;
}, y);
}
int RGWPutMetadataObject::verify_permission(optional_yield y)
{
// This looks to be something specific to Swift. We could add
// operations like swift:PutMetadataObject to the Policy Engine.
if (!verify_object_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
return 0;
}
void RGWPutMetadataObject::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPutMetadataObject::execute(optional_yield y)
{
rgw_obj target_obj;
rgw::sal::Attrs attrs, rmattrs;
s->object->set_atomic();
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs);
if (op_ret < 0) {
return;
}
/* check if obj exists, read orig attrs */
op_ret = s->object->get_obj_attrs(s->yield, s, &target_obj);
if (op_ret < 0) {
return;
}
/* Check whether the object has expired. Swift API documentation
* stands that we should return 404 Not Found in such case. */
if (need_object_expiration() && s->object->is_expired()) {
op_ret = -ENOENT;
return;
}
/* Filter currently existing attributes. */
prepare_add_del_attrs(s->object->get_attrs(), attrs, rmattrs);
populate_with_generic_attrs(s, attrs);
encode_delete_at_attr(delete_at, attrs);
if (dlo_manifest) {
op_ret = encode_dlo_manifest_attr(dlo_manifest, attrs);
if (op_ret < 0) {
ldpp_dout(this, 0) << "bad user manifest: " << dlo_manifest << dendl;
return;
}
}
op_ret = s->object->set_obj_attrs(this, &attrs, &rmattrs, s->yield);
}
int RGWDeleteObj::handle_slo_manifest(bufferlist& bl, optional_yield y)
{
RGWSLOInfo slo_info;
auto bliter = bl.cbegin();
try {
decode(slo_info, bliter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode slo manifest" << dendl;
return -EIO;
}
try {
deleter = std::unique_ptr<RGWBulkDelete::Deleter>(\
new RGWBulkDelete::Deleter(this, driver, s));
} catch (const std::bad_alloc&) {
return -ENOMEM;
}
list<RGWBulkDelete::acct_path_t> items;
for (const auto& iter : slo_info.entries) {
const string& path_str = iter.path;
const size_t pos_init = path_str.find_first_not_of('/');
if (std::string_view::npos == pos_init) {
return -EINVAL;
}
const size_t sep_pos = path_str.find('/', pos_init);
if (std::string_view::npos == sep_pos) {
return -EINVAL;
}
RGWBulkDelete::acct_path_t path;
path.bucket_name = url_decode(path_str.substr(pos_init, sep_pos - pos_init));
path.obj_key = url_decode(path_str.substr(sep_pos + 1));
items.push_back(path);
}
/* Request removal of the manifest object itself. */
RGWBulkDelete::acct_path_t path;
path.bucket_name = s->bucket_name;
path.obj_key = s->object->get_key();
items.push_back(path);
int ret = deleter->delete_chunk(items, y);
if (ret < 0) {
return ret;
}
return 0;
}
int RGWDeleteObj::verify_permission(optional_yield y)
{
int op_ret = get_params(y);
if (op_ret) {
return op_ret;
}
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (s->iam_policy || ! s->iam_user_policies.empty() || ! s->session_policies.empty()) {
if (s->bucket->get_info().obj_lock_enabled() && bypass_governance_mode) {
auto r = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3BypassGovernanceRetention, ARN(s->bucket->get_key(), s->object->get_name()));
if (r == Effect::Deny) {
bypass_perm = false;
} else if (r == Effect::Pass && s->iam_policy) {
ARN obj_arn(ARN(s->bucket->get_key(), s->object->get_name()));
r = s->iam_policy->eval(s->env, *s->auth.identity, rgw::IAM::s3BypassGovernanceRetention, obj_arn);
if (r == Effect::Deny) {
bypass_perm = false;
}
} else if (r == Effect::Pass && !s->session_policies.empty()) {
r = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3BypassGovernanceRetention, ARN(s->bucket->get_key(), s->object->get_name()));
if (r == Effect::Deny) {
bypass_perm = false;
}
}
}
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
s->object->get_instance().empty() ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
ARN(s->bucket->get_key(), s->object->get_name()));
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
rgw::IAM::Effect r = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
ARN obj_arn(ARN(s->bucket->get_key(), s->object->get_name()));
if (s->iam_policy) {
r = s->iam_policy->eval(s->env, *s->auth.identity,
s->object->get_instance().empty() ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
obj_arn,
princ_type);
}
if (r == Effect::Deny)
return -EACCES;
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
s->object->get_instance().empty() ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
obj_arn);
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && r == Effect::Allow)) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || r == Effect::Allow) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
return 0;
}
}
return -EACCES;
}
if (r == Effect::Allow || identity_policy_res == Effect::Allow)
return 0;
}
if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
if (s->bucket->get_info().mfa_enabled() &&
!s->object->get_instance().empty() &&
!s->mfa_verified) {
ldpp_dout(this, 5) << "NOTICE: object delete request with a versioned object, mfa auth not provided" << dendl;
return -ERR_MFA_REQUIRED;
}
return 0;
}
void RGWDeleteObj::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWDeleteObj::execute(optional_yield y)
{
if (!s->bucket_exists) {
op_ret = -ERR_NO_SUCH_BUCKET;
return;
}
if (!rgw::sal::Object::empty(s->object.get())) {
uint64_t obj_size = 0;
std::string etag;
{
RGWObjState* astate = nullptr;
bool check_obj_lock = s->object->have_instance() && s->bucket->get_info().obj_lock_enabled();
op_ret = s->object->get_obj_state(this, &astate, s->yield, true);
if (op_ret < 0) {
if (need_object_expiration() || multipart_delete) {
return;
}
if (check_obj_lock) {
/* check if obj exists, read orig attrs */
if (op_ret == -ENOENT) {
/* object maybe delete_marker, skip check_obj_lock*/
check_obj_lock = false;
} else {
return;
}
}
} else {
obj_size = astate->size;
etag = astate->attrset[RGW_ATTR_ETAG].to_str();
}
// ignore return value from get_obj_attrs in all other cases
op_ret = 0;
if (check_obj_lock) {
ceph_assert(astate);
int object_lock_response = verify_object_lock(this, astate->attrset, bypass_perm, bypass_governance_mode);
if (object_lock_response != 0) {
op_ret = object_lock_response;
if (op_ret == -EACCES) {
s->err.message = "forbidden by object lock";
}
return;
}
}
if (multipart_delete) {
if (!astate) {
op_ret = -ERR_NOT_SLO_MANIFEST;
return;
}
const auto slo_attr = astate->attrset.find(RGW_ATTR_SLO_MANIFEST);
if (slo_attr != astate->attrset.end()) {
op_ret = handle_slo_manifest(slo_attr->second, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to handle slo manifest ret=" << op_ret << dendl;
}
} else {
op_ret = -ERR_NOT_SLO_MANIFEST;
}
return;
}
}
// make reservation for notification if needed
const auto versioned_object = s->bucket->versioning_enabled();
const auto event_type = versioned_object &&
s->object->get_instance().empty() ?
rgw::notify::ObjectRemovedDeleteMarkerCreated :
rgw::notify::ObjectRemovedDelete;
std::unique_ptr<rgw::sal::Notification> res
= driver->get_notification(s->object.get(), s->src_object.get(), s,
event_type, y);
op_ret = res->publish_reserve(this);
if (op_ret < 0) {
return;
}
s->object->set_atomic();
bool ver_restored = false;
op_ret = s->object->swift_versioning_restore(ver_restored, this, y);
if (op_ret < 0) {
return;
}
if (!ver_restored) {
uint64_t epoch = 0;
/* Swift's versioning mechanism hasn't found any previous version of
* the object that could be restored. This means we should proceed
* with the regular delete path. */
op_ret = get_system_versioning_params(s, &epoch, &version_id);
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::Object::DeleteOp> del_op = s->object->get_delete_op();
del_op->params.obj_owner = s->owner;
del_op->params.bucket_owner = s->bucket_owner;
del_op->params.versioning_status = s->bucket->get_info().versioning_status();
del_op->params.unmod_since = unmod_since;
del_op->params.high_precision_time = s->system_request;
del_op->params.olh_epoch = epoch;
del_op->params.marker_version_id = version_id;
op_ret = del_op->delete_obj(this, y);
if (op_ret >= 0) {
delete_marker = del_op->result.delete_marker;
version_id = del_op->result.version_id;
}
/* Check whether the object has expired. Swift API documentation
* stands that we should return 404 Not Found in such case. */
if (need_object_expiration() && s->object->is_expired()) {
op_ret = -ENOENT;
return;
}
}
if (op_ret == -ECANCELED) {
op_ret = 0;
}
if (op_ret == -ERR_PRECONDITION_FAILED && no_precondition_error) {
op_ret = 0;
}
// send request to notification manager
int ret = res->publish_commit(this, obj_size, ceph::real_clock::now(), etag, version_id);
if (ret < 0) {
ldpp_dout(this, 1) << "ERROR: publishing notification failed, with error: " << ret << dendl;
// too late to rollback operation, hence op_ret is not set here
}
} else {
op_ret = -EINVAL;
}
}
bool RGWCopyObj::parse_copy_location(const std::string_view& url_src,
string& bucket_name,
rgw_obj_key& key,
req_state* s)
{
std::string_view name_str;
std::string_view params_str;
// search for ? before url-decoding so we don't accidentally match %3F
size_t pos = url_src.find('?');
if (pos == string::npos) {
name_str = url_src;
} else {
name_str = url_src.substr(0, pos);
params_str = url_src.substr(pos + 1);
}
if (name_str[0] == '/') // trim leading slash
name_str.remove_prefix(1);
std::string dec_src = url_decode(name_str);
pos = dec_src.find('/');
if (pos == string::npos)
return false;
bucket_name = dec_src.substr(0, pos);
key.name = dec_src.substr(pos + 1);
if (key.name.empty()) {
return false;
}
if (! params_str.empty()) {
RGWHTTPArgs args;
args.set(std::string(params_str));
args.parse(s);
key.instance = args.get("versionId", NULL);
}
return true;
}
int RGWCopyObj::init_processing(optional_yield y)
{
op_ret = RGWOp::init_processing(y);
if (op_ret < 0) {
return op_ret;
}
op_ret = get_params(y);
if (op_ret < 0)
return op_ret;
op_ret = get_system_versioning_params(s, &olh_epoch, &version_id);
if (op_ret < 0) {
return op_ret;
}
op_ret = driver->get_bucket(this, s->user.get(),
rgw_bucket_key(s->src_tenant_name,
s->src_bucket_name),
&src_bucket, y);
if (op_ret < 0) {
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_SUCH_BUCKET;
}
return op_ret;
}
/* This is the only place the bucket is set on src_object */
s->src_object->set_bucket(src_bucket.get());
return 0;
}
int RGWCopyObj::verify_permission(optional_yield y)
{
RGWAccessControlPolicy src_acl(s->cct);
boost::optional<Policy> src_policy;
/* get buckets info (source and dest) */
if (s->local_source && source_zone.empty()) {
s->src_object->set_atomic();
s->src_object->set_prefetch_data();
rgw_placement_rule src_placement;
/* check source object permissions */
op_ret = read_obj_policy(this, driver, s, src_bucket->get_info(), src_bucket->get_attrs(), &src_acl, &src_placement.storage_class,
src_policy, src_bucket.get(), s->src_object.get(), y);
if (op_ret < 0) {
return op_ret;
}
/* follow up on previous checks that required reading source object head */
if (need_to_check_storage_class) {
src_placement.inherit_from(src_bucket->get_placement_rule());
op_ret = check_storage_class(src_placement);
if (op_ret < 0) {
return op_ret;
}
}
/* admin request overrides permission checks */
if (!s->auth.identity->is_admin_of(src_acl.get_owner().get_id())) {
if (src_policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, src_policy, s->iam_user_policies, s->session_policies);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, s->src_object.get(), has_s3_existing_tag, has_s3_resource_tag);
ARN obj_arn(s->src_object->get_obj());
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
s->src_object->get_instance().empty() ?
rgw::IAM::s3GetObject :
rgw::IAM::s3GetObjectVersion,
obj_arn);
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
auto e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
if (src_policy) {
e = src_policy->eval(s->env, *s->auth.identity,
s->src_object->get_instance().empty() ?
rgw::IAM::s3GetObject :
rgw::IAM::s3GetObjectVersion,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
s->src_object->get_instance().empty() ?
rgw::IAM::s3GetObject :
rgw::IAM::s3GetObjectVersion,
obj_arn);
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) &&
(session_policy_res != Effect::Allow || e != Effect::Allow)) {
return -EACCES;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) && e != Effect::Allow) {
return -EACCES;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) {
return -EACCES;
}
}
}
if (identity_policy_res == Effect::Pass && e == Effect::Pass &&
!src_acl.verify_permission(this, *s->auth.identity, s->perm_mask,
RGW_PERM_READ)) {
return -EACCES;
}
//remove src object tags as it may interfere with policy evaluation of destination obj
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_remove_objtags(this, s, s->src_object.get(), has_s3_existing_tag, has_s3_resource_tag);
} else if (!src_acl.verify_permission(this, *s->auth.identity,
s->perm_mask,
RGW_PERM_READ)) {
return -EACCES;
}
}
}
RGWAccessControlPolicy dest_bucket_policy(s->cct);
s->object->set_atomic();
/* check dest bucket permissions */
op_ret = read_bucket_policy(this, driver, s, s->bucket->get_info(),
s->bucket->get_attrs(),
&dest_bucket_policy, s->bucket->get_key(), y);
if (op_ret < 0) {
return op_ret;
}
auto dest_iam_policy = get_iam_policy_from_attr(s->cct, s->bucket->get_attrs(), s->bucket->get_tenant());
/* admin request overrides permission checks */
if (! s->auth.identity->is_admin_of(dest_policy.get_owner().get_id())){
if (dest_iam_policy != boost::none || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
//Add destination bucket tags for authorization
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, dest_iam_policy, s->iam_user_policies, s->session_policies);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s, s->bucket.get());
rgw_add_to_iam_environment(s->env, "s3:x-amz-copy-source", copy_source);
if (md_directive)
rgw_add_to_iam_environment(s->env, "s3:x-amz-metadata-directive",
*md_directive);
ARN obj_arn(s->object->get_obj());
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies,
s->env,
rgw::IAM::s3PutObject,
obj_arn);
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
auto e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
if (dest_iam_policy) {
e = dest_iam_policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3PutObject,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject, obj_arn);
if (session_policy_res == Effect::Deny) {
return false;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) &&
(session_policy_res != Effect::Allow || e == Effect::Allow)) {
return -EACCES;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) && e != Effect::Allow) {
return -EACCES;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) {
return -EACCES;
}
}
}
if (identity_policy_res == Effect::Pass && e == Effect::Pass &&
! dest_bucket_policy.verify_permission(this,
*s->auth.identity,
s->perm_mask,
RGW_PERM_WRITE)){
return -EACCES;
}
} else if (! dest_bucket_policy.verify_permission(this, *s->auth.identity, s->perm_mask,
RGW_PERM_WRITE)) {
return -EACCES;
}
}
op_ret = init_dest_policy();
if (op_ret < 0) {
return op_ret;
}
return 0;
}
int RGWCopyObj::init_common()
{
if (if_mod) {
if (parse_time(if_mod, &mod_time) < 0) {
op_ret = -EINVAL;
return op_ret;
}
mod_ptr = &mod_time;
}
if (if_unmod) {
if (parse_time(if_unmod, &unmod_time) < 0) {
op_ret = -EINVAL;
return op_ret;
}
unmod_ptr = &unmod_time;
}
bufferlist aclbl;
dest_policy.encode(aclbl);
emplace_attr(RGW_ATTR_ACL, std::move(aclbl));
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs);
if (op_ret < 0) {
return op_ret;
}
populate_with_generic_attrs(s, attrs);
return 0;
}
static void copy_obj_progress_cb(off_t ofs, void *param)
{
RGWCopyObj *op = static_cast<RGWCopyObj *>(param);
op->progress_cb(ofs);
}
void RGWCopyObj::progress_cb(off_t ofs)
{
if (!s->cct->_conf->rgw_copy_obj_progress)
return;
if (ofs - last_ofs <
static_cast<off_t>(s->cct->_conf->rgw_copy_obj_progress_every_bytes)) {
return;
}
send_partial_response(ofs);
last_ofs = ofs;
}
void RGWCopyObj::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWCopyObj::execute(optional_yield y)
{
if (init_common() < 0)
return;
// make reservation for notification if needed
std::unique_ptr<rgw::sal::Notification> res
= driver->get_notification(
s->object.get(), s->src_object.get(),
s, rgw::notify::ObjectCreatedCopy, y);
op_ret = res->publish_reserve(this);
if (op_ret < 0) {
return;
}
if ( ! version_id.empty()) {
s->object->set_instance(version_id);
} else if (s->bucket->versioning_enabled()) {
s->object->gen_rand_obj_instance_name();
}
s->src_object->set_atomic();
s->object->set_atomic();
encode_delete_at_attr(delete_at, attrs);
if (obj_retention) {
bufferlist obj_retention_bl;
obj_retention->encode(obj_retention_bl);
emplace_attr(RGW_ATTR_OBJECT_RETENTION, std::move(obj_retention_bl));
}
if (obj_legal_hold) {
bufferlist obj_legal_hold_bl;
obj_legal_hold->encode(obj_legal_hold_bl);
emplace_attr(RGW_ATTR_OBJECT_LEGAL_HOLD, std::move(obj_legal_hold_bl));
}
uint64_t obj_size = 0;
{
// get src object size (cached in obj_ctx from verify_permission())
RGWObjState* astate = nullptr;
op_ret = s->src_object->get_obj_state(this, &astate, s->yield, true);
if (op_ret < 0) {
return;
}
/* Check if the src object is cloud-tiered */
bufferlist bl;
if (astate->get_attr(RGW_ATTR_MANIFEST, bl)) {
RGWObjManifest m;
try{
decode(m, bl);
if (m.get_tier_type() == "cloud-s3") {
op_ret = -ERR_INVALID_OBJECT_STATE;
s->err.message = "This object was transitioned to cloud-s3";
ldpp_dout(this, 4) << "Cannot copy cloud tiered object. Failing with "
<< op_ret << dendl;
return;
}
} catch (const buffer::end_of_buffer&) {
// ignore empty manifest; it's not cloud-tiered
} catch (const std::exception& e) {
ldpp_dout(this, 1) << "WARNING: failed to decode object manifest for "
<< *s->object << ": " << e.what() << dendl;
}
}
obj_size = astate->size;
if (!s->system_request) { // no quota enforcement for system requests
if (astate->accounted_size > static_cast<size_t>(s->cct->_conf->rgw_max_put_size)) {
op_ret = -ERR_TOO_LARGE;
return;
}
// enforce quota against the destination bucket owner
op_ret = s->bucket->check_quota(this, quota, astate->accounted_size, y);
if (op_ret < 0) {
return;
}
}
}
bool high_precision_time = (s->system_request);
/* Handle object versioning of Swift API. In case of copying to remote this
* should fail gently (op_ret == 0) as the dst_obj will not exist here. */
op_ret = s->object->swift_versioning_copy(this, s->yield);
if (op_ret < 0) {
return;
}
op_ret = s->src_object->copy_object(s->user.get(),
&s->info,
source_zone,
s->object.get(),
s->bucket.get(),
src_bucket.get(),
s->dest_placement,
&src_mtime,
&mtime,
mod_ptr,
unmod_ptr,
high_precision_time,
if_match,
if_nomatch,
attrs_mod,
copy_if_newer,
attrs,
RGWObjCategory::Main,
olh_epoch,
delete_at,
(version_id.empty() ? NULL : &version_id),
&s->req_id, /* use req_id as tag */
&etag,
copy_obj_progress_cb, (void *)this,
this,
s->yield);
// send request to notification manager
int ret = res->publish_commit(this, obj_size, mtime, etag, s->object->get_instance());
if (ret < 0) {
ldpp_dout(this, 1) << "ERROR: publishing notification failed, with error: " << ret << dendl;
// too late to rollback operation, hence op_ret is not set here
}
}
int RGWGetACLs::verify_permission(optional_yield y)
{
bool perm;
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (!rgw::sal::Object::empty(s->object.get())) {
auto iam_action = s->object->get_instance().empty() ?
rgw::IAM::s3GetObjectAcl :
rgw::IAM::s3GetObjectVersionAcl;
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
perm = verify_object_permission(this, s, iam_action);
} else {
if (!s->bucket_exists) {
return -ERR_NO_SUCH_BUCKET;
}
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
perm = verify_bucket_permission(this, s, rgw::IAM::s3GetBucketAcl);
}
if (!perm)
return -EACCES;
return 0;
}
void RGWGetACLs::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetACLs::execute(optional_yield y)
{
stringstream ss;
RGWAccessControlPolicy* const acl = \
(!rgw::sal::Object::empty(s->object.get()) ? s->object_acl.get() : s->bucket_acl.get());
RGWAccessControlPolicy_S3* const s3policy = \
static_cast<RGWAccessControlPolicy_S3*>(acl);
s3policy->to_xml(ss);
acls = ss.str();
}
int RGWPutACLs::verify_permission(optional_yield y)
{
bool perm;
rgw_add_to_iam_environment(s->env, "s3:x-amz-acl", s->canned_acl);
rgw_add_grant_to_iam_environment(s->env, s);
if (!rgw::sal::Object::empty(s->object.get())) {
auto iam_action = s->object->get_instance().empty() ? rgw::IAM::s3PutObjectAcl : rgw::IAM::s3PutObjectVersionAcl;
op_ret = rgw_iam_add_objtags(this, s, true, true);
perm = verify_object_permission(this, s, iam_action);
} else {
op_ret = rgw_iam_add_buckettags(this, s);
perm = verify_bucket_permission(this, s, rgw::IAM::s3PutBucketAcl);
}
if (!perm)
return -EACCES;
return 0;
}
int RGWGetLC::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
bool perm;
perm = verify_bucket_permission(this, s, rgw::IAM::s3GetLifecycleConfiguration);
if (!perm)
return -EACCES;
return 0;
}
int RGWPutLC::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
bool perm;
perm = verify_bucket_permission(this, s, rgw::IAM::s3PutLifecycleConfiguration);
if (!perm)
return -EACCES;
return 0;
}
int RGWDeleteLC::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
bool perm;
perm = verify_bucket_permission(this, s, rgw::IAM::s3PutLifecycleConfiguration);
if (!perm)
return -EACCES;
return 0;
}
void RGWPutACLs::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetLC::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPutLC::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWDeleteLC::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPutACLs::execute(optional_yield y)
{
bufferlist bl;
RGWAccessControlPolicy_S3 *policy = NULL;
RGWACLXMLParser_S3 parser(s->cct);
RGWAccessControlPolicy_S3 new_policy(s->cct);
stringstream ss;
op_ret = 0; /* XXX redundant? */
if (!parser.init()) {
op_ret = -EINVAL;
return;
}
RGWAccessControlPolicy* const existing_policy = \
(rgw::sal::Object::empty(s->object.get()) ? s->bucket_acl.get() : s->object_acl.get());
owner = existing_policy->get_owner();
op_ret = get_params(y);
if (op_ret < 0) {
if (op_ret == -ERANGE) {
ldpp_dout(this, 4) << "The size of request xml data is larger than the max limitation, data size = "
<< s->length << dendl;
op_ret = -ERR_MALFORMED_XML;
s->err.message = "The XML you provided was larger than the maximum " +
std::to_string(s->cct->_conf->rgw_max_put_param_size) +
" bytes allowed.";
}
return;
}
char* buf = data.c_str();
ldpp_dout(this, 15) << "read len=" << data.length() << " data=" << (buf ? buf : "") << dendl;
if (!s->canned_acl.empty() && data.length() > 0) {
op_ret = -EINVAL;
return;
}
if (!s->canned_acl.empty() || s->has_acl_header) {
op_ret = get_policy_from_state(driver, s, ss);
if (op_ret < 0)
return;
data.clear();
data.append(ss.str());
}
if (!parser.parse(data.c_str(), data.length(), 1)) {
op_ret = -EINVAL;
return;
}
policy = static_cast<RGWAccessControlPolicy_S3 *>(parser.find_first("AccessControlPolicy"));
if (!policy) {
op_ret = -EINVAL;
return;
}
const RGWAccessControlList& req_acl = policy->get_acl();
const multimap<string, ACLGrant>& req_grant_map = req_acl.get_grant_map();
#define ACL_GRANTS_MAX_NUM 100
int max_num = s->cct->_conf->rgw_acl_grants_max_num;
if (max_num < 0) {
max_num = ACL_GRANTS_MAX_NUM;
}
int grants_num = req_grant_map.size();
if (grants_num > max_num) {
ldpp_dout(this, 4) << "An acl can have up to " << max_num
<< " grants, request acl grants num: " << grants_num << dendl;
op_ret = -ERR_LIMIT_EXCEEDED;
s->err.message = "The request is rejected, because the acl grants number you requested is larger than the maximum "
+ std::to_string(max_num)
+ " grants allowed in an acl.";
return;
}
// forward bucket acl requests to meta master zone
if ((rgw::sal::Object::empty(s->object.get()))) {
bufferlist in_data;
// include acl data unless it was generated from a canned_acl
if (s->canned_acl.empty()) {
in_data.append(data);
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
}
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
ldpp_dout(this, 15) << "Old AccessControlPolicy";
policy->to_xml(*_dout);
*_dout << dendl;
}
op_ret = policy->rebuild(this, driver, &owner, new_policy, s->err.message);
if (op_ret < 0)
return;
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
ldpp_dout(this, 15) << "New AccessControlPolicy:";
new_policy.to_xml(*_dout);
*_dout << dendl;
}
if (s->bucket_access_conf &&
s->bucket_access_conf->block_public_acls() &&
new_policy.is_public(this)) {
op_ret = -EACCES;
return;
}
new_policy.encode(bl);
map<string, bufferlist> attrs;
if (!rgw::sal::Object::empty(s->object.get())) {
s->object->set_atomic();
//if instance is empty, we should modify the latest object
op_ret = s->object->modify_obj_attrs(RGW_ATTR_ACL, bl, s->yield, this);
} else {
map<string,bufferlist> attrs = s->bucket_attrs;
attrs[RGW_ATTR_ACL] = bl;
op_ret = s->bucket->merge_and_store_attrs(this, attrs, y);
}
if (op_ret == -ECANCELED) {
op_ret = 0; /* lost a race, but it's ok because acls are immutable */
}
}
void RGWPutLC::execute(optional_yield y)
{
bufferlist bl;
RGWLifecycleConfiguration_S3 config(s->cct);
RGWXMLParser parser;
RGWLifecycleConfiguration_S3 new_config(s->cct);
// amazon says that Content-MD5 is required for this op specifically, but MD5
// is not a security primitive and FIPS mode makes it difficult to use. if the
// client provides the header we'll try to verify its checksum, but the header
// itself is no longer required
std::optional<std::string> content_md5_bin;
content_md5 = s->info.env->get("HTTP_CONTENT_MD5");
if (content_md5 != nullptr) {
try {
content_md5_bin = rgw::from_base64(std::string_view(content_md5));
} catch (...) {
s->err.message = "Request header Content-MD5 contains character "
"that is not base64 encoded.";
ldpp_dout(this, 5) << s->err.message << dendl;
op_ret = -ERR_BAD_DIGEST;
return;
}
}
if (!parser.init()) {
op_ret = -EINVAL;
return;
}
op_ret = get_params(y);
if (op_ret < 0)
return;
char* buf = data.c_str();
ldpp_dout(this, 15) << "read len=" << data.length() << " data=" << (buf ? buf : "") << dendl;
if (content_md5_bin) {
MD5 data_hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
data_hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
unsigned char data_hash_res[CEPH_CRYPTO_MD5_DIGESTSIZE];
data_hash.Update(reinterpret_cast<const unsigned char*>(buf), data.length());
data_hash.Final(data_hash_res);
if (memcmp(data_hash_res, content_md5_bin->c_str(), CEPH_CRYPTO_MD5_DIGESTSIZE) != 0) {
op_ret = -ERR_BAD_DIGEST;
s->err.message = "The Content-MD5 you specified did not match what we received.";
ldpp_dout(this, 5) << s->err.message
<< " Specified content md5: " << content_md5
<< ", calculated content md5: " << data_hash_res
<< dendl;
return;
}
}
if (!parser.parse(buf, data.length(), 1)) {
op_ret = -ERR_MALFORMED_XML;
return;
}
try {
RGWXMLDecoder::decode_xml("LifecycleConfiguration", config, &parser);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "Bad lifecycle configuration: " << err << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
op_ret = config.rebuild(new_config);
if (op_ret < 0)
return;
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
XMLFormatter xf;
new_config.dump_xml(&xf);
stringstream ss;
xf.flush(ss);
ldpp_dout(this, 15) << "New LifecycleConfiguration:" << ss.str() << dendl;
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = driver->get_rgwlc()->set_bucket_config(s->bucket.get(), s->bucket_attrs, &new_config);
if (op_ret < 0) {
return;
}
return;
}
void RGWDeleteLC::execute(optional_yield y)
{
bufferlist data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = driver->get_rgwlc()->remove_bucket_config(s->bucket.get(), s->bucket_attrs);
if (op_ret < 0) {
return;
}
return;
}
int RGWGetCORS::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketCORS);
}
void RGWGetCORS::execute(optional_yield y)
{
op_ret = read_bucket_cors();
if (op_ret < 0)
return ;
if (!cors_exist) {
ldpp_dout(this, 2) << "No CORS configuration set yet for this bucket" << dendl;
op_ret = -ERR_NO_CORS_FOUND;
return;
}
}
int RGWPutCORS::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketCORS);
}
void RGWPutCORS::execute(optional_yield y)
{
rgw_raw_obj obj;
op_ret = get_params(y);
if (op_ret < 0)
return;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this] {
rgw::sal::Attrs attrs(s->bucket_attrs);
attrs[RGW_ATTR_CORS] = cors_bl;
return s->bucket->merge_and_store_attrs(this, attrs, s->yield);
}, y);
}
int RGWDeleteCORS::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
// No separate delete permission
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketCORS);
}
void RGWDeleteCORS::execute(optional_yield y)
{
bufferlist data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this] {
op_ret = read_bucket_cors();
if (op_ret < 0)
return op_ret;
if (!cors_exist) {
ldpp_dout(this, 2) << "No CORS configuration set yet for this bucket" << dendl;
op_ret = -ENOENT;
return op_ret;
}
rgw::sal::Attrs attrs(s->bucket_attrs);
attrs.erase(RGW_ATTR_CORS);
op_ret = s->bucket->merge_and_store_attrs(this, attrs, s->yield);
if (op_ret < 0) {
ldpp_dout(this, 0) << "RGWLC::RGWDeleteCORS() failed to set attrs on bucket=" << s->bucket->get_name()
<< " returned err=" << op_ret << dendl;
}
return op_ret;
}, y);
}
void RGWOptionsCORS::get_response_params(string& hdrs, string& exp_hdrs, unsigned *max_age) {
get_cors_response_headers(this, rule, req_hdrs, hdrs, exp_hdrs, max_age);
}
int RGWOptionsCORS::validate_cors_request(RGWCORSConfiguration *cc) {
rule = cc->host_name_rule(origin);
if (!rule) {
ldpp_dout(this, 10) << "There is no cors rule present for " << origin << dendl;
return -ENOENT;
}
if (!validate_cors_rule_method(this, rule, req_meth)) {
return -ENOENT;
}
if (!validate_cors_rule_header(this, rule, req_hdrs)) {
return -ENOENT;
}
return 0;
}
void RGWOptionsCORS::execute(optional_yield y)
{
op_ret = read_bucket_cors();
if (op_ret < 0)
return;
origin = s->info.env->get("HTTP_ORIGIN");
if (!origin) {
ldpp_dout(this, 0) << "Missing mandatory Origin header" << dendl;
op_ret = -EINVAL;
return;
}
req_meth = s->info.env->get("HTTP_ACCESS_CONTROL_REQUEST_METHOD");
if (!req_meth) {
ldpp_dout(this, 0) << "Missing mandatory Access-control-request-method header" << dendl;
op_ret = -EINVAL;
return;
}
if (!cors_exist) {
ldpp_dout(this, 2) << "No CORS configuration set yet for this bucket" << dendl;
op_ret = -ENOENT;
return;
}
req_hdrs = s->info.env->get("HTTP_ACCESS_CONTROL_REQUEST_HEADERS");
op_ret = validate_cors_request(&bucket_cors);
if (!rule) {
origin = req_meth = NULL;
return;
}
return;
}
int RGWGetRequestPayment::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketRequestPayment);
}
void RGWGetRequestPayment::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetRequestPayment::execute(optional_yield y)
{
requester_pays = s->bucket->get_info().requester_pays;
}
int RGWSetRequestPayment::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketRequestPayment);
}
void RGWSetRequestPayment::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWSetRequestPayment::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, in_data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
s->bucket->get_info().requester_pays = requester_pays;
op_ret = s->bucket->put_info(this, false, real_time(), y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket->get_name()
<< " returned err=" << op_ret << dendl;
return;
}
s->bucket_attrs = s->bucket->get_attrs();
}
int RGWInitMultipart::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
// add server-side encryption headers
rgw_iam_add_crypt_attrs(s->env, s->info.crypt_attribute_map);
if (s->iam_policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
rgw::IAM::Effect e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
ARN obj_arn(s->object->get_obj());
if (s->iam_policy) {
e = s->iam_policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3PutObject,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow)) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
return 0;
}
}
return -EACCES;
}
if (e == Effect::Allow || identity_policy_res == Effect::Allow) {
return 0;
}
}
if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
return 0;
}
void RGWInitMultipart::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWInitMultipart::execute(optional_yield y)
{
multipart_trace = tracing::rgw::tracer.start_trace(tracing::rgw::MULTIPART, s->trace_enabled);
bufferlist aclbl, tracebl;
rgw::sal::Attrs attrs;
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
if (rgw::sal::Object::empty(s->object.get()))
return;
if (multipart_trace) {
tracing::encode(multipart_trace->GetContext(), tracebl);
attrs[RGW_ATTR_TRACE] = tracebl;
}
policy.encode(aclbl);
attrs[RGW_ATTR_ACL] = aclbl;
populate_with_generic_attrs(s, attrs);
/* select encryption mode */
op_ret = prepare_encryption(attrs);
if (op_ret != 0)
return;
op_ret = rgw_get_request_metadata(this, s->cct, s->info, attrs);
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::MultipartUpload> upload;
upload = s->bucket->get_multipart_upload(s->object->get_name(),
upload_id);
op_ret = upload->init(this, s->yield, s->owner, s->dest_placement, attrs);
if (op_ret == 0) {
upload_id = upload->get_upload_id();
}
s->trace->SetAttribute(tracing::rgw::UPLOAD_ID, upload_id);
multipart_trace->UpdateName(tracing::rgw::MULTIPART + upload_id);
}
int RGWCompleteMultipart::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
// add server-side encryption headers
rgw_iam_add_crypt_attrs(s->env, s->info.crypt_attribute_map);
if (s->iam_policy || ! s->iam_user_policies.empty() || ! s->session_policies.empty()) {
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
rgw::IAM::Effect e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
rgw::ARN obj_arn(s->object->get_obj());
if (s->iam_policy) {
e = s->iam_policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3PutObject,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow)) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
return 0;
}
}
return -EACCES;
}
if (e == Effect::Allow || identity_policy_res == Effect::Allow) {
return 0;
}
}
if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
return 0;
}
void RGWCompleteMultipart::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWCompleteMultipart::execute(optional_yield y)
{
RGWMultiCompleteUpload *parts;
RGWMultiXMLParser parser;
std::unique_ptr<rgw::sal::MultipartUpload> upload;
off_t ofs = 0;
std::unique_ptr<rgw::sal::Object> meta_obj;
std::unique_ptr<rgw::sal::Object> target_obj;
uint64_t olh_epoch = 0;
op_ret = get_params(y);
if (op_ret < 0)
return;
op_ret = get_system_versioning_params(s, &olh_epoch, &version_id);
if (op_ret < 0) {
return;
}
if (!data.length()) {
op_ret = -ERR_MALFORMED_XML;
return;
}
if (!parser.init()) {
op_ret = -EIO;
return;
}
if (!parser.parse(data.c_str(), data.length(), 1)) {
op_ret = -ERR_MALFORMED_XML;
return;
}
parts = static_cast<RGWMultiCompleteUpload *>(parser.find_first("CompleteMultipartUpload"));
if (!parts || parts->parts.empty()) {
// CompletedMultipartUpload is incorrect but some versions of some libraries use it, see PR #41700
parts = static_cast<RGWMultiCompleteUpload *>(parser.find_first("CompletedMultipartUpload"));
}
if (!parts || parts->parts.empty()) {
op_ret = -ERR_MALFORMED_XML;
return;
}
if ((int)parts->parts.size() >
s->cct->_conf->rgw_multipart_part_upload_limit) {
op_ret = -ERANGE;
return;
}
upload = s->bucket->get_multipart_upload(s->object->get_name(), upload_id);
RGWCompressionInfo cs_info;
bool compressed = false;
uint64_t accounted_size = 0;
list<rgw_obj_index_key> remove_objs; /* objects to be removed from index listing */
meta_obj = upload->get_meta_obj();
meta_obj->set_in_extra_data(true);
meta_obj->set_hash_source(s->object->get_name());
/*take a cls lock on meta_obj to prevent racing completions (or retries)
from deleting the parts*/
int max_lock_secs_mp =
s->cct->_conf.get_val<int64_t>("rgw_mp_lock_max_time");
utime_t dur(max_lock_secs_mp, 0);
serializer = meta_obj->get_serializer(this, "RGWCompleteMultipart");
op_ret = serializer->try_lock(this, dur, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "failed to acquire lock" << dendl;
if (op_ret == -ENOENT && check_previously_completed(parts)) {
ldpp_dout(this, 1) << "NOTICE: This multipart completion is already completed" << dendl;
op_ret = 0;
return;
}
op_ret = -ERR_INTERNAL_ERROR;
s->err.message = "This multipart completion is already in progress";
return;
}
op_ret = meta_obj->get_obj_attrs(s->yield, this);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get obj attrs, obj=" << meta_obj
<< " ret=" << op_ret << dendl;
return;
}
s->trace->SetAttribute(tracing::rgw::UPLOAD_ID, upload_id);
jspan_context trace_ctx(false, false);
extract_span_context(meta_obj->get_attrs(), trace_ctx);
multipart_trace = tracing::rgw::tracer.add_span(name(), trace_ctx);
// make reservation for notification if needed
std::unique_ptr<rgw::sal::Notification> res
= driver->get_notification(meta_obj.get(), nullptr, s, rgw::notify::ObjectCreatedCompleteMultipartUpload, y, &s->object->get_name());
op_ret = res->publish_reserve(this);
if (op_ret < 0) {
return;
}
target_obj = s->bucket->get_object(rgw_obj_key(s->object->get_name()));
if (s->bucket->versioning_enabled()) {
if (!version_id.empty()) {
target_obj->set_instance(version_id);
} else {
target_obj->gen_rand_obj_instance_name();
version_id = target_obj->get_instance();
}
}
target_obj->set_attrs(meta_obj->get_attrs());
op_ret = upload->complete(this, y, s->cct, parts->parts, remove_objs, accounted_size, compressed, cs_info, ofs, s->req_id, s->owner, olh_epoch, target_obj.get());
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: upload complete failed ret=" << op_ret << dendl;
return;
}
// remove the upload meta object ; the meta object is not versioned
// when the bucket is, as that would add an unneeded delete marker
int r = meta_obj->delete_object(this, y, true /* prevent versioning */);
if (r >= 0) {
/* serializer's exclusive lock is released */
serializer->clear_locked();
} else {
ldpp_dout(this, 0) << "WARNING: failed to remove object " << meta_obj << dendl;
}
// send request to notification manager
int ret = res->publish_commit(this, ofs, upload->get_mtime(), etag, target_obj->get_instance());
if (ret < 0) {
ldpp_dout(this, 1) << "ERROR: publishing notification failed, with error: " << ret << dendl;
// too late to rollback operation, hence op_ret is not set here
}
} // RGWCompleteMultipart::execute
bool RGWCompleteMultipart::check_previously_completed(const RGWMultiCompleteUpload* parts)
{
// re-calculate the etag from the parts and compare to the existing object
int ret = s->object->get_obj_attrs(s->yield, this);
if (ret < 0) {
ldpp_dout(this, 0) << __func__ << "() ERROR: get_obj_attrs() returned ret=" << ret << dendl;
return false;
}
rgw::sal::Attrs sattrs = s->object->get_attrs();
string oetag = sattrs[RGW_ATTR_ETAG].to_str();
MD5 hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
for (const auto& [index, part] : parts->parts) {
std::string partetag = rgw_string_unquote(part);
char petag[CEPH_CRYPTO_MD5_DIGESTSIZE];
hex_to_buf(partetag.c_str(), petag, CEPH_CRYPTO_MD5_DIGESTSIZE);
hash.Update((const unsigned char *)petag, sizeof(petag));
ldpp_dout(this, 20) << __func__ << "() re-calculating multipart etag: part: "
<< index << ", etag: " << partetag << dendl;
}
unsigned char final_etag[CEPH_CRYPTO_MD5_DIGESTSIZE];
char final_etag_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 16];
hash.Final(final_etag);
buf_to_hex(final_etag, CEPH_CRYPTO_MD5_DIGESTSIZE, final_etag_str);
snprintf(&final_etag_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2], sizeof(final_etag_str) - CEPH_CRYPTO_MD5_DIGESTSIZE * 2,
"-%lld", (long long)parts->parts.size());
if (oetag.compare(final_etag_str) != 0) {
ldpp_dout(this, 1) << __func__ << "() NOTICE: etag mismatch: object etag:"
<< oetag << ", re-calculated etag:" << final_etag_str << dendl;
return false;
}
ldpp_dout(this, 5) << __func__ << "() object etag and re-calculated etag match, etag: " << oetag << dendl;
return true;
}
void RGWCompleteMultipart::complete()
{
/* release exclusive lock iff not already */
if (unlikely(serializer.get() && serializer->is_locked())) {
int r = serializer->unlock();
if (r < 0) {
ldpp_dout(this, 0) << "WARNING: failed to unlock " << *serializer.get() << dendl;
}
}
etag = s->object->get_attrs()[RGW_ATTR_ETAG].to_str();
send_response();
}
int RGWAbortMultipart::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (s->iam_policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3AbortMultipartUpload,
s->object->get_obj());
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
rgw::IAM::Effect e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
ARN obj_arn(s->object->get_obj());
if (s->iam_policy) {
e = s->iam_policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3AbortMultipartUpload,
obj_arn, princ_type);
}
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject,
s->object->get_obj());
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow)) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
return 0;
}
}
return -EACCES;
}
if (e == Effect::Allow || identity_policy_res == Effect::Allow) {
return 0;
}
}
if (!verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
return 0;
}
void RGWAbortMultipart::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWAbortMultipart::execute(optional_yield y)
{
op_ret = -EINVAL;
string upload_id;
upload_id = s->info.args.get("uploadId");
std::unique_ptr<rgw::sal::Object> meta_obj;
std::unique_ptr<rgw::sal::MultipartUpload> upload;
if (upload_id.empty() || rgw::sal::Object::empty(s->object.get()))
return;
upload = s->bucket->get_multipart_upload(s->object->get_name(), upload_id);
jspan_context trace_ctx(false, false);
if (tracing::rgw::tracer.is_enabled()) {
// read meta object attributes for trace info
meta_obj = upload->get_meta_obj();
meta_obj->set_in_extra_data(true);
meta_obj->get_obj_attrs(s->yield, this);
extract_span_context(meta_obj->get_attrs(), trace_ctx);
}
multipart_trace = tracing::rgw::tracer.add_span(name(), trace_ctx);
op_ret = upload->abort(this, s->cct, y);
}
int RGWListMultipart::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s, rgw::IAM::s3ListMultipartUploadParts))
return -EACCES;
return 0;
}
void RGWListMultipart::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWListMultipart::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
upload = s->bucket->get_multipart_upload(s->object->get_name(), upload_id);
rgw::sal::Attrs attrs;
op_ret = upload->get_info(this, s->yield, &placement, &attrs);
/* decode policy */
map<string, bufferlist>::iterator iter = attrs.find(RGW_ATTR_ACL);
if (iter != attrs.end()) {
auto bliter = iter->second.cbegin();
try {
policy.decode(bliter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: could not decode policy, caught buffer::error" << dendl;
op_ret = -EIO;
}
}
if (op_ret < 0)
return;
op_ret = upload->list_parts(this, s->cct, max_parts, marker, NULL, &truncated, y);
}
int RGWListBucketMultiparts::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this,
s,
rgw::IAM::s3ListBucketMultipartUploads))
return -EACCES;
return 0;
}
void RGWListBucketMultiparts::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWListBucketMultiparts::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
if (s->prot_flags & RGW_REST_SWIFT) {
string path_args;
path_args = s->info.args.get("path");
if (!path_args.empty()) {
if (!delimiter.empty() || !prefix.empty()) {
op_ret = -EINVAL;
return;
}
prefix = path_args;
delimiter="/";
}
}
op_ret = s->bucket->list_multiparts(this, prefix, marker_meta,
delimiter, max_uploads, uploads,
&common_prefixes, &is_truncated, y);
if (op_ret < 0) {
return;
}
if (!uploads.empty()) {
next_marker_key = uploads.back()->get_key();
next_marker_upload_id = uploads.back()->get_upload_id();
}
}
void RGWGetHealthCheck::execute(optional_yield y)
{
if (!g_conf()->rgw_healthcheck_disabling_path.empty() &&
(::access(g_conf()->rgw_healthcheck_disabling_path.c_str(), F_OK) == 0)) {
/* Disabling path specified & existent in the filesystem. */
op_ret = -ERR_SERVICE_UNAVAILABLE; /* 503 */
} else {
op_ret = 0; /* 200 OK */
}
}
int RGWDeleteMultiObj::verify_permission(optional_yield y)
{
int op_ret = get_params(y);
if (op_ret) {
return op_ret;
}
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (s->iam_policy || ! s->iam_user_policies.empty() || ! s->session_policies.empty()) {
if (s->bucket->get_info().obj_lock_enabled() && bypass_governance_mode) {
ARN bucket_arn(s->bucket->get_key());
auto r = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3BypassGovernanceRetention, ARN(s->bucket->get_key()));
if (r == Effect::Deny) {
bypass_perm = false;
} else if (r == Effect::Pass && s->iam_policy) {
r = s->iam_policy->eval(s->env, *s->auth.identity, rgw::IAM::s3BypassGovernanceRetention,
bucket_arn);
if (r == Effect::Deny) {
bypass_perm = false;
}
} else if (r == Effect::Pass && !s->session_policies.empty()) {
r = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3BypassGovernanceRetention, ARN(s->bucket->get_key()));
if (r == Effect::Deny) {
bypass_perm = false;
}
}
}
bool not_versioned = rgw::sal::Object::empty(s->object.get()) || s->object->get_instance().empty();
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
not_versioned ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
ARN(s->bucket->get_key()));
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
rgw::IAM::Effect r = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
rgw::ARN bucket_arn(s->bucket->get_key());
if (s->iam_policy) {
r = s->iam_policy->eval(s->env, *s->auth.identity,
not_versioned ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
bucket_arn,
princ_type);
}
if (r == Effect::Deny)
return -EACCES;
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
not_versioned ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
ARN(s->bucket->get_key()));
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && r == Effect::Allow)) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || r == Effect::Allow) {
return 0;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
return 0;
}
}
return -EACCES;
}
if (r == Effect::Allow || identity_policy_res == Effect::Allow)
return 0;
}
acl_allowed = verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE);
if (!acl_allowed)
return -EACCES;
return 0;
}
void RGWDeleteMultiObj::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWDeleteMultiObj::write_ops_log_entry(rgw_log_entry& entry) const {
int num_err = 0;
int num_ok = 0;
for (auto iter = ops_log_entries.begin();
iter != ops_log_entries.end();
++iter) {
if (iter->error) {
num_err++;
} else {
num_ok++;
}
}
entry.delete_multi_obj_meta.num_err = num_err;
entry.delete_multi_obj_meta.num_ok = num_ok;
entry.delete_multi_obj_meta.objects = std::move(ops_log_entries);
}
void RGWDeleteMultiObj::wait_flush(optional_yield y,
boost::asio::deadline_timer *formatter_flush_cond,
std::function<bool()> predicate)
{
if (y && formatter_flush_cond) {
auto yc = y.get_yield_context();
while (!predicate()) {
boost::system::error_code error;
formatter_flush_cond->async_wait(yc[error]);
rgw_flush_formatter(s, s->formatter);
}
}
}
void RGWDeleteMultiObj::handle_individual_object(const rgw_obj_key& o, optional_yield y,
boost::asio::deadline_timer *formatter_flush_cond)
{
std::string version_id;
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(o);
if (s->iam_policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
o.instance.empty() ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
ARN(obj->get_obj()));
if (identity_policy_res == Effect::Deny) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
rgw::IAM::Effect e = Effect::Pass;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
if (s->iam_policy) {
ARN obj_arn(obj->get_obj());
e = s->iam_policy->eval(s->env,
*s->auth.identity,
o.instance.empty() ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
obj_arn,
princ_type);
}
if (e == Effect::Deny) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
o.instance.empty() ?
rgw::IAM::s3DeleteObject :
rgw::IAM::s3DeleteObjectVersion,
ARN(obj->get_obj()));
if (session_policy_res == Effect::Deny) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) &&
(session_policy_res != Effect::Allow || e != Effect::Allow)) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) && e != Effect::Allow) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res != Effect::Allow || identity_policy_res != Effect::Allow) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
}
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
if ((identity_policy_res == Effect::Pass && e == Effect::Pass && !acl_allowed)) {
send_partial_response(o, false, "", -EACCES, formatter_flush_cond);
return;
}
}
uint64_t obj_size = 0;
std::string etag;
if (!rgw::sal::Object::empty(obj.get())) {
RGWObjState* astate = nullptr;
bool check_obj_lock = obj->have_instance() && bucket->get_info().obj_lock_enabled();
const auto ret = obj->get_obj_state(this, &astate, y, true);
if (ret < 0) {
if (ret == -ENOENT) {
// object maybe delete_marker, skip check_obj_lock
check_obj_lock = false;
} else {
// Something went wrong.
send_partial_response(o, false, "", ret, formatter_flush_cond);
return;
}
} else {
obj_size = astate->size;
etag = astate->attrset[RGW_ATTR_ETAG].to_str();
}
if (check_obj_lock) {
ceph_assert(astate);
int object_lock_response = verify_object_lock(this, astate->attrset, bypass_perm, bypass_governance_mode);
if (object_lock_response != 0) {
send_partial_response(o, false, "", object_lock_response, formatter_flush_cond);
return;
}
}
}
// make reservation for notification if needed
const auto versioned_object = s->bucket->versioning_enabled();
const auto event_type = versioned_object && obj->get_instance().empty() ?
rgw::notify::ObjectRemovedDeleteMarkerCreated :
rgw::notify::ObjectRemovedDelete;
std::unique_ptr<rgw::sal::Notification> res
= driver->get_notification(obj.get(), s->src_object.get(), s, event_type, y);
op_ret = res->publish_reserve(this);
if (op_ret < 0) {
send_partial_response(o, false, "", op_ret, formatter_flush_cond);
return;
}
obj->set_atomic();
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 = s->owner;
del_op->params.bucket_owner = s->bucket_owner;
del_op->params.marker_version_id = version_id;
op_ret = del_op->delete_obj(this, y);
if (op_ret == -ENOENT) {
op_ret = 0;
}
send_partial_response(o, del_op->result.delete_marker, del_op->result.version_id, op_ret, formatter_flush_cond);
// send request to notification manager
int ret = res->publish_commit(this, obj_size, ceph::real_clock::now(), etag, version_id);
if (ret < 0) {
ldpp_dout(this, 1) << "ERROR: publishing notification failed, with error: " << ret << dendl;
// too late to rollback operation, hence op_ret is not set here
}
}
void RGWDeleteMultiObj::execute(optional_yield y)
{
RGWMultiDelDelete *multi_delete;
vector<rgw_obj_key>::iterator iter;
RGWMultiDelXMLParser parser;
uint32_t aio_count = 0;
const uint32_t max_aio = std::max<uint32_t>(1, s->cct->_conf->rgw_multi_obj_del_max_aio);
char* buf;
std::optional<boost::asio::deadline_timer> formatter_flush_cond;
if (y) {
formatter_flush_cond = std::make_optional<boost::asio::deadline_timer>(y.get_io_context());
}
buf = data.c_str();
if (!buf) {
op_ret = -EINVAL;
goto error;
}
if (!parser.init()) {
op_ret = -EINVAL;
goto error;
}
if (!parser.parse(buf, data.length(), 1)) {
op_ret = -EINVAL;
goto error;
}
multi_delete = static_cast<RGWMultiDelDelete *>(parser.find_first("Delete"));
if (!multi_delete) {
op_ret = -EINVAL;
goto error;
} else {
#define DELETE_MULTI_OBJ_MAX_NUM 1000
int max_num = s->cct->_conf->rgw_delete_multi_obj_max_num;
if (max_num < 0) {
max_num = DELETE_MULTI_OBJ_MAX_NUM;
}
int multi_delete_object_num = multi_delete->objects.size();
if (multi_delete_object_num > max_num) {
op_ret = -ERR_MALFORMED_XML;
goto error;
}
}
if (multi_delete->is_quiet())
quiet = true;
if (s->bucket->get_info().mfa_enabled()) {
bool has_versioned = false;
for (auto i : multi_delete->objects) {
if (!i.instance.empty()) {
has_versioned = true;
break;
}
}
if (has_versioned && !s->mfa_verified) {
ldpp_dout(this, 5) << "NOTICE: multi-object delete request with a versioned object, mfa auth not provided" << dendl;
op_ret = -ERR_MFA_REQUIRED;
goto error;
}
}
begin_response();
if (multi_delete->objects.empty()) {
goto done;
}
for (iter = multi_delete->objects.begin();
iter != multi_delete->objects.end();
++iter) {
rgw_obj_key obj_key = *iter;
if (y) {
wait_flush(y, &*formatter_flush_cond, [&aio_count, max_aio] {
return aio_count < max_aio;
});
aio_count++;
spawn::spawn(y.get_yield_context(), [this, &y, &aio_count, obj_key, &formatter_flush_cond] (yield_context yield) {
handle_individual_object(obj_key, optional_yield { y.get_io_context(), yield }, &*formatter_flush_cond);
aio_count--;
});
} else {
handle_individual_object(obj_key, y, nullptr);
}
}
if (formatter_flush_cond) {
wait_flush(y, &*formatter_flush_cond, [this, n=multi_delete->objects.size()] {
return n == ops_log_entries.size();
});
}
/* set the return code to zero, errors at this point will be
dumped to the response */
op_ret = 0;
done:
// will likely segfault if begin_response() has not been called
end_response();
return;
error:
send_status();
return;
}
bool RGWBulkDelete::Deleter::verify_permission(RGWBucketInfo& binfo,
map<string, bufferlist>& battrs,
ACLOwner& bucket_owner /* out */,
optional_yield y)
{
RGWAccessControlPolicy bacl(driver->ctx());
int ret = read_bucket_policy(dpp, driver, s, binfo, battrs, &bacl, binfo.bucket, y);
if (ret < 0) {
return false;
}
auto policy = get_iam_policy_from_attr(s->cct, battrs, binfo.bucket.tenant);
bucket_owner = bacl.get_owner();
/* We can use global user_acl because each BulkDelete request is allowed
* to work on entities from a single account only. */
return verify_bucket_permission(dpp, s, binfo.bucket, s->user_acl.get(),
&bacl, policy, s->iam_user_policies, s->session_policies, rgw::IAM::s3DeleteBucket);
}
bool RGWBulkDelete::Deleter::delete_single(const acct_path_t& path, optional_yield y)
{
std::unique_ptr<rgw::sal::Bucket> bucket;
ACLOwner bowner;
RGWObjVersionTracker ot;
int ret = driver->get_bucket(dpp, s->user.get(), s->user->get_tenant(), path.bucket_name, &bucket, y);
if (ret < 0) {
goto binfo_fail;
}
ret = bucket->load_bucket(dpp, s->yield);
if (ret < 0) {
goto binfo_fail;
}
if (!verify_permission(bucket->get_info(), bucket->get_attrs(), bowner, y)) {
ret = -EACCES;
goto auth_fail;
}
if (!path.obj_key.empty()) {
ACLOwner bucket_owner;
bucket_owner.set_id(bucket->get_info().owner);
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(path.obj_key);
obj->set_atomic();
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 = bowner;
del_op->params.bucket_owner = bucket_owner;
ret = del_op->delete_obj(dpp, y);
if (ret < 0) {
goto delop_fail;
}
} else {
ret = bucket->remove_bucket(dpp, false, true, &s->info, s->yield);
if (ret < 0) {
goto delop_fail;
}
}
num_deleted++;
return true;
binfo_fail:
if (-ENOENT == ret) {
ldpp_dout(dpp, 20) << "cannot find bucket = " << path.bucket_name << dendl;
num_unfound++;
} else {
ldpp_dout(dpp, 20) << "cannot get bucket info, ret = " << ret << dendl;
fail_desc_t failed_item = {
.err = ret,
.path = path
};
failures.push_back(failed_item);
}
return false;
auth_fail:
ldpp_dout(dpp, 20) << "wrong auth for " << path << dendl;
{
fail_desc_t failed_item = {
.err = ret,
.path = path
};
failures.push_back(failed_item);
}
return false;
delop_fail:
if (-ENOENT == ret) {
ldpp_dout(dpp, 20) << "cannot find entry " << path << dendl;
num_unfound++;
} else {
fail_desc_t failed_item = {
.err = ret,
.path = path
};
failures.push_back(failed_item);
}
return false;
}
bool RGWBulkDelete::Deleter::delete_chunk(const std::list<acct_path_t>& paths, optional_yield y)
{
ldpp_dout(dpp, 20) << "in delete_chunk" << dendl;
for (auto path : paths) {
ldpp_dout(dpp, 20) << "bulk deleting path: " << path << dendl;
delete_single(path, y);
}
return true;
}
int RGWBulkDelete::verify_permission(optional_yield y)
{
return 0;
}
void RGWBulkDelete::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWBulkDelete::execute(optional_yield y)
{
deleter = std::unique_ptr<Deleter>(new Deleter(this, driver, s));
bool is_truncated = false;
do {
list<RGWBulkDelete::acct_path_t> items;
int ret = get_data(items, &is_truncated);
if (ret < 0) {
return;
}
ret = deleter->delete_chunk(items, y);
} while (!op_ret && is_truncated);
return;
}
constexpr std::array<int, 2> RGWBulkUploadOp::terminal_errors;
int RGWBulkUploadOp::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if (! verify_user_permission_no_policy(this, s, RGW_PERM_WRITE)) {
return -EACCES;
}
if (s->user->get_tenant() != s->bucket_tenant) {
ldpp_dout(this, 10) << "user cannot create a bucket in a different tenant"
<< " (user_id.tenant=" << s->user->get_tenant()
<< " requested=" << s->bucket_tenant << ")" << dendl;
return -EACCES;
}
if (s->user->get_max_buckets() < 0) {
return -EPERM;
}
return 0;
}
void RGWBulkUploadOp::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
boost::optional<std::pair<std::string, rgw_obj_key>>
RGWBulkUploadOp::parse_path(const std::string_view& path)
{
/* We need to skip all slashes at the beginning in order to preserve
* compliance with Swift. */
const size_t start_pos = path.find_first_not_of('/');
if (std::string_view::npos != start_pos) {
/* Seperator is the first slash after the leading ones. */
const size_t sep_pos = path.substr(start_pos).find('/');
if (std::string_view::npos != sep_pos) {
const auto bucket_name = path.substr(start_pos, sep_pos - start_pos);
const auto obj_name = path.substr(sep_pos + 1);
return std::make_pair(std::string(bucket_name),
rgw_obj_key(std::string(obj_name)));
} else {
/* It's guaranteed here that bucket name is at least one character
* long and is different than slash. */
return std::make_pair(std::string(path.substr(start_pos)),
rgw_obj_key());
}
}
return none;
}
std::pair<std::string, std::string>
RGWBulkUploadOp::handle_upload_path(req_state *s)
{
std::string bucket_path, file_prefix;
if (! s->init_state.url_bucket.empty()) {
file_prefix = bucket_path = s->init_state.url_bucket + "/";
if (!rgw::sal::Object::empty(s->object.get())) {
const std::string& object_name = s->object->get_name();
/* As rgw_obj_key::empty() already verified emptiness of s->object->get_name(),
* we can safely examine its last element. */
if (object_name.back() == '/') {
file_prefix.append(object_name);
} else {
file_prefix.append(object_name).append("/");
}
}
}
return std::make_pair(bucket_path, file_prefix);
}
int RGWBulkUploadOp::handle_dir_verify_permission(optional_yield y)
{
if (s->user->get_max_buckets() > 0) {
rgw::sal::BucketList buckets;
std::string marker;
op_ret = s->user->list_buckets(this, marker, std::string(), s->user->get_max_buckets(),
false, buckets, y);
if (op_ret < 0) {
return op_ret;
}
if (buckets.count() >= static_cast<size_t>(s->user->get_max_buckets())) {
return -ERR_TOO_MANY_BUCKETS;
}
}
return 0;
}
static void forward_req_info(const DoutPrefixProvider *dpp, CephContext *cct, req_info& info, const std::string& bucket_name)
{
/* the request of container or object level will contain bucket name.
* only at account level need to append the bucket name */
if (info.script_uri.find(bucket_name) != std::string::npos) {
return;
}
ldpp_dout(dpp, 20) << "append the bucket: "<< bucket_name << " to req_info" << dendl;
info.script_uri.append("/").append(bucket_name);
info.request_uri_aws4 = info.request_uri = info.script_uri;
info.effective_uri = "/" + bucket_name;
}
void RGWBulkUploadOp::init(rgw::sal::Driver* const driver,
req_state* const s,
RGWHandler* const h)
{
RGWOp::init(driver, s, h);
}
int RGWBulkUploadOp::handle_dir(const std::string_view path, optional_yield y)
{
ldpp_dout(this, 20) << "got directory=" << path << dendl;
op_ret = handle_dir_verify_permission(y);
if (op_ret < 0) {
return op_ret;
}
std::string bucket_name;
rgw_obj_key object_junk;
std::tie(bucket_name, object_junk) = *parse_path(path);
/* we need to make sure we read bucket info, it's not read before for this
* specific request */
std::unique_ptr<rgw::sal::Bucket> bucket;
/* Create metadata: ACLs. */
std::map<std::string, ceph::bufferlist> attrs;
RGWAccessControlPolicy policy;
policy.create_default(s->user->get_id(), s->user->get_display_name());
ceph::bufferlist aclbl;
policy.encode(aclbl);
attrs.emplace(RGW_ATTR_ACL, std::move(aclbl));
obj_version objv, ep_objv;
bool bucket_exists;
RGWQuotaInfo quota_info;
const RGWQuotaInfo* pquota_info = nullptr;
RGWBucketInfo out_info;
string swift_ver_location;
rgw_bucket new_bucket;
req_info info = s->info;
new_bucket.tenant = s->bucket_tenant; /* ignored if bucket exists */
new_bucket.name = bucket_name;
rgw_placement_rule placement_rule;
placement_rule.storage_class = s->info.storage_class;
forward_req_info(this, s->cct, info, bucket_name);
op_ret = s->user->create_bucket(this, new_bucket,
driver->get_zone()->get_zonegroup().get_id(),
placement_rule, swift_ver_location,
pquota_info, policy, attrs,
out_info, ep_objv,
true, false, &bucket_exists,
info, &bucket, y);
/* continue if EEXIST and create_bucket will fail below. this way we can
* recover from a partial create by retrying it. */
ldpp_dout(this, 20) << "rgw_create_bucket returned ret=" << op_ret
<< ", bucket=" << bucket << dendl;
return op_ret;
}
bool RGWBulkUploadOp::handle_file_verify_permission(RGWBucketInfo& binfo,
const rgw_obj& obj,
std::map<std::string, ceph::bufferlist>& battrs,
ACLOwner& bucket_owner /* out */,
optional_yield y)
{
RGWAccessControlPolicy bacl(driver->ctx());
op_ret = read_bucket_policy(this, driver, s, binfo, battrs, &bacl, binfo.bucket, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "cannot read_policy() for bucket" << dendl;
return false;
}
auto policy = get_iam_policy_from_attr(s->cct, battrs, binfo.bucket.tenant);
bucket_owner = bacl.get_owner();
if (policy || ! s->iam_user_policies.empty() || !s->session_policies.empty()) {
auto identity_policy_res = eval_identity_or_session_policies(this, s->iam_user_policies, s->env,
rgw::IAM::s3PutObject, obj);
if (identity_policy_res == Effect::Deny) {
return false;
}
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
ARN obj_arn(obj);
auto e = policy->eval(s->env, *s->auth.identity,
rgw::IAM::s3PutObject, obj_arn, princ_type);
if (e == Effect::Deny) {
return false;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(this, s->session_policies, s->env,
rgw::IAM::s3PutObject, obj);
if (session_policy_res == Effect::Deny) {
return false;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow)) {
return true;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow) {
return true;
}
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) {
return true;
}
}
return false;
}
if (e == Effect::Allow || identity_policy_res == Effect::Allow) {
return true;
}
}
return verify_bucket_permission_no_policy(this, s, s->user_acl.get(),
&bacl, RGW_PERM_WRITE);
}
int RGWBulkUploadOp::handle_file(const std::string_view path,
const size_t size,
AlignedStreamGetter& body, optional_yield y)
{
ldpp_dout(this, 20) << "got file=" << path << ", size=" << size << dendl;
if (size > static_cast<size_t>(s->cct->_conf->rgw_max_put_size)) {
op_ret = -ERR_TOO_LARGE;
return op_ret;
}
std::string bucket_name;
rgw_obj_key object;
std::tie(bucket_name, object) = *parse_path(path);
std::unique_ptr<rgw::sal::Bucket> bucket;
ACLOwner bowner;
op_ret = driver->get_bucket(this, s->user.get(), rgw_bucket(rgw_bucket_key(s->user->get_tenant(), bucket_name)), &bucket, y);
if (op_ret < 0) {
if (op_ret == -ENOENT) {
ldpp_dout(this, 20) << "non existent directory=" << bucket_name << dendl;
}
return op_ret;
}
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object);
if (! handle_file_verify_permission(bucket->get_info(),
obj->get_obj(),
bucket->get_attrs(), bowner, y)) {
ldpp_dout(this, 20) << "object creation unauthorized" << dendl;
op_ret = -EACCES;
return op_ret;
}
op_ret = bucket->check_quota(this, quota, size, y);
if (op_ret < 0) {
return op_ret;
}
if (bucket->versioning_enabled()) {
obj->gen_rand_obj_instance_name();
}
rgw_placement_rule dest_placement = s->dest_placement;
dest_placement.inherit_from(bucket->get_placement_rule());
std::unique_ptr<rgw::sal::Writer> processor;
processor = driver->get_atomic_writer(this, s->yield, obj.get(),
bowner.get_id(),
&s->dest_placement, 0, s->req_id);
op_ret = processor->prepare(s->yield);
if (op_ret < 0) {
ldpp_dout(this, 20) << "cannot prepare processor due to ret=" << op_ret << dendl;
return op_ret;
}
/* No filters by default. */
rgw::sal::DataProcessor *filter = processor.get();
const auto& compression_type = driver->get_compression_type(dest_placement);
CompressorRef plugin;
boost::optional<RGWPutObj_Compress> compressor;
if (compression_type != "none") {
plugin = Compressor::create(s->cct, compression_type);
if (! plugin) {
ldpp_dout(this, 1) << "Cannot load plugin for rgw_compression_type "
<< compression_type << dendl;
} else {
compressor.emplace(s->cct, plugin, filter);
filter = &*compressor;
}
}
/* Upload file content. */
ssize_t len = 0;
size_t ofs = 0;
MD5 hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
do {
ceph::bufferlist data;
len = body.get_at_most(s->cct->_conf->rgw_max_chunk_size, data);
ldpp_dout(this, 20) << "body=" << data.c_str() << dendl;
if (len < 0) {
op_ret = len;
return op_ret;
} else if (len > 0) {
hash.Update((const unsigned char *)data.c_str(), data.length());
op_ret = filter->process(std::move(data), ofs);
if (op_ret < 0) {
ldpp_dout(this, 20) << "filter->process() returned ret=" << op_ret << dendl;
return op_ret;
}
ofs += len;
}
} while (len > 0);
// flush
op_ret = filter->process({}, ofs);
if (op_ret < 0) {
return op_ret;
}
if (ofs != size) {
ldpp_dout(this, 10) << "real file size different from declared" << dendl;
op_ret = -EINVAL;
return op_ret;
}
op_ret = bucket->check_quota(this, quota, size, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "quota exceeded for path=" << path << dendl;
return op_ret;
}
char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
unsigned char m[CEPH_CRYPTO_MD5_DIGESTSIZE];
hash.Final(m);
buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);
/* Create metadata: ETAG. */
std::map<std::string, ceph::bufferlist> attrs;
std::string etag = calc_md5;
ceph::bufferlist etag_bl;
etag_bl.append(etag.c_str(), etag.size() + 1);
attrs.emplace(RGW_ATTR_ETAG, std::move(etag_bl));
/* Create metadata: ACLs. */
RGWAccessControlPolicy policy;
policy.create_default(s->user->get_id(), s->user->get_display_name());
ceph::bufferlist aclbl;
policy.encode(aclbl);
attrs.emplace(RGW_ATTR_ACL, std::move(aclbl));
/* Create metadata: compression info. */
if (compressor && compressor->is_compressed()) {
ceph::bufferlist tmp;
RGWCompressionInfo cs_info;
cs_info.compression_type = plugin->get_type_name();
cs_info.orig_size = size;
cs_info.compressor_message = compressor->get_compressor_message();
cs_info.blocks = std::move(compressor->get_compression_blocks());
encode(cs_info, tmp);
attrs.emplace(RGW_ATTR_COMPRESSION, std::move(tmp));
}
/* Complete the transaction. */
op_ret = processor->complete(size, etag, nullptr, ceph::real_time(),
attrs, ceph::real_time() /* delete_at */,
nullptr, nullptr, nullptr, nullptr, nullptr,
s->yield);
if (op_ret < 0) {
ldpp_dout(this, 20) << "processor::complete returned op_ret=" << op_ret << dendl;
}
return op_ret;
}
void RGWBulkUploadOp::execute(optional_yield y)
{
ceph::bufferlist buffer(64 * 1024);
ldpp_dout(this, 20) << "start" << dendl;
/* Create an instance of stream-abstracting class. Having this indirection
* allows for easy introduction of decompressors like gzip and bzip2. */
auto stream = create_stream();
if (! stream) {
return;
}
/* Handling the $UPLOAD_PATH accordingly to the Swift's Bulk middleware. See:
* https://github.com/openstack/swift/blob/2.13.0/swift/common/middleware/bulk.py#L31-L41 */
std::string bucket_path, file_prefix;
std::tie(bucket_path, file_prefix) = handle_upload_path(s);
auto status = rgw::tar::StatusIndicator::create();
do {
op_ret = stream->get_exactly(rgw::tar::BLOCK_SIZE, buffer);
if (op_ret < 0) {
ldpp_dout(this, 2) << "cannot read header" << dendl;
return;
}
/* We need to re-interpret the buffer as a TAR block. Exactly two blocks
* must be tracked to detect out end-of-archive. It occurs when both of
* them are empty (zeroed). Tracing this particular inter-block dependency
* is responsibility of the rgw::tar::StatusIndicator class. */
boost::optional<rgw::tar::HeaderView> header;
std::tie(status, header) = rgw::tar::interpret_block(status, buffer);
if (! status.empty() && header) {
/* This specific block isn't empty (entirely zeroed), so we can parse
* it as a TAR header and dispatch. At the moment we do support only
* regular files and directories. Everything else (symlinks, devices)
* will be ignored but won't cease the whole upload. */
switch (header->get_filetype()) {
case rgw::tar::FileType::NORMAL_FILE: {
ldpp_dout(this, 2) << "handling regular file" << dendl;
std::string filename;
if (bucket_path.empty())
filename = header->get_filename();
else
filename = file_prefix + std::string(header->get_filename());
auto body = AlignedStreamGetter(0, header->get_filesize(),
rgw::tar::BLOCK_SIZE, *stream);
op_ret = handle_file(filename,
header->get_filesize(),
body, y);
if (! op_ret) {
/* Only regular files counts. */
num_created++;
} else {
failures.emplace_back(op_ret, std::string(filename));
}
break;
}
case rgw::tar::FileType::DIRECTORY: {
ldpp_dout(this, 2) << "handling regular directory" << dendl;
std::string_view dirname = bucket_path.empty() ? header->get_filename() : bucket_path;
op_ret = handle_dir(dirname, y);
if (op_ret < 0 && op_ret != -ERR_BUCKET_EXISTS) {
failures.emplace_back(op_ret, std::string(dirname));
}
break;
}
default: {
/* Not recognized. Skip. */
op_ret = 0;
break;
}
}
/* In case of any problems with sub-request authorization Swift simply
* terminates whole upload immediately. */
if (boost::algorithm::contains(std::initializer_list<int>{ op_ret },
terminal_errors)) {
ldpp_dout(this, 2) << "terminating due to ret=" << op_ret << dendl;
break;
}
} else {
ldpp_dout(this, 2) << "an empty block" << dendl;
op_ret = 0;
}
buffer.clear();
} while (! status.eof());
return;
}
RGWBulkUploadOp::AlignedStreamGetter::~AlignedStreamGetter()
{
const size_t aligned_legnth = length + (-length % alignment);
ceph::bufferlist junk;
DecoratedStreamGetter::get_exactly(aligned_legnth - position, junk);
}
ssize_t RGWBulkUploadOp::AlignedStreamGetter::get_at_most(const size_t want,
ceph::bufferlist& dst)
{
const size_t max_to_read = std::min(want, length - position);
const auto len = DecoratedStreamGetter::get_at_most(max_to_read, dst);
if (len > 0) {
position += len;
}
return len;
}
ssize_t RGWBulkUploadOp::AlignedStreamGetter::get_exactly(const size_t want,
ceph::bufferlist& dst)
{
const auto len = DecoratedStreamGetter::get_exactly(want, dst);
if (len > 0) {
position += len;
}
return len;
}
int RGWGetAttrs::verify_permission(optional_yield y)
{
s->object->set_atomic();
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
auto iam_action = s->object->get_instance().empty() ?
rgw::IAM::s3GetObject :
rgw::IAM::s3GetObjectVersion;
if (!verify_object_permission(this, s, iam_action)) {
return -EACCES;
}
return 0;
}
void RGWGetAttrs::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetAttrs::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0)
return;
s->object->set_atomic();
op_ret = s->object->get_obj_attrs(s->yield, this);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get obj attrs, obj=" << s->object
<< " ret=" << op_ret << dendl;
return;
}
/* XXX RGWObject::get_obj_attrs() does not support filtering (yet) */
auto& obj_attrs = s->object->get_attrs();
if (attrs.size() != 0) {
/* return only attrs requested */
for (auto& att : attrs) {
auto iter = obj_attrs.find(att.first);
if (iter != obj_attrs.end()) {
att.second = iter->second;
}
}
} else {
/* return all attrs */
for (auto& att : obj_attrs) {
attrs.insert(get_attrs_t::value_type(att.first, att.second));;
}
}
return;
}
int RGWRMAttrs::verify_permission(optional_yield y)
{
// This looks to be part of the RGW-NFS machinery and has no S3 or
// Swift equivalent.
bool perm;
if (!rgw::sal::Object::empty(s->object.get())) {
perm = verify_object_permission_no_policy(this, s, RGW_PERM_WRITE);
} else {
perm = verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE);
}
if (!perm)
return -EACCES;
return 0;
}
void RGWRMAttrs::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWRMAttrs::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0)
return;
s->object->set_atomic();
op_ret = s->object->set_obj_attrs(this, nullptr, &attrs, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to delete obj attrs, obj=" << s->object
<< " ret=" << op_ret << dendl;
}
return;
}
int RGWSetAttrs::verify_permission(optional_yield y)
{
// This looks to be part of the RGW-NFS machinery and has no S3 or
// Swift equivalent.
bool perm;
if (!rgw::sal::Object::empty(s->object.get())) {
perm = verify_object_permission_no_policy(this, s, RGW_PERM_WRITE);
} else {
perm = verify_bucket_permission_no_policy(this, s, RGW_PERM_WRITE);
}
if (!perm)
return -EACCES;
return 0;
}
void RGWSetAttrs::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWSetAttrs::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0)
return;
if (!rgw::sal::Object::empty(s->object.get())) {
rgw::sal::Attrs a(attrs);
op_ret = s->object->set_obj_attrs(this, &a, nullptr, y);
} else {
op_ret = s->bucket->merge_and_store_attrs(this, attrs, y);
}
} /* RGWSetAttrs::execute() */
void RGWGetObjLayout::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetObjLayout::execute(optional_yield y)
{
}
int RGWConfigBucketMetaSearch::verify_permission(optional_yield y)
{
if (!s->auth.identity->is_owner_of(s->bucket_owner.get_id())) {
return -EACCES;
}
return 0;
}
void RGWConfigBucketMetaSearch::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWConfigBucketMetaSearch::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "NOTICE: get_params() returned ret=" << op_ret << dendl;
return;
}
s->bucket->get_info().mdsearch_config = mdsearch_config;
op_ret = s->bucket->put_info(this, false, real_time(), y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket->get_name()
<< " returned err=" << op_ret << dendl;
return;
}
s->bucket_attrs = s->bucket->get_attrs();
}
int RGWGetBucketMetaSearch::verify_permission(optional_yield y)
{
if (!s->auth.identity->is_owner_of(s->bucket_owner.get_id())) {
return -EACCES;
}
return 0;
}
void RGWGetBucketMetaSearch::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
int RGWDelBucketMetaSearch::verify_permission(optional_yield y)
{
if (!s->auth.identity->is_owner_of(s->bucket_owner.get_id())) {
return -EACCES;
}
return 0;
}
void RGWDelBucketMetaSearch::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWDelBucketMetaSearch::execute(optional_yield y)
{
s->bucket->get_info().mdsearch_config.clear();
op_ret = s->bucket->put_info(this, false, real_time(), y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "NOTICE: put_bucket_info on bucket=" << s->bucket->get_name()
<< " returned err=" << op_ret << dendl;
return;
}
s->bucket_attrs = s->bucket->get_attrs();
}
RGWHandler::~RGWHandler()
{
}
int RGWHandler::init(rgw::sal::Driver* _driver,
req_state *_s,
rgw::io::BasicClient *cio)
{
driver = _driver;
s = _s;
return 0;
}
int RGWHandler::do_init_permissions(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = rgw_build_bucket_policies(dpp, driver, s, y);
if (ret < 0) {
ldpp_dout(dpp, 10) << "init_permissions on " << s->bucket
<< " failed, ret=" << ret << dendl;
return ret==-ENODATA ? -EACCES : ret;
}
rgw_build_iam_environment(driver, s);
return ret;
}
int RGWHandler::do_read_permissions(RGWOp *op, bool only_bucket, optional_yield y)
{
if (only_bucket) {
/* already read bucket info */
return 0;
}
int ret = rgw_build_object_policies(op, driver, s, op->prefetch_data(), y);
if (ret < 0) {
ldpp_dout(op, 10) << "read_permissions on " << s->bucket << ":"
<< s->object << " only_bucket=" << only_bucket
<< " ret=" << ret << dendl;
if (ret == -ENODATA)
ret = -EACCES;
if (s->auth.identity->is_anonymous() && ret == -EACCES)
ret = -EPERM;
}
return ret;
}
int RGWOp::error_handler(int err_no, string *error_content, optional_yield y) {
return dialect_handler->error_handler(err_no, error_content, y);
}
int RGWHandler::error_handler(int err_no, string *error_content, optional_yield) {
// This is the do-nothing error handler
return err_no;
}
std::ostream& RGWOp::gen_prefix(std::ostream& out) const
{
// append <dialect>:<op name> to the prefix
return s->gen_prefix(out) << s->dialect << ':' << name() << ' ';
}
void RGWDefaultResponseOp::send_response() {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
void RGWPutBucketPolicy::send_response()
{
if (!op_ret) {
/* A successful Put Bucket Policy should return a 204 on success */
op_ret = STATUS_NO_CONTENT;
}
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
int RGWPutBucketPolicy::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketPolicy)) {
return -EACCES;
}
return 0;
}
int RGWPutBucketPolicy::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
// At some point when I have more time I want to make a version of
// rgw_rest_read_all_input that doesn't use malloc.
std::tie(op_ret, data) = read_all_input(s, max_size, false);
// And throws exceptions.
return op_ret;
}
void RGWPutBucketPolicy::execute(optional_yield y)
{
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
try {
const Policy p(
s->cct, s->bucket_tenant, data,
s->cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
rgw::sal::Attrs attrs(s->bucket_attrs);
if (s->bucket_access_conf &&
s->bucket_access_conf->block_public_policy() &&
rgw::IAM::is_public(p)) {
op_ret = -EACCES;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [&p, this, &attrs] {
attrs[RGW_ATTR_IAM_POLICY].clear();
attrs[RGW_ATTR_IAM_POLICY].append(p.text);
op_ret = s->bucket->merge_and_store_attrs(this, attrs, s->yield);
return op_ret;
}, y);
} catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 5) << "failed to parse policy: " << e.what() << dendl;
op_ret = -EINVAL;
s->err.message = e.what();
}
}
void RGWGetBucketPolicy::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/json");
dump_body(s, policy);
}
int RGWGetBucketPolicy::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetBucketPolicy)) {
return -EACCES;
}
return 0;
}
void RGWGetBucketPolicy::execute(optional_yield y)
{
rgw::sal::Attrs attrs(s->bucket_attrs);
auto aiter = attrs.find(RGW_ATTR_IAM_POLICY);
if (aiter == attrs.end()) {
ldpp_dout(this, 0) << "can't find bucket IAM POLICY attr bucket_name = "
<< s->bucket_name << dendl;
op_ret = -ERR_NO_SUCH_BUCKET_POLICY;
s->err.message = "The bucket policy does not exist";
return;
} else {
policy = attrs[RGW_ATTR_IAM_POLICY];
if (policy.length() == 0) {
ldpp_dout(this, 10) << "The bucket policy does not exist, bucket: "
<< s->bucket_name << dendl;
op_ret = -ERR_NO_SUCH_BUCKET_POLICY;
s->err.message = "The bucket policy does not exist";
return;
}
}
}
void RGWDeleteBucketPolicy::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
int RGWDeleteBucketPolicy::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3DeleteBucketPolicy)) {
return -EACCES;
}
return 0;
}
void RGWDeleteBucketPolicy::execute(optional_yield y)
{
bufferlist data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this] {
rgw::sal::Attrs attrs(s->bucket_attrs);
attrs.erase(RGW_ATTR_IAM_POLICY);
op_ret = s->bucket->merge_and_store_attrs(this, attrs, s->yield);
return op_ret;
}, y);
}
void RGWPutBucketObjectLock::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
int RGWPutBucketObjectLock::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3PutBucketObjectLockConfiguration);
}
void RGWPutBucketObjectLock::execute(optional_yield y)
{
if (!s->bucket->get_info().obj_lock_enabled()) {
s->err.message = "object lock configuration can't be set if bucket object lock not enabled";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_BUCKET_STATE;
return;
}
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
op_ret = -EINVAL;
return;
}
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
if (!parser.parse(data.c_str(), data.length(), 1)) {
op_ret = -ERR_MALFORMED_XML;
return;
}
try {
RGWXMLDecoder::decode_xml("ObjectLockConfiguration", obj_lock, &parser, true);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "unexpected xml:" << err << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
if (obj_lock.has_rule() && !obj_lock.retention_period_valid()) {
s->err.message = "retention period must be a positive integer value";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_RETENTION_PERIOD;
return;
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << __func__ << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
s->bucket->get_info().obj_lock = obj_lock;
op_ret = s->bucket->put_info(this, false, real_time(), y);
return op_ret;
}, y);
return;
}
void RGWGetBucketObjectLock::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
int RGWGetBucketObjectLock::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
return verify_bucket_owner_or_policy(s, rgw::IAM::s3GetBucketObjectLockConfiguration);
}
void RGWGetBucketObjectLock::execute(optional_yield y)
{
if (!s->bucket->get_info().obj_lock_enabled()) {
op_ret = -ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION;
return;
}
}
int RGWPutObjRetention::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s, rgw::IAM::s3PutObjectRetention)) {
return -EACCES;
}
op_ret = get_params(y);
if (op_ret) {
return op_ret;
}
if (bypass_governance_mode) {
bypass_perm = verify_object_permission(this, s, rgw::IAM::s3BypassGovernanceRetention);
}
return 0;
}
void RGWPutObjRetention::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPutObjRetention::execute(optional_yield y)
{
if (!s->bucket->get_info().obj_lock_enabled()) {
s->err.message = "object retention can't be set if bucket object lock not configured";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_REQUEST;
return;
}
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
op_ret = -EINVAL;
return;
}
if (!parser.parse(data.c_str(), data.length(), 1)) {
op_ret = -ERR_MALFORMED_XML;
return;
}
try {
RGWXMLDecoder::decode_xml("Retention", obj_retention, &parser, true);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "unexpected xml:" << err << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
if (ceph::real_clock::to_time_t(obj_retention.get_retain_until_date()) < ceph_clock_now()) {
s->err.message = "the retain-until date must be in the future";
ldpp_dout(this, 0) << "ERROR: " << s->err.message << dendl;
op_ret = -EINVAL;
return;
}
bufferlist bl;
obj_retention.encode(bl);
//check old retention
op_ret = s->object->get_obj_attrs(s->yield, this);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: get obj attr error"<< dendl;
return;
}
rgw::sal::Attrs attrs = s->object->get_attrs();
auto aiter = attrs.find(RGW_ATTR_OBJECT_RETENTION);
if (aiter != attrs.end()) {
RGWObjectRetention old_obj_retention;
try {
decode(old_obj_retention, aiter->second);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl;
op_ret = -EIO;
return;
}
if (ceph::real_clock::to_time_t(obj_retention.get_retain_until_date()) < ceph::real_clock::to_time_t(old_obj_retention.get_retain_until_date())) {
if (old_obj_retention.get_mode().compare("GOVERNANCE") != 0 || !bypass_perm || !bypass_governance_mode) {
s->err.message = "proposed retain-until date shortens an existing retention period and governance bypass check failed";
op_ret = -EACCES;
return;
}
} else if (old_obj_retention.get_mode() == obj_retention.get_mode()) {
// ok if retention mode doesn't change
} else if (obj_retention.get_mode() == "GOVERNANCE") {
s->err.message = "can't change retention mode from COMPLIANCE to GOVERNANCE";
op_ret = -EACCES;
return;
} else if (!bypass_perm || !bypass_governance_mode) {
s->err.message = "can't change retention mode from GOVERNANCE without governance bypass";
op_ret = -EACCES;
return;
}
}
op_ret = s->object->modify_obj_attrs(RGW_ATTR_OBJECT_RETENTION, bl, s->yield, this);
return;
}
int RGWGetObjRetention::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s, rgw::IAM::s3GetObjectRetention)) {
return -EACCES;
}
return 0;
}
void RGWGetObjRetention::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetObjRetention::execute(optional_yield y)
{
if (!s->bucket->get_info().obj_lock_enabled()) {
s->err.message = "bucket object lock not configured";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_REQUEST;
return;
}
op_ret = s->object->get_obj_attrs(s->yield, this);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get obj attrs, obj=" << s->object
<< " ret=" << op_ret << dendl;
return;
}
rgw::sal::Attrs attrs = s->object->get_attrs();
auto aiter = attrs.find(RGW_ATTR_OBJECT_RETENTION);
if (aiter == attrs.end()) {
op_ret = -ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION;
return;
}
bufferlist::const_iterator iter{&aiter->second};
try {
obj_retention.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(this, 0) << __func__ << "decode object retention config failed" << dendl;
op_ret = -EIO;
return;
}
return;
}
int RGWPutObjLegalHold::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s, rgw::IAM::s3PutObjectLegalHold)) {
return -EACCES;
}
return 0;
}
void RGWPutObjLegalHold::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWPutObjLegalHold::execute(optional_yield y) {
if (!s->bucket->get_info().obj_lock_enabled()) {
s->err.message = "object legal hold can't be set if bucket object lock not enabled";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_REQUEST;
return;
}
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
op_ret = -EINVAL;
return;
}
op_ret = get_params(y);
if (op_ret < 0)
return;
if (!parser.parse(data.c_str(), data.length(), 1)) {
op_ret = -ERR_MALFORMED_XML;
return;
}
try {
RGWXMLDecoder::decode_xml("LegalHold", obj_legal_hold, &parser, true);
} catch (RGWXMLDecoder::err &err) {
ldpp_dout(this, 5) << "unexpected xml:" << err << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
bufferlist bl;
obj_legal_hold.encode(bl);
//if instance is empty, we should modify the latest object
op_ret = s->object->modify_obj_attrs(RGW_ATTR_OBJECT_LEGAL_HOLD, bl, s->yield, this);
return;
}
int RGWGetObjLegalHold::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s);
if (has_s3_existing_tag || has_s3_resource_tag)
rgw_iam_add_objtags(this, s, has_s3_existing_tag, has_s3_resource_tag);
if (!verify_object_permission(this, s, rgw::IAM::s3GetObjectLegalHold)) {
return -EACCES;
}
return 0;
}
void RGWGetObjLegalHold::pre_exec()
{
rgw_bucket_object_pre_exec(s);
}
void RGWGetObjLegalHold::execute(optional_yield y)
{
if (!s->bucket->get_info().obj_lock_enabled()) {
s->err.message = "bucket object lock not configured";
ldpp_dout(this, 4) << "ERROR: " << s->err.message << dendl;
op_ret = -ERR_INVALID_REQUEST;
return;
}
map<string, bufferlist> attrs;
op_ret = s->object->get_obj_attrs(s->yield, this);
if (op_ret < 0) {
ldpp_dout(this, 0) << "ERROR: failed to get obj attrs, obj=" << s->object
<< " ret=" << op_ret << dendl;
return;
}
auto aiter = s->object->get_attrs().find(RGW_ATTR_OBJECT_LEGAL_HOLD);
if (aiter == s->object->get_attrs().end()) {
op_ret = -ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION;
return;
}
bufferlist::const_iterator iter{&aiter->second};
try {
obj_legal_hold.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(this, 0) << __func__ << "decode object legal hold config failed" << dendl;
op_ret = -EIO;
return;
}
return;
}
void RGWGetClusterStat::execute(optional_yield y)
{
op_ret = driver->cluster_stat(stats_op);
}
int RGWGetBucketPolicyStatus::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetBucketPolicyStatus)) {
return -EACCES;
}
return 0;
}
void RGWGetBucketPolicyStatus::execute(optional_yield y)
{
isPublic = (s->iam_policy && rgw::IAM::is_public(*s->iam_policy)) || s->bucket_acl->is_public(this);
}
int RGWPutBucketPublicAccessBlock::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketPublicAccessBlock)) {
return -EACCES;
}
return 0;
}
int RGWPutBucketPublicAccessBlock::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
return op_ret;
}
void RGWPutBucketPublicAccessBlock::execute(optional_yield y)
{
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
op_ret = -EINVAL;
return;
}
op_ret = get_params(y);
if (op_ret < 0)
return;
if (!parser.parse(data.c_str(), data.length(), 1)) {
ldpp_dout(this, 0) << "ERROR: malformed XML" << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
try {
RGWXMLDecoder::decode_xml("PublicAccessBlockConfiguration", access_conf, &parser, true);
} catch (RGWXMLDecoder::err &err) {
ldpp_dout(this, 5) << "unexpected xml:" << err << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
bufferlist bl;
access_conf.encode(bl);
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, &bl] {
rgw::sal::Attrs attrs(s->bucket_attrs);
attrs[RGW_ATTR_PUBLIC_ACCESS] = bl;
return s->bucket->merge_and_store_attrs(this, attrs, s->yield);
}, y);
}
int RGWGetBucketPublicAccessBlock::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetBucketPolicy)) {
return -EACCES;
}
return 0;
}
void RGWGetBucketPublicAccessBlock::execute(optional_yield y)
{
auto attrs = s->bucket_attrs;
if (auto aiter = attrs.find(RGW_ATTR_PUBLIC_ACCESS);
aiter == attrs.end()) {
ldpp_dout(this, 0) << "can't find bucket IAM POLICY attr bucket_name = "
<< s->bucket_name << dendl;
// return the default;
return;
} else {
bufferlist::const_iterator iter{&aiter->second};
try {
access_conf.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(this, 0) << __func__ << "decode access_conf failed" << dendl;
op_ret = -EIO;
return;
}
}
}
void RGWDeleteBucketPublicAccessBlock::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
int RGWDeleteBucketPublicAccessBlock::verify_permission(optional_yield y)
{
auto [has_s3_existing_tag, has_s3_resource_tag] = rgw_check_policy_condition(this, s, false);
if (has_s3_resource_tag)
rgw_iam_add_buckettags(this, s);
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketPublicAccessBlock)) {
return -EACCES;
}
return 0;
}
void RGWDeleteBucketPublicAccessBlock::execute(optional_yield y)
{
bufferlist data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this] {
rgw::sal::Attrs attrs(s->bucket_attrs);
attrs.erase(RGW_ATTR_PUBLIC_ACCESS);
op_ret = s->bucket->merge_and_store_attrs(this, attrs, s->yield);
return op_ret;
}, y);
}
int RGWPutBucketEncryption::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
return op_ret;
}
int RGWPutBucketEncryption::verify_permission(optional_yield y)
{
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketEncryption)) {
return -EACCES;
}
return 0;
}
void RGWPutBucketEncryption::execute(optional_yield y)
{
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
op_ret = -EINVAL;
return;
}
op_ret = get_params(y);
if (op_ret < 0) {
return;
}
if (!parser.parse(data.c_str(), data.length(), 1)) {
ldpp_dout(this, 0) << "ERROR: malformed XML" << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
try {
RGWXMLDecoder::decode_xml("ServerSideEncryptionConfiguration", bucket_encryption_conf, &parser, true);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "unexpected xml:" << err << dendl;
op_ret = -ERR_MALFORMED_XML;
return;
}
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
bufferlist conf_bl;
bucket_encryption_conf.encode(conf_bl);
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y, &conf_bl] {
rgw::sal::Attrs attrs = s->bucket->get_attrs();
attrs[RGW_ATTR_BUCKET_ENCRYPTION_POLICY] = conf_bl;
return s->bucket->merge_and_store_attrs(this, attrs, y);
}, y);
}
int RGWGetBucketEncryption::verify_permission(optional_yield y)
{
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetBucketEncryption)) {
return -EACCES;
}
return 0;
}
void RGWGetBucketEncryption::execute(optional_yield y)
{
const auto& attrs = s->bucket_attrs;
if (auto aiter = attrs.find(RGW_ATTR_BUCKET_ENCRYPTION_POLICY);
aiter == attrs.end()) {
ldpp_dout(this, 0) << "can't find BUCKET ENCRYPTION attr for bucket_name = " << s->bucket_name << dendl;
op_ret = -ENOENT;
s->err.message = "The server side encryption configuration was not found";
return;
} else {
bufferlist::const_iterator iter{&aiter->second};
try {
bucket_encryption_conf.decode(iter);
} catch (const buffer::error& e) {
ldpp_dout(this, 0) << __func__ << "decode bucket_encryption_conf failed" << dendl;
op_ret = -EIO;
return;
}
}
}
int RGWDeleteBucketEncryption::verify_permission(optional_yield y)
{
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketEncryption)) {
return -EACCES;
}
return 0;
}
void RGWDeleteBucketEncryption::execute(optional_yield y)
{
bufferlist data;
op_ret = driver->forward_request_to_master(this, s->user.get(), nullptr, data, nullptr, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 0) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
op_ret = retry_raced_bucket_write(this, s->bucket.get(), [this, y] {
rgw::sal::Attrs attrs = s->bucket->get_attrs();
attrs.erase(RGW_ATTR_BUCKET_ENCRYPTION_POLICY);
attrs.erase(RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID);
op_ret = s->bucket->merge_and_store_attrs(this, attrs, y);
return op_ret;
}, y);
}
void rgw_slo_entry::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("path", path, obj);
JSONDecoder::decode_json("etag", etag, obj);
JSONDecoder::decode_json("size_bytes", size_bytes, obj);
};
| 282,319 | 30.445756 | 178 |
cc
|
null |
ceph-main/src/rgw/rgw_op.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/**
* All operations via the rados gateway are carried out by
* small classes known as RGWOps. This class contains a req_state
* and each possible command is a subclass of this with a defined
* execute() method that does whatever the subclass name implies.
* These subclasses must be further subclassed (by interface type)
* to provide additional virtual methods such as send_response or get_params.
*/
#pragma once
#include <limits.h>
#include <array>
#include <memory>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <boost/function.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/asio/deadline_timer.hpp>
#include "common/armor.h"
#include "common/mime.h"
#include "common/utf8.h"
#include "common/ceph_json.h"
#include "common/ceph_time.h"
#include "rgw_common.h"
#include "rgw_dmclock.h"
#include "rgw_sal.h"
#include "rgw_user.h"
#include "rgw_bucket.h"
#include "rgw_acl.h"
#include "rgw_cors.h"
#include "rgw_quota.h"
#include "rgw_putobj.h"
#include "rgw_sal.h"
#include "rgw_compression_types.h"
#include "rgw_log.h"
#include "rgw_lc.h"
#include "rgw_tag.h"
#include "rgw_object_lock.h"
#include "cls/rgw/cls_rgw_client.h"
#include "rgw_public_access.h"
#include "rgw_bucket_encryption.h"
#include "rgw_tracer.h"
#include "services/svc_sys_obj.h"
#include "services/svc_tier_rados.h"
#include "include/ceph_assert.h"
struct req_state;
class RGWOp;
class RGWRados;
class RGWMultiCompleteUpload;
class RGWPutObj_Torrent;
namespace rgw {
namespace auth {
namespace registry {
class StrategyRegistry;
}
}
}
int rgw_op_get_bucket_policy_from_attr(const DoutPrefixProvider *dpp,
CephContext *cct,
rgw::sal::Driver* driver,
RGWBucketInfo& bucket_info,
std::map<std::string, bufferlist>& bucket_attrs,
RGWAccessControlPolicy *policy,
optional_yield y);
class RGWHandler {
protected:
rgw::sal::Driver* driver{nullptr};
req_state *s{nullptr};
int do_init_permissions(const DoutPrefixProvider *dpp, optional_yield y);
int do_read_permissions(RGWOp* op, bool only_bucket, optional_yield y);
public:
RGWHandler() {}
virtual ~RGWHandler();
virtual int init(rgw::sal::Driver* driver,
req_state* _s,
rgw::io::BasicClient* cio);
virtual int init_permissions(RGWOp*, optional_yield y) {
return 0;
}
virtual int retarget(RGWOp* op, RGWOp** new_op, optional_yield) {
*new_op = op;
return 0;
}
virtual int read_permissions(RGWOp* op, optional_yield y) = 0;
virtual int authorize(const DoutPrefixProvider* dpp, optional_yield y) = 0;
virtual int postauth_init(optional_yield y) = 0;
virtual int error_handler(int err_no, std::string* error_content, optional_yield y);
virtual void dump(const std::string& code, const std::string& message) const {}
virtual bool supports_quota() {
return true;
}
};
void rgw_bucket_object_pre_exec(req_state *s);
namespace dmc = rgw::dmclock;
std::tuple<int, bufferlist > rgw_rest_read_all_input(req_state *s,
const uint64_t max_len,
const bool allow_chunked=true);
template <class T>
int rgw_rest_get_json_input(CephContext *cct, req_state *s, T& out,
uint64_t max_len, bool *empty)
{
if (empty)
*empty = false;
int rv = 0;
bufferlist data;
std::tie(rv, data) = rgw_rest_read_all_input(s, max_len);
if (rv < 0) {
return rv;
}
if (!data.length()) {
if (empty) {
*empty = true;
}
return -EINVAL;
}
JSONParser parser;
if (!parser.parse(data.c_str(), data.length())) {
return -EINVAL;
}
try {
decode_json_obj(out, &parser);
} catch (JSONDecoder::err& e) {
return -EINVAL;
}
return 0;
}
/**
* Provide the base class for all ops.
*/
class RGWOp : public DoutPrefixProvider {
protected:
req_state *s;
RGWHandler *dialect_handler;
rgw::sal::Driver* driver;
RGWCORSConfiguration bucket_cors;
bool cors_exist;
RGWQuota quota;
int op_ret;
int do_aws4_auth_completion();
bool init_called = false;
virtual int init_quota();
std::tuple<int, bufferlist> read_all_input(req_state *s,
const uint64_t max_len,
const bool allow_chunked=true) {
int rv = 0;
bufferlist data;
std::tie(rv, data) = rgw_rest_read_all_input(s, max_len);
if (rv >= 0) {
do_aws4_auth_completion();
}
return std::make_tuple(rv, std::move(data));
}
template <class T>
int get_json_input(CephContext *cct, req_state *s, T& out,
uint64_t max_len, bool *empty) {
int r = rgw_rest_get_json_input(cct, s, out, max_len, empty);
if (r >= 0) {
do_aws4_auth_completion();
}
return r;
}
public:
RGWOp()
: s(nullptr),
dialect_handler(nullptr),
driver(nullptr),
cors_exist(false),
op_ret(0) {
}
virtual ~RGWOp() override;
int get_ret() const { return op_ret; }
virtual int init_processing(optional_yield y) {
if (dialect_handler->supports_quota()) {
op_ret = init_quota();
if (op_ret < 0)
return op_ret;
}
return 0;
}
virtual void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *dialect_handler) {
if (init_called) return;
this->driver = driver;
init_called = true;
this->s = s;
this->dialect_handler = dialect_handler;
}
int read_bucket_cors();
bool generate_cors_headers(std::string& origin, std::string& method, std::string& headers, std::string& exp_headers, unsigned *max_age);
virtual int verify_params() { return 0; }
virtual bool prefetch_data() { return false; }
/* Authenticate requester -- verify its identity.
*
* NOTE: typically the procedure is common across all operations of the same
* dialect (S3, Swift API). However, there are significant exceptions in
* both APIs: browser uploads, /info and OPTIONS handlers. All of them use
* different, specific authentication schema driving the need for per-op
* authentication. The alternative is to duplicate parts of the method-
* dispatch logic in RGWHandler::authorize() and pollute it with a lot
* of special cases. */
virtual int verify_requester(const rgw::auth::StrategyRegistry& auth_registry, optional_yield y) {
/* TODO(rzarzynski): rename RGWHandler::authorize to generic_authenticate. */
return dialect_handler->authorize(this, y);
}
virtual int verify_permission(optional_yield y) = 0;
virtual int verify_op_mask();
virtual void pre_exec() {}
virtual void execute(optional_yield y) = 0;
virtual void send_response() {}
virtual void complete() {
send_response();
}
virtual const char* name() const = 0;
virtual RGWOpType get_type() { return RGW_OP_UNKNOWN; }
virtual uint32_t op_mask() { return 0; }
virtual int error_handler(int err_no, std::string *error_content, optional_yield y);
// implements DoutPrefixProvider
std::ostream& gen_prefix(std::ostream& out) const override;
CephContext* get_cct() const override { return s->cct; }
unsigned get_subsys() const override { return ceph_subsys_rgw; }
virtual dmc::client_id dmclock_client() { return dmc::client_id::metadata; }
virtual dmc::Cost dmclock_cost() { return 1; }
virtual void write_ops_log_entry(rgw_log_entry& entry) const {};
};
class RGWDefaultResponseOp : public RGWOp {
public:
void send_response() override;
};
class RGWGetObj_Filter : public RGWGetDataCB
{
protected:
RGWGetObj_Filter *next{nullptr};
public:
RGWGetObj_Filter() {}
explicit RGWGetObj_Filter(RGWGetObj_Filter *next): next(next) {}
~RGWGetObj_Filter() override {}
/**
* Passes data through filter.
* Filter can modify content of bl.
* When bl_len == 0 , it means 'flush
*/
int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override {
if (next) {
return next->handle_data(bl, bl_ofs, bl_len);
}
return 0;
}
/**
* Flushes any cached data. Used by RGWGetObjFilter.
* Return logic same as handle_data.
*/
virtual int flush() {
if (next) {
return next->flush();
}
return 0;
}
/**
* Allows filter to extend range required for successful filtering
*/
virtual int fixup_range(off_t& ofs, off_t& end) {
if (next) {
return next->fixup_range(ofs, end);
}
return 0;
}
};
class RGWGetObj : public RGWOp {
protected:
const char *range_str;
const char *if_mod;
const char *if_unmod;
const char *if_match;
const char *if_nomatch;
uint32_t mod_zone_id;
uint64_t mod_pg_ver;
off_t ofs;
uint64_t total_len;
off_t start;
off_t end;
ceph::real_time mod_time;
ceph::real_time lastmod;
ceph::real_time unmod_time;
ceph::real_time *mod_ptr;
ceph::real_time *unmod_ptr;
rgw::sal::Attrs attrs;
bool get_torrent = false;
bool get_data;
bool partial_content;
bool ignore_invalid_range;
bool range_parsed;
bool skip_manifest;
bool skip_decrypt{false};
bool sync_cloudtiered{false};
utime_t gc_invalidate_time;
bool is_slo;
std::string lo_etag;
bool rgwx_stat; /* extended rgw stat operation */
std::string version_id;
rgw_zone_set_entry dst_zone_trace;
// compression attrs
RGWCompressionInfo cs_info;
off_t first_block, last_block;
off_t q_ofs, q_len;
bool first_data;
uint64_t cur_ofs;
bufferlist waiting;
uint64_t action = 0;
bool get_retention;
bool get_legal_hold;
int init_common();
public:
RGWGetObj() {
range_str = NULL;
if_mod = NULL;
if_unmod = NULL;
if_match = NULL;
if_nomatch = NULL;
mod_zone_id = 0;
mod_pg_ver = 0;
start = 0;
ofs = 0;
total_len = 0;
end = -1;
mod_ptr = NULL;
unmod_ptr = NULL;
get_data = false;
partial_content = false;
range_parsed = false;
skip_manifest = false;
is_slo = false;
first_block = 0;
last_block = 0;
q_ofs = 0;
q_len = 0;
first_data = true;
cur_ofs = 0;
get_retention = false;
get_legal_hold = false;
}
bool prefetch_data() override;
void set_get_data(bool get_data) {
this->get_data = get_data;
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
int parse_range();
int read_user_manifest_part(
rgw::sal::Bucket* bucket,
const rgw_bucket_dir_entry& ent,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<rgw::IAM::Policy>& bucket_policy,
const off_t start_ofs,
const off_t end_ofs,
bool swift_slo);
int handle_user_manifest(const char *prefix, optional_yield y);
int handle_slo_manifest(bufferlist& bl, optional_yield y);
int get_data_cb(bufferlist& bl, off_t ofs, off_t len);
virtual int get_params(optional_yield y) = 0;
virtual int send_response_data_error(optional_yield y) = 0;
virtual int send_response_data(bufferlist& bl, off_t ofs, off_t len) = 0;
const char* name() const override { return "get_obj"; }
RGWOpType get_type() override { return RGW_OP_GET_OBJ; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
virtual bool need_object_expiration() { return false; }
/**
* calculates filter used to decrypt RGW objects data
*/
virtual int get_decrypt_filter(std::unique_ptr<RGWGetObj_Filter>* filter, RGWGetObj_Filter* cb, bufferlist* manifest_bl) {
*filter = nullptr;
return 0;
}
// get lua script to run as a "get object" filter
int get_lua_filter(std::unique_ptr<RGWGetObj_Filter>* filter,
RGWGetObj_Filter* cb);
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
};
class RGWGetObj_CB : public RGWGetObj_Filter
{
RGWGetObj *op;
public:
explicit RGWGetObj_CB(RGWGetObj *_op) : op(_op) {}
~RGWGetObj_CB() override {}
int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override {
return op->get_data_cb(bl, bl_ofs, bl_len);
}
};
class RGWGetObjTags : public RGWOp {
protected:
bufferlist tags_bl;
bool has_tags{false};
public:
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
void pre_exec() override;
virtual void send_response_data(bufferlist& bl) = 0;
const char* name() const override { return "get_obj_tags"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
RGWOpType get_type() override { return RGW_OP_GET_OBJ_TAGGING; }
};
class RGWPutObjTags : public RGWOp {
protected:
bufferlist tags_bl;
public:
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
virtual int get_params(optional_yield y) = 0;
const char* name() const override { return "put_obj_tags"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
RGWOpType get_type() override { return RGW_OP_PUT_OBJ_TAGGING; }
};
class RGWDeleteObjTags: public RGWOp {
public:
void pre_exec() override;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
const char* name() const override { return "delete_obj_tags"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
RGWOpType get_type() override { return RGW_OP_DELETE_OBJ_TAGGING;}
};
class RGWGetBucketTags : public RGWOp {
protected:
bufferlist tags_bl;
bool has_tags{false};
public:
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
void pre_exec() override;
virtual void send_response_data(bufferlist& bl) = 0;
const char* name() const override { return "get_bucket_tags"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_TAGGING; }
};
class RGWPutBucketTags : public RGWOp {
protected:
bufferlist tags_bl;
bufferlist in_data;
public:
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
virtual int get_params(const DoutPrefixProvider *dpp, optional_yield y) = 0;
const char* name() const override { return "put_bucket_tags"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
RGWOpType get_type() override { return RGW_OP_PUT_BUCKET_TAGGING; }
};
class RGWDeleteBucketTags : public RGWOp {
public:
void pre_exec() override;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
const char* name() const override { return "delete_bucket_tags"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
RGWOpType get_type() override { return RGW_OP_DELETE_BUCKET_TAGGING;}
};
struct rgw_sync_policy_group;
class RGWGetBucketReplication : public RGWOp {
public:
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
void pre_exec() override;
virtual void send_response_data() = 0;
const char* name() const override { return "get_bucket_replication"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_REPLICATION; }
};
class RGWPutBucketReplication : public RGWOp {
protected:
bufferlist in_data;
std::vector<rgw_sync_policy_group> sync_policy_groups;
public:
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
virtual int get_params(optional_yield y) = 0;
const char* name() const override { return "put_bucket_replication"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
RGWOpType get_type() override { return RGW_OP_PUT_BUCKET_REPLICATION; }
};
class RGWDeleteBucketReplication : public RGWOp {
protected:
virtual void update_sync_policy(rgw_sync_policy_info *policy) = 0;
public:
void pre_exec() override;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
const char* name() const override { return "delete_bucket_replication"; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
RGWOpType get_type() override { return RGW_OP_DELETE_BUCKET_REPLICATION;}
};
class RGWBulkDelete : public RGWOp {
public:
struct acct_path_t {
std::string bucket_name;
rgw_obj_key obj_key;
};
struct fail_desc_t {
int err;
acct_path_t path;
};
class Deleter {
protected:
const DoutPrefixProvider * dpp;
unsigned int num_deleted;
unsigned int num_unfound;
std::list<fail_desc_t> failures;
rgw::sal::Driver* const driver;
req_state * const s;
public:
Deleter(const DoutPrefixProvider* dpp, rgw::sal::Driver* const str, req_state * const s)
: dpp(dpp),
num_deleted(0),
num_unfound(0),
driver(str),
s(s) {
}
unsigned int get_num_deleted() const {
return num_deleted;
}
unsigned int get_num_unfound() const {
return num_unfound;
}
const std::list<fail_desc_t> get_failures() const {
return failures;
}
bool verify_permission(RGWBucketInfo& binfo,
std::map<std::string, bufferlist>& battrs,
ACLOwner& bucket_owner /* out */,
optional_yield y);
bool delete_single(const acct_path_t& path, optional_yield y);
bool delete_chunk(const std::list<acct_path_t>& paths, optional_yield y);
};
/* End of Deleter subclass */
static const size_t MAX_CHUNK_ENTRIES = 1024;
protected:
std::unique_ptr<Deleter> deleter;
public:
RGWBulkDelete()
: deleter(nullptr) {
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_data(std::list<acct_path_t>& items,
bool * is_truncated) = 0;
void send_response() override = 0;
const char* name() const override { return "bulk_delete"; }
RGWOpType get_type() override { return RGW_OP_BULK_DELETE; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
};
inline std::ostream& operator<<(std::ostream& out, const RGWBulkDelete::acct_path_t &o) {
return out << o.bucket_name << "/" << o.obj_key;
}
class RGWBulkUploadOp : public RGWOp {
protected:
class fail_desc_t {
public:
fail_desc_t(const int err, std::string path)
: err(err),
path(std::move(path)) {
}
const int err;
const std::string path;
};
static constexpr std::array<int, 2> terminal_errors = {
{ -EACCES, -EPERM }
};
/* FIXME: boost::container::small_vector<fail_desc_t, 4> failures; */
std::vector<fail_desc_t> failures;
size_t num_created;
class StreamGetter;
class DecoratedStreamGetter;
class AlignedStreamGetter;
virtual std::unique_ptr<StreamGetter> create_stream() = 0;
virtual void send_response() override = 0;
boost::optional<std::pair<std::string, rgw_obj_key>>
parse_path(const std::string_view& path);
std::pair<std::string, std::string>
handle_upload_path(req_state *s);
bool handle_file_verify_permission(RGWBucketInfo& binfo,
const rgw_obj& obj,
std::map<std::string, ceph::bufferlist>& battrs,
ACLOwner& bucket_owner /* out */,
optional_yield y);
int handle_file(std::string_view path,
size_t size,
AlignedStreamGetter& body,
optional_yield y);
int handle_dir_verify_permission(optional_yield y);
int handle_dir(std::string_view path, optional_yield y);
public:
RGWBulkUploadOp()
: num_created(0) {
}
void init(rgw::sal::Driver* const driver,
req_state* const s,
RGWHandler* const h) override;
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
const char* name() const override { return "bulk_upload"; }
RGWOpType get_type() override {
return RGW_OP_BULK_UPLOAD;
}
uint32_t op_mask() override {
return RGW_OP_TYPE_WRITE;
}
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
}; /* RGWBulkUploadOp */
class RGWBulkUploadOp::StreamGetter {
public:
StreamGetter() = default;
virtual ~StreamGetter() = default;
virtual ssize_t get_at_most(size_t want, ceph::bufferlist& dst) = 0;
virtual ssize_t get_exactly(size_t want, ceph::bufferlist& dst) = 0;
}; /* End of nested subclass StreamGetter */
class RGWBulkUploadOp::DecoratedStreamGetter : public StreamGetter {
StreamGetter& decoratee;
protected:
StreamGetter& get_decoratee() {
return decoratee;
}
public:
explicit DecoratedStreamGetter(StreamGetter& decoratee)
: decoratee(decoratee) {
}
virtual ~DecoratedStreamGetter() = default;
ssize_t get_at_most(const size_t want, ceph::bufferlist& dst) override {
return get_decoratee().get_at_most(want, dst);
}
ssize_t get_exactly(const size_t want, ceph::bufferlist& dst) override {
return get_decoratee().get_exactly(want, dst);
}
}; /* RGWBulkUploadOp::DecoratedStreamGetter */
class RGWBulkUploadOp::AlignedStreamGetter
: public RGWBulkUploadOp::DecoratedStreamGetter {
size_t position;
size_t length;
size_t alignment;
public:
template <typename U>
AlignedStreamGetter(const size_t position,
const size_t length,
const size_t alignment,
U&& decoratee)
: DecoratedStreamGetter(std::forward<U>(decoratee)),
position(position),
length(length),
alignment(alignment) {
}
virtual ~AlignedStreamGetter();
ssize_t get_at_most(size_t want, ceph::bufferlist& dst) override;
ssize_t get_exactly(size_t want, ceph::bufferlist& dst) override;
}; /* RGWBulkUploadOp::AlignedStreamGetter */
struct RGWUsageStats {
uint64_t bytes_used = 0;
uint64_t bytes_used_rounded = 0;
uint64_t buckets_count = 0;
uint64_t objects_count = 0;
};
#define RGW_LIST_BUCKETS_LIMIT_MAX 10000
class RGWListBuckets : public RGWOp {
protected:
bool sent_data;
std::string marker;
std::string end_marker;
int64_t limit;
uint64_t limit_max;
bool is_truncated;
RGWUsageStats global_stats;
std::map<std::string, RGWUsageStats> policies_stats;
virtual uint64_t get_default_max() const {
return 1000;
}
public:
RGWListBuckets()
: sent_data(false),
limit(RGW_LIST_BUCKETS_LIMIT_MAX),
limit_max(RGW_LIST_BUCKETS_LIMIT_MAX),
is_truncated(false) {
}
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
virtual void handle_listing_chunk(rgw::sal::BucketList&& buckets) {
/* The default implementation, used by e.g. S3, just generates a new
* part of listing and sends it client immediately. Swift can behave
* differently: when the reverse option is requested, all incoming
* instances of RGWBucketList are buffered and finally reversed. */
return send_response_data(buckets);
}
virtual void send_response_begin(bool has_buckets) = 0;
virtual void send_response_data(rgw::sal::BucketList& buckets) = 0;
virtual void send_response_end() = 0;
void send_response() override {}
virtual bool should_get_stats() { return false; }
virtual bool supports_account_metadata() { return false; }
const char* name() const override { return "list_buckets"; }
RGWOpType get_type() override { return RGW_OP_LIST_BUCKETS; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
}; // class RGWListBuckets
class RGWGetUsage : public RGWOp {
protected:
bool sent_data;
std::string start_date;
std::string end_date;
int show_log_entries;
int show_log_sum;
std::map<std::string, bool> categories;
std::map<rgw_user_bucket, rgw_usage_log_entry> usage;
std::map<std::string, rgw_usage_log_entry> summary_map;
std::map<std::string, bucket_meta_entry> buckets_usage;
cls_user_header header;
RGWStorageStats stats;
public:
RGWGetUsage() : sent_data(false), show_log_entries(true), show_log_sum(true){
}
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override {}
virtual bool should_get_stats() { return false; }
const char* name() const override { return "get_self_usage"; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWStatAccount : public RGWOp {
protected:
RGWUsageStats global_stats;
std::map<std::string, RGWUsageStats> policies_stats;
public:
RGWStatAccount() = default;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "stat_account"; }
RGWOpType get_type() override { return RGW_OP_STAT_ACCOUNT; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWListBucket : public RGWOp {
protected:
std::string prefix;
rgw_obj_key marker;
rgw_obj_key next_marker;
rgw_obj_key end_marker;
std::string max_keys;
std::string delimiter;
std::string encoding_type;
bool list_versions;
int max;
std::vector<rgw_bucket_dir_entry> objs;
std::map<std::string, bool> common_prefixes;
int default_max;
bool is_truncated;
bool allow_unordered;
int shard_id;
int parse_max_keys();
public:
RGWListBucket() : list_versions(false), max(0),
default_max(0), is_truncated(false),
allow_unordered(false), shard_id(-1) {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
}
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "list_bucket"; }
RGWOpType get_type() override { return RGW_OP_LIST_BUCKET; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
virtual bool need_container_stats() { return false; }
};
class RGWGetBucketLogging : public RGWOp {
public:
RGWGetBucketLogging() {}
int verify_permission(optional_yield y) override;
void execute(optional_yield) override { }
void send_response() override = 0;
const char* name() const override { return "get_bucket_logging"; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_LOGGING; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWGetBucketLocation : public RGWOp {
public:
RGWGetBucketLocation() {}
~RGWGetBucketLocation() override {}
int verify_permission(optional_yield y) override;
void execute(optional_yield) override { }
void send_response() override = 0;
const char* name() const override { return "get_bucket_location"; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_LOCATION; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWGetBucketVersioning : public RGWOp {
protected:
bool versioned{false};
bool versioning_enabled{false};
bool mfa_enabled{false};
public:
RGWGetBucketVersioning() = default;
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "get_bucket_versioning"; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_VERSIONING; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
enum BucketVersionStatus {
VersioningStatusInvalid = -1,
VersioningNotChanged = 0,
VersioningEnabled = 1,
VersioningSuspended =2,
};
class RGWSetBucketVersioning : public RGWOp {
protected:
int versioning_status;
bool mfa_set_status{false};
bool mfa_status{false};
bufferlist in_data;
public:
RGWSetBucketVersioning() : versioning_status(VersioningNotChanged) {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) { return 0; }
void send_response() override = 0;
const char* name() const override { return "set_bucket_versioning"; }
RGWOpType get_type() override { return RGW_OP_SET_BUCKET_VERSIONING; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetBucketWebsite : public RGWOp {
public:
RGWGetBucketWebsite() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "get_bucket_website"; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_WEBSITE; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWSetBucketWebsite : public RGWOp {
protected:
bufferlist in_data;
RGWBucketWebsiteConf website_conf;
public:
RGWSetBucketWebsite() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) { return 0; }
void send_response() override = 0;
const char* name() const override { return "set_bucket_website"; }
RGWOpType get_type() override { return RGW_OP_SET_BUCKET_WEBSITE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWDeleteBucketWebsite : public RGWOp {
public:
RGWDeleteBucketWebsite() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "delete_bucket_website"; }
RGWOpType get_type() override { return RGW_OP_SET_BUCKET_WEBSITE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWStatBucket : public RGWOp {
protected:
std::unique_ptr<rgw::sal::Bucket> bucket;
public:
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "stat_bucket"; }
RGWOpType get_type() override { return RGW_OP_STAT_BUCKET; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWCreateBucket : public RGWOp {
protected:
RGWAccessControlPolicy policy;
std::string location_constraint;
rgw_placement_rule placement_rule;
RGWBucketInfo info;
obj_version ep_objv;
bool has_cors;
bool relaxed_region_enforcement;
bool obj_lock_enabled;
RGWCORSConfiguration cors_config;
boost::optional<std::string> swift_ver_location;
std::map<std::string, buffer::list> attrs;
std::set<std::string> rmattr_names;
bufferlist in_data;
virtual bool need_metadata_upload() const { return false; }
public:
RGWCreateBucket() : has_cors(false), relaxed_region_enforcement(false), obj_lock_enabled(false) {}
void emplace_attr(std::string&& key, buffer::list&& bl) {
attrs.emplace(std::move(key), std::move(bl)); /* key and bl are r-value refs */
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
relaxed_region_enforcement =
s->cct->_conf.get_val<bool>("rgw_relaxed_region_enforcement");
}
virtual int get_params(optional_yield y) { return 0; }
void send_response() override = 0;
const char* name() const override { return "create_bucket"; }
RGWOpType get_type() override { return RGW_OP_CREATE_BUCKET; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWDeleteBucket : public RGWOp {
protected:
RGWObjVersionTracker objv_tracker;
public:
RGWDeleteBucket() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "delete_bucket"; }
RGWOpType get_type() override { return RGW_OP_DELETE_BUCKET; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
};
struct rgw_slo_entry {
std::string path;
std::string etag;
uint64_t size_bytes;
rgw_slo_entry() : size_bytes(0) {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(path, bl);
encode(etag, bl);
encode(size_bytes, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(path, bl);
decode(etag, bl);
decode(size_bytes, bl);
DECODE_FINISH(bl);
}
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(rgw_slo_entry)
struct RGWSLOInfo {
std::vector<rgw_slo_entry> entries;
uint64_t total_size;
/* in memory only */
bufferlist raw_data;
RGWSLOInfo() : total_size(0) {}
~RGWSLOInfo() {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(entries, bl);
encode(total_size, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(entries, bl);
decode(total_size, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(RGWSLOInfo)
class RGWPutObj : public RGWOp {
protected:
off_t ofs;
const char *supplied_md5_b64;
const char *supplied_etag;
const char *if_match;
const char *if_nomatch;
std::string copy_source;
const char *copy_source_range;
RGWBucketInfo copy_source_bucket_info;
std::string copy_source_tenant_name;
std::string copy_source_bucket_name;
std::string copy_source_object_name;
std::string copy_source_version_id;
off_t copy_source_range_fst;
off_t copy_source_range_lst;
std::string etag;
bool chunked_upload;
RGWAccessControlPolicy policy;
std::unique_ptr <RGWObjTags> obj_tags;
const char *dlo_manifest;
RGWSLOInfo *slo_info;
rgw::sal::Attrs attrs;
ceph::real_time mtime;
uint64_t olh_epoch;
std::string version_id;
bufferlist bl_aux;
std::map<std::string, std::string> crypt_http_responses;
std::string user_data;
std::string multipart_upload_id;
std::string multipart_part_str;
int multipart_part_num = 0;
jspan multipart_trace;
boost::optional<ceph::real_time> delete_at;
//append obj
bool append;
uint64_t position;
uint64_t cur_accounted_size;
//object lock
RGWObjectRetention *obj_retention;
RGWObjectLegalHold *obj_legal_hold;
public:
RGWPutObj() : ofs(0),
supplied_md5_b64(NULL),
supplied_etag(NULL),
if_match(NULL),
if_nomatch(NULL),
copy_source_range(NULL),
copy_source_range_fst(0),
copy_source_range_lst(0),
chunked_upload(0),
dlo_manifest(NULL),
slo_info(NULL),
olh_epoch(0),
append(false),
position(0),
cur_accounted_size(0),
obj_retention(nullptr),
obj_legal_hold(nullptr) {}
~RGWPutObj() override {
delete slo_info;
delete obj_retention;
delete obj_legal_hold;
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
}
virtual int init_processing(optional_yield y) override;
void emplace_attr(std::string&& key, buffer::list&& bl) {
attrs.emplace(std::move(key), std::move(bl)); /* key and bl are r-value refs */
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
/* this is for cases when copying data from other object */
virtual int get_decrypt_filter(std::unique_ptr<RGWGetObj_Filter>* filter,
RGWGetObj_Filter* cb,
std::map<std::string, bufferlist>& attrs,
bufferlist* manifest_bl) {
*filter = nullptr;
return 0;
}
virtual int get_encrypt_filter(std::unique_ptr<rgw::sal::DataProcessor> *filter,
rgw::sal::DataProcessor *cb) {
return 0;
}
// if configured, construct a filter to generate torrent metadata
auto get_torrent_filter(rgw::sal::DataProcessor *cb)
-> std::optional<RGWPutObj_Torrent>;
// get lua script to run as a "put object" filter
int get_lua_filter(std::unique_ptr<rgw::sal::DataProcessor>* filter,
rgw::sal::DataProcessor* cb);
int get_data_cb(bufferlist& bl, off_t bl_ofs, off_t bl_len);
int get_data(const off_t fst, const off_t lst, bufferlist& bl);
virtual int get_params(optional_yield y) = 0;
virtual int get_data(bufferlist& bl) = 0;
void send_response() override = 0;
const char* name() const override { return "put_obj"; }
RGWOpType get_type() override { return RGW_OP_PUT_OBJ; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
};
class RGWPostObj : public RGWOp {
protected:
off_t min_len;
off_t max_len;
int len;
off_t ofs;
const char *supplied_md5_b64;
const char *supplied_etag;
std::string etag;
RGWAccessControlPolicy policy;
std::map<std::string, bufferlist> attrs;
boost::optional<ceph::real_time> delete_at;
/* Must be called after get_data() or the result is undefined. */
virtual std::string get_current_filename() const = 0;
virtual std::string get_current_content_type() const = 0;
virtual bool is_next_file_to_upload() {
return false;
}
public:
RGWPostObj() : min_len(0),
max_len(LLONG_MAX),
len(0),
ofs(0),
supplied_md5_b64(nullptr),
supplied_etag(nullptr) {
}
void emplace_attr(std::string&& key, buffer::list&& bl) {
attrs.emplace(std::move(key), std::move(bl)); /* key and bl are r-value refs */
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_encrypt_filter(std::unique_ptr<rgw::sal::DataProcessor> *filter,
rgw::sal::DataProcessor *cb) {
return 0;
}
virtual int get_params(optional_yield y) = 0;
virtual int get_data(ceph::bufferlist& bl, bool& again) = 0;
void send_response() override = 0;
const char* name() const override { return "post_obj"; }
RGWOpType get_type() override { return RGW_OP_POST_OBJ; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
};
class RGWPutMetadataAccount : public RGWOp {
protected:
std::set<std::string> rmattr_names;
std::map<std::string, bufferlist> attrs, orig_attrs;
std::map<int, std::string> temp_url_keys;
RGWQuotaInfo new_quota;
bool new_quota_extracted;
RGWAccessControlPolicy policy;
bool has_policy;
public:
RGWPutMetadataAccount()
: new_quota_extracted(false),
has_policy(false) {
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
}
int init_processing(optional_yield y) override;
int verify_permission(optional_yield y) override;
void pre_exec() override { }
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
virtual void filter_out_temp_url(std::map<std::string, bufferlist>& add_attrs,
const std::set<std::string>& rmattr_names,
std::map<int, std::string>& temp_url_keys);
const char* name() const override { return "put_account_metadata"; }
RGWOpType get_type() override { return RGW_OP_PUT_METADATA_ACCOUNT; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWPutMetadataBucket : public RGWOp {
protected:
rgw::sal::Attrs attrs;
std::set<std::string> rmattr_names;
bool has_policy, has_cors;
uint32_t policy_rw_mask;
RGWAccessControlPolicy policy;
RGWCORSConfiguration cors_config;
rgw_placement_rule placement_rule;
boost::optional<std::string> swift_ver_location;
public:
RGWPutMetadataBucket()
: has_policy(false), has_cors(false), policy_rw_mask(0)
{}
void emplace_attr(std::string&& key, buffer::list&& bl) {
attrs.emplace(std::move(key), std::move(bl)); /* key and bl are r-value refs */
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "put_bucket_metadata"; }
RGWOpType get_type() override { return RGW_OP_PUT_METADATA_BUCKET; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWPutMetadataObject : public RGWOp {
protected:
RGWAccessControlPolicy policy;
boost::optional<ceph::real_time> delete_at;
const char *dlo_manifest;
public:
RGWPutMetadataObject()
: dlo_manifest(NULL)
{}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "put_obj_metadata"; }
RGWOpType get_type() override { return RGW_OP_PUT_METADATA_OBJECT; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
virtual bool need_object_expiration() { return false; }
};
class RGWDeleteObj : public RGWOp {
protected:
bool delete_marker;
bool multipart_delete;
std::string version_id;
ceph::real_time unmod_since; /* if unmodified since */
bool no_precondition_error;
std::unique_ptr<RGWBulkDelete::Deleter> deleter;
bool bypass_perm;
bool bypass_governance_mode;
public:
RGWDeleteObj()
: delete_marker(false),
multipart_delete(false),
no_precondition_error(false),
deleter(nullptr),
bypass_perm(true),
bypass_governance_mode(false) {
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
int handle_slo_manifest(bufferlist& bl, optional_yield y);
virtual int get_params(optional_yield y) { return 0; }
void send_response() override = 0;
const char* name() const override { return "delete_obj"; }
RGWOpType get_type() override { return RGW_OP_DELETE_OBJ; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
virtual bool need_object_expiration() { return false; }
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
};
class RGWCopyObj : public RGWOp {
protected:
RGWAccessControlPolicy dest_policy;
const char *if_mod;
const char *if_unmod;
const char *if_match;
const char *if_nomatch;
// Required or it is not a copy operation
std::string_view copy_source;
// Not actually required
std::optional<std::string_view> md_directive;
off_t ofs;
off_t len;
off_t end;
ceph::real_time mod_time;
ceph::real_time unmod_time;
ceph::real_time *mod_ptr;
ceph::real_time *unmod_ptr;
rgw::sal::Attrs attrs;
std::unique_ptr<rgw::sal::Bucket> src_bucket;
ceph::real_time src_mtime;
ceph::real_time mtime;
rgw::sal::AttrsMod attrs_mod;
std::string source_zone;
std::string etag;
off_t last_ofs;
std::string version_id;
uint64_t olh_epoch;
boost::optional<ceph::real_time> delete_at;
bool copy_if_newer;
bool need_to_check_storage_class = false;
//object lock
RGWObjectRetention *obj_retention;
RGWObjectLegalHold *obj_legal_hold;
int init_common();
public:
RGWCopyObj() {
if_mod = NULL;
if_unmod = NULL;
if_match = NULL;
if_nomatch = NULL;
ofs = 0;
len = 0;
end = -1;
mod_ptr = NULL;
unmod_ptr = NULL;
attrs_mod = rgw::sal::ATTRSMOD_NONE;
last_ofs = 0;
olh_epoch = 0;
copy_if_newer = false;
obj_retention = nullptr;
obj_legal_hold = nullptr;
}
~RGWCopyObj() override {
delete obj_retention;
delete obj_legal_hold;
}
static bool parse_copy_location(const std::string_view& src,
std::string& bucket_name,
rgw_obj_key& object,
req_state *s);
void emplace_attr(std::string&& key, buffer::list&& bl) {
attrs.emplace(std::move(key), std::move(bl));
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
dest_policy.set_ctx(s->cct);
}
int init_processing(optional_yield y) override;
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void progress_cb(off_t ofs);
virtual int check_storage_class(const rgw_placement_rule& src_placement) {
return 0;
}
virtual int init_dest_policy() { return 0; }
virtual int get_params(optional_yield y) = 0;
virtual void send_partial_response(off_t ofs) {}
void send_response() override = 0;
const char* name() const override { return "copy_obj"; }
RGWOpType get_type() override { return RGW_OP_COPY_OBJ; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
dmc::client_id dmclock_client() override { return dmc::client_id::data; }
};
class RGWGetACLs : public RGWOp {
protected:
std::string acls;
public:
RGWGetACLs() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "get_acls"; }
RGWOpType get_type() override { return RGW_OP_GET_ACLS; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutACLs : public RGWOp {
protected:
bufferlist data;
ACLOwner owner;
public:
RGWPutACLs() {}
~RGWPutACLs() override {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_policy_from_state(rgw::sal::Driver* driver, req_state *s, std::stringstream& ss) { return 0; }
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "put_acls"; }
RGWOpType get_type() override { return RGW_OP_PUT_ACLS; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetLC : public RGWOp {
protected:
public:
RGWGetLC() { }
~RGWGetLC() override { }
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield) override = 0;
void send_response() override = 0;
const char* name() const override { return "get_lifecycle"; }
RGWOpType get_type() override { return RGW_OP_GET_LC; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutLC : public RGWOp {
protected:
bufferlist data;
const char *content_md5;
std::string cookie;
public:
RGWPutLC() {
content_md5 = nullptr;
}
~RGWPutLC() override {}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *dialect_handler) override {
static constexpr std::size_t COOKIE_LEN = 16;
char buf[COOKIE_LEN + 1];
RGWOp::init(driver, s, dialect_handler);
gen_rand_alphanumeric(s->cct, buf, sizeof(buf) - 1);
cookie = buf;
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
// virtual int get_policy_from_state(RGWRados* driver, req_state *s, std::stringstream& ss) { return 0; }
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "put_lifecycle"; }
RGWOpType get_type() override { return RGW_OP_PUT_LC; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWDeleteLC : public RGWOp {
public:
RGWDeleteLC() = default;
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "delete_lifecycle"; }
RGWOpType get_type() override { return RGW_OP_DELETE_LC; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetCORS : public RGWOp {
protected:
public:
RGWGetCORS() {}
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "get_cors"; }
RGWOpType get_type() override { return RGW_OP_GET_CORS; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutCORS : public RGWOp {
protected:
bufferlist cors_bl;
bufferlist in_data;
public:
RGWPutCORS() {}
~RGWPutCORS() override {}
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "put_cors"; }
RGWOpType get_type() override { return RGW_OP_PUT_CORS; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWDeleteCORS : public RGWOp {
protected:
public:
RGWDeleteCORS() {}
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "delete_cors"; }
RGWOpType get_type() override { return RGW_OP_DELETE_CORS; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWOptionsCORS : public RGWOp {
protected:
RGWCORSRule *rule;
const char *origin, *req_hdrs, *req_meth;
public:
RGWOptionsCORS() : rule(NULL), origin(NULL),
req_hdrs(NULL), req_meth(NULL) {
}
int verify_permission(optional_yield y) override {return 0;}
int validate_cors_request(RGWCORSConfiguration *cc);
void execute(optional_yield y) override;
void get_response_params(std::string& allowed_hdrs, std::string& exp_hdrs, unsigned *max_age);
void send_response() override = 0;
const char* name() const override { return "options_cors"; }
RGWOpType get_type() override { return RGW_OP_OPTIONS_CORS; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutBucketEncryption : public RGWOp {
protected:
RGWBucketEncryptionConfig bucket_encryption_conf;
bufferlist data;
public:
RGWPutBucketEncryption() = default;
~RGWPutBucketEncryption() {}
int get_params(optional_yield y);
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
const char* name() const override { return "put_bucket_encryption"; }
RGWOpType get_type() override { return RGW_OP_PUT_BUCKET_ENCRYPTION; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetBucketEncryption : public RGWOp {
protected:
RGWBucketEncryptionConfig bucket_encryption_conf;
public:
RGWGetBucketEncryption() {}
int get_params(optional_yield y);
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
const char* name() const override { return "get_bucket_encryption"; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_ENCRYPTION; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWDeleteBucketEncryption : public RGWOp {
protected:
RGWBucketEncryptionConfig bucket_encryption_conf;
public:
RGWDeleteBucketEncryption() {}
int get_params(optional_yield y);
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
const char* name() const override { return "delete_bucket_encryption"; }
RGWOpType get_type() override { return RGW_OP_DELETE_BUCKET_ENCRYPTION; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetRequestPayment : public RGWOp {
protected:
bool requester_pays;
public:
RGWGetRequestPayment() : requester_pays(0) {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "get_request_payment"; }
RGWOpType get_type() override { return RGW_OP_GET_REQUEST_PAYMENT; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWSetRequestPayment : public RGWOp {
protected:
bool requester_pays;
bufferlist in_data;
public:
RGWSetRequestPayment() : requester_pays(false) {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) { return 0; }
void send_response() override = 0;
const char* name() const override { return "set_request_payment"; }
RGWOpType get_type() override { return RGW_OP_SET_REQUEST_PAYMENT; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWInitMultipart : public RGWOp {
protected:
std::string upload_id;
RGWAccessControlPolicy policy;
ceph::real_time mtime;
jspan multipart_trace;
public:
RGWInitMultipart() {}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy.set_ctx(s->cct);
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "init_multipart"; }
RGWOpType get_type() override { return RGW_OP_INIT_MULTIPART; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
virtual int prepare_encryption(std::map<std::string, bufferlist>& attrs) { return 0; }
};
class RGWCompleteMultipart : public RGWOp {
protected:
std::string upload_id;
std::string etag;
std::string version_id;
bufferlist data;
std::unique_ptr<rgw::sal::MPSerializer> serializer;
jspan multipart_trace;
public:
RGWCompleteMultipart() {}
~RGWCompleteMultipart() = default;
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
bool check_previously_completed(const RGWMultiCompleteUpload* parts);
void complete() override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "complete_multipart"; }
RGWOpType get_type() override { return RGW_OP_COMPLETE_MULTIPART; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWAbortMultipart : public RGWOp {
protected:
jspan multipart_trace;
public:
RGWAbortMultipart() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
void send_response() override = 0;
const char* name() const override { return "abort_multipart"; }
RGWOpType get_type() override { return RGW_OP_ABORT_MULTIPART; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
};
class RGWListMultipart : public RGWOp {
protected:
std::string upload_id;
std::unique_ptr<rgw::sal::MultipartUpload> upload;
int max_parts;
int marker;
RGWAccessControlPolicy policy;
bool truncated;
rgw_placement_rule* placement;
public:
RGWListMultipart() {
max_parts = 1000;
marker = 0;
truncated = false;
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
policy = RGWAccessControlPolicy(s->cct);
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "list_multipart"; }
RGWOpType get_type() override { return RGW_OP_LIST_MULTIPART; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWListBucketMultiparts : public RGWOp {
protected:
std::string prefix;
std::string marker_meta;
std::string marker_key;
std::string marker_upload_id;
std::string next_marker_key;
std::string next_marker_upload_id;
int max_uploads;
std::string delimiter;
std::vector<std::unique_ptr<rgw::sal::MultipartUpload>> uploads;
std::map<std::string, bool> common_prefixes;
bool is_truncated;
int default_max;
bool encode_url {false};
public:
RGWListBucketMultiparts() {
max_uploads = 0;
is_truncated = false;
default_max = 0;
}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
max_uploads = default_max;
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "list_bucket_multiparts"; }
RGWOpType get_type() override { return RGW_OP_LIST_BUCKET_MULTIPARTS; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWGetCrossDomainPolicy : public RGWOp {
public:
RGWGetCrossDomainPolicy() = default;
~RGWGetCrossDomainPolicy() override = default;
int verify_permission(optional_yield) override {
return 0;
}
void execute(optional_yield) override {
op_ret = 0;
}
const char* name() const override { return "get_crossdomain_policy"; }
RGWOpType get_type() override {
return RGW_OP_GET_CROSS_DOMAIN_POLICY;
}
uint32_t op_mask() override {
return RGW_OP_TYPE_READ;
}
};
class RGWGetHealthCheck : public RGWOp {
public:
RGWGetHealthCheck() = default;
~RGWGetHealthCheck() override = default;
int verify_permission(optional_yield) override {
return 0;
}
void execute(optional_yield y) override;
const char* name() const override { return "get_health_check"; }
RGWOpType get_type() override {
return RGW_OP_GET_HEALTH_CHECK;
}
uint32_t op_mask() override {
return RGW_OP_TYPE_READ;
}
};
class RGWDeleteMultiObj : public RGWOp {
/**
* Handles the deletion of an individual object and uses
* set_partial_response to record the outcome.
*/
void handle_individual_object(const rgw_obj_key& o,
optional_yield y,
boost::asio::deadline_timer *formatter_flush_cond);
/**
* When the request is being executed in a coroutine, performs
* the actual formatter flushing and is responsible for the
* termination condition (when when all partial object responses
* have been sent). Note that the formatter flushing must be handled
* on the coroutine that invokes the execute method vs. the
* coroutines that are spawned to handle individual objects because
* the flush logic uses a yield context that was captured
* and saved on the req_state vs. one that is passed on the stack.
* This is a no-op in the case where we're not executing as a coroutine.
*/
void wait_flush(optional_yield y,
boost::asio::deadline_timer *formatter_flush_cond,
std::function<bool()> predicate);
protected:
std::vector<delete_multi_obj_entry> ops_log_entries;
bufferlist data;
rgw::sal::Bucket* bucket;
bool quiet;
bool status_dumped;
bool acl_allowed = false;
bool bypass_perm;
bool bypass_governance_mode;
public:
RGWDeleteMultiObj() {
quiet = false;
status_dumped = false;
bypass_perm = true;
bypass_governance_mode = false;
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
virtual void send_status() = 0;
virtual void begin_response() = 0;
virtual void send_partial_response(const rgw_obj_key& key, bool delete_marker,
const std::string& marker_version_id, int ret,
boost::asio::deadline_timer *formatter_flush_cond) = 0;
virtual void end_response() = 0;
const char* name() const override { return "multi_object_delete"; }
RGWOpType get_type() override { return RGW_OP_DELETE_MULTI_OBJ; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
void write_ops_log_entry(rgw_log_entry& entry) const override;
};
class RGWInfo: public RGWOp {
public:
RGWInfo() = default;
~RGWInfo() override = default;
int verify_permission(optional_yield) override { return 0; }
const char* name() const override { return "get info"; }
RGWOpType get_type() override { return RGW_OP_GET_INFO; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
extern int rgw_build_bucket_policies(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
req_state* s, optional_yield y);
extern int rgw_build_object_policies(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
req_state *s, bool prefetch_data, optional_yield y);
extern void rgw_build_iam_environment(rgw::sal::Driver* driver,
req_state* s);
extern std::vector<rgw::IAM::Policy> get_iam_user_policy_from_attr(CephContext* cct,
std::map<std::string, bufferlist>& attrs,
const std::string& tenant);
inline int get_system_versioning_params(req_state *s,
uint64_t *olh_epoch,
std::string *version_id)
{
if (!s->system_request) {
return 0;
}
if (olh_epoch) {
std::string epoch_str = s->info.args.get(RGW_SYS_PARAM_PREFIX "versioned-epoch");
if (!epoch_str.empty()) {
std::string err;
*olh_epoch = strict_strtol(epoch_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_subdout(s, rgw, 0) << "failed to parse versioned-epoch param"
<< dendl;
return -EINVAL;
}
}
}
if (version_id) {
*version_id = s->info.args.get(RGW_SYS_PARAM_PREFIX "version-id");
}
return 0;
} /* get_system_versioning_params */
static inline void format_xattr(std::string &xattr)
{
/* If the extended attribute is not valid UTF-8, we encode it using
* quoted-printable encoding.
*/
if ((check_utf8(xattr.c_str(), xattr.length()) != 0) ||
(check_for_control_characters(xattr.c_str(), xattr.length()) != 0)) {
static const char MIME_PREFIX_STR[] = "=?UTF-8?Q?";
static const int MIME_PREFIX_LEN = sizeof(MIME_PREFIX_STR) - 1;
static const char MIME_SUFFIX_STR[] = "?=";
static const int MIME_SUFFIX_LEN = sizeof(MIME_SUFFIX_STR) - 1;
int mlen = mime_encode_as_qp(xattr.c_str(), NULL, 0);
char *mime = new char[MIME_PREFIX_LEN + mlen + MIME_SUFFIX_LEN + 1];
strcpy(mime, MIME_PREFIX_STR);
mime_encode_as_qp(xattr.c_str(), mime + MIME_PREFIX_LEN, mlen);
strcpy(mime + MIME_PREFIX_LEN + (mlen - 1), MIME_SUFFIX_STR);
xattr.assign(mime);
delete [] mime;
}
} /* format_xattr */
/**
* Get the HTTP request metadata out of the req_state as a
* map(<attr_name, attr_contents>, where attr_name is RGW_ATTR_PREFIX.HTTP_NAME)
* s: The request state
* attrs: will be filled up with attrs mapped as <attr_name, attr_contents>
* On success returns 0.
* On failure returns a negative error code.
*
*/
inline int rgw_get_request_metadata(const DoutPrefixProvider *dpp,
CephContext* const cct,
struct req_info& info,
std::map<std::string, ceph::bufferlist>& attrs,
const bool allow_empty_attrs = true)
{
static const std::set<std::string> blocklisted_headers = {
"x-amz-server-side-encryption-customer-algorithm",
"x-amz-server-side-encryption-customer-key",
"x-amz-server-side-encryption-customer-key-md5",
"x-amz-storage-class"
};
size_t valid_meta_count = 0;
for (auto& kv : info.x_meta_map) {
const std::string& name = kv.first;
std::string& xattr = kv.second;
if (blocklisted_headers.count(name) == 1) {
ldpp_subdout(dpp, rgw, 10) << "skipping x>> " << name << dendl;
continue;
} else if (allow_empty_attrs || !xattr.empty()) {
ldpp_subdout(dpp, rgw, 10) << "x>> " << name << ":" << xattr << dendl;
format_xattr(xattr);
std::string attr_name(RGW_ATTR_PREFIX);
attr_name.append(name);
/* Check roughly whether we aren't going behind the limit on attribute
* name. Passing here doesn't guarantee that an OSD will accept that
* as ObjectStore::get_max_attr_name_length() can set the limit even
* lower than the "osd_max_attr_name_len" configurable. */
const auto max_attr_name_len = cct->_conf->rgw_max_attr_name_len;
if (max_attr_name_len && attr_name.length() > max_attr_name_len) {
return -ENAMETOOLONG;
}
/* Similar remarks apply to the check for value size. We're veryfing
* it early at the RGW's side as it's being claimed in /info. */
const auto max_attr_size = cct->_conf->rgw_max_attr_size;
if (max_attr_size && xattr.length() > max_attr_size) {
return -EFBIG;
}
/* Swift allows administrators to limit the number of metadats items
* send _in a single request_. */
const auto max_attrs_num_in_req = cct->_conf->rgw_max_attrs_num_in_req;
if (max_attrs_num_in_req &&
++valid_meta_count > max_attrs_num_in_req) {
return -E2BIG;
}
auto rval = attrs.emplace(std::move(attr_name), ceph::bufferlist());
/* At the moment the value of the freshly created attribute key-value
* pair is an empty bufferlist. */
ceph::bufferlist& bl = rval.first->second;
bl.append(xattr.c_str(), xattr.size() + 1);
}
}
return 0;
} /* rgw_get_request_metadata */
inline void encode_delete_at_attr(boost::optional<ceph::real_time> delete_at,
std::map<std::string, bufferlist>& attrs)
{
if (delete_at == boost::none) {
return;
}
bufferlist delatbl;
encode(*delete_at, delatbl);
attrs[RGW_ATTR_DELETE_AT] = delatbl;
} /* encode_delete_at_attr */
inline void encode_obj_tags_attr(RGWObjTags* obj_tags, std::map<std::string, bufferlist>& attrs)
{
if (obj_tags == nullptr){
// we assume the user submitted a tag format which we couldn't parse since
// this wouldn't be parsed later by get/put obj tags, lets delete if the
// attr was populated
return;
}
bufferlist tagsbl;
obj_tags->encode(tagsbl);
attrs[RGW_ATTR_TAGS] = tagsbl;
}
inline int encode_dlo_manifest_attr(const char * const dlo_manifest,
std::map<std::string, bufferlist>& attrs)
{
std::string dm = dlo_manifest;
if (dm.find('/') == std::string::npos) {
return -EINVAL;
}
bufferlist manifest_bl;
manifest_bl.append(dlo_manifest, strlen(dlo_manifest) + 1);
attrs[RGW_ATTR_USER_MANIFEST] = manifest_bl;
return 0;
} /* encode_dlo_manifest_attr */
inline void complete_etag(MD5& hash, std::string *etag)
{
char etag_buf[CEPH_CRYPTO_MD5_DIGESTSIZE];
char etag_buf_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 16];
hash.Final((unsigned char *)etag_buf);
buf_to_hex((const unsigned char *)etag_buf, CEPH_CRYPTO_MD5_DIGESTSIZE,
etag_buf_str);
*etag = etag_buf_str;
} /* complete_etag */
using boost::container::flat_map;
class RGWGetAttrs : public RGWOp {
public:
using get_attrs_t = flat_map<std::string, std::optional<buffer::list>>;
protected:
get_attrs_t attrs;
public:
RGWGetAttrs()
{}
virtual ~RGWGetAttrs() {}
void emplace_key(std::string&& key) {
attrs.emplace(std::move(key), std::nullopt);
}
int verify_permission(optional_yield y);
void pre_exec();
void execute(optional_yield y);
virtual int get_params() = 0;
virtual void send_response() = 0;
virtual const char* name() const { return "get_attrs"; }
virtual RGWOpType get_type() { return RGW_OP_GET_ATTRS; }
virtual uint32_t op_mask() { return RGW_OP_TYPE_READ; }
}; /* RGWGetAttrs */
class RGWSetAttrs : public RGWOp {
protected:
std::map<std::string, buffer::list> attrs;
public:
RGWSetAttrs() {}
~RGWSetAttrs() override {}
void emplace_attr(std::string&& key, buffer::list&& bl) {
attrs.emplace(std::move(key), std::move(bl));
}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
void send_response() override = 0;
const char* name() const override { return "set_attrs"; }
RGWOpType get_type() override { return RGW_OP_SET_ATTRS; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWRMAttrs : public RGWOp {
protected:
rgw::sal::Attrs attrs;
public:
RGWRMAttrs()
{}
virtual ~RGWRMAttrs() {}
void emplace_key(std::string&& key) {
attrs.emplace(std::move(key), buffer::list());
}
int verify_permission(optional_yield y);
void pre_exec();
void execute(optional_yield y);
virtual int get_params() = 0;
virtual void send_response() = 0;
virtual const char* name() const { return "rm_attrs"; }
virtual RGWOpType get_type() { return RGW_OP_DELETE_ATTRS; }
virtual uint32_t op_mask() { return RGW_OP_TYPE_DELETE; }
}; /* RGWRMAttrs */
class RGWGetObjLayout : public RGWOp {
public:
RGWGetObjLayout() {
}
int check_caps(RGWUserCaps& caps) {
return caps.check_cap("admin", RGW_CAP_READ);
}
int verify_permission(optional_yield) override {
return check_caps(s->user->get_info().caps);
}
void pre_exec() override;
void execute(optional_yield y) override;
const char* name() const override { return "get_obj_layout"; }
virtual RGWOpType get_type() override { return RGW_OP_GET_OBJ_LAYOUT; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutBucketPolicy : public RGWOp {
bufferlist data;
public:
RGWPutBucketPolicy() = default;
~RGWPutBucketPolicy() {
}
void send_response() override;
int verify_permission(optional_yield y) override;
uint32_t op_mask() override {
return RGW_OP_TYPE_WRITE;
}
void execute(optional_yield y) override;
int get_params(optional_yield y);
const char* name() const override { return "put_bucket_policy"; }
RGWOpType get_type() override {
return RGW_OP_PUT_BUCKET_POLICY;
}
};
class RGWGetBucketPolicy : public RGWOp {
buffer::list policy;
public:
RGWGetBucketPolicy() = default;
void send_response() override;
int verify_permission(optional_yield y) override;
uint32_t op_mask() override {
return RGW_OP_TYPE_READ;
}
void execute(optional_yield y) override;
const char* name() const override { return "get_bucket_policy"; }
RGWOpType get_type() override {
return RGW_OP_GET_BUCKET_POLICY;
}
};
class RGWDeleteBucketPolicy : public RGWOp {
public:
RGWDeleteBucketPolicy() = default;
void send_response() override;
int verify_permission(optional_yield y) override;
uint32_t op_mask() override {
return RGW_OP_TYPE_WRITE;
}
void execute(optional_yield y) override;
int get_params(optional_yield y);
const char* name() const override { return "delete_bucket_policy"; }
RGWOpType get_type() override {
return RGW_OP_DELETE_BUCKET_POLICY;
}
};
class RGWPutBucketObjectLock : public RGWOp {
protected:
bufferlist data;
bufferlist obj_lock_bl;
RGWObjectLock obj_lock;
public:
RGWPutBucketObjectLock() = default;
~RGWPutBucketObjectLock() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
virtual int get_params(optional_yield y) = 0;
const char* name() const override { return "put_bucket_object_lock"; }
RGWOpType get_type() override { return RGW_OP_PUT_BUCKET_OBJ_LOCK; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetBucketObjectLock : public RGWOp {
public:
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
const char* name() const override {return "get_bucket_object_lock"; }
RGWOpType get_type() override { return RGW_OP_GET_BUCKET_OBJ_LOCK; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutObjRetention : public RGWOp {
protected:
bufferlist data;
RGWObjectRetention obj_retention;
bool bypass_perm;
bool bypass_governance_mode;
public:
RGWPutObjRetention():bypass_perm(true), bypass_governance_mode(false) {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
virtual int get_params(optional_yield y) = 0;
const char* name() const override { return "put_obj_retention"; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
RGWOpType get_type() override { return RGW_OP_PUT_OBJ_RETENTION; }
};
class RGWGetObjRetention : public RGWOp {
protected:
RGWObjectRetention obj_retention;
public:
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
const char* name() const override {return "get_obj_retention"; }
RGWOpType get_type() override { return RGW_OP_GET_OBJ_RETENTION; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWPutObjLegalHold : public RGWOp {
protected:
bufferlist data;
RGWObjectLegalHold obj_legal_hold;
public:
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
virtual int get_params(optional_yield y) = 0;
const char* name() const override { return "put_obj_legal_hold"; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
RGWOpType get_type() override { return RGW_OP_PUT_OBJ_LEGAL_HOLD; }
};
class RGWGetObjLegalHold : public RGWOp {
protected:
RGWObjectLegalHold obj_legal_hold;
public:
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual void send_response() override = 0;
const char* name() const override {return "get_obj_legal_hold"; }
RGWOpType get_type() override { return RGW_OP_GET_OBJ_LEGAL_HOLD; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWConfigBucketMetaSearch : public RGWOp {
protected:
std::map<std::string, uint32_t> mdsearch_config;
public:
RGWConfigBucketMetaSearch() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
virtual int get_params(optional_yield y) = 0;
const char* name() const override { return "config_bucket_meta_search"; }
virtual RGWOpType get_type() override { return RGW_OP_CONFIG_BUCKET_META_SEARCH; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetBucketMetaSearch : public RGWOp {
public:
RGWGetBucketMetaSearch() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield) override {}
const char* name() const override { return "get_bucket_meta_search"; }
virtual RGWOpType get_type() override { return RGW_OP_GET_BUCKET_META_SEARCH; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
class RGWDelBucketMetaSearch : public RGWOp {
public:
RGWDelBucketMetaSearch() {}
int verify_permission(optional_yield y) override;
void pre_exec() override;
void execute(optional_yield y) override;
const char* name() const override { return "delete_bucket_meta_search"; }
virtual RGWOpType delete_type() { return RGW_OP_DEL_BUCKET_META_SEARCH; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
class RGWGetClusterStat : public RGWOp {
protected:
RGWClusterStat stats_op;
public:
RGWGetClusterStat() {}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWOp::init(driver, s, h);
}
int verify_permission(optional_yield) override {return 0;}
virtual void send_response() override = 0;
virtual int get_params(optional_yield y) = 0;
void execute(optional_yield y) override;
const char* name() const override { return "get_cluster_stat"; }
dmc::client_id dmclock_client() override { return dmc::client_id::admin; }
};
class RGWGetBucketPolicyStatus : public RGWOp {
protected:
bool isPublic {false};
public:
int verify_permission(optional_yield y) override;
const char* name() const override { return "get_bucket_policy_status"; }
virtual RGWOpType get_type() override { return RGW_OP_GET_BUCKET_POLICY_STATUS; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
void execute(optional_yield y) override;
dmc::client_id dmclock_client() override { return dmc::client_id::metadata; }
};
class RGWPutBucketPublicAccessBlock : public RGWOp {
protected:
bufferlist data;
PublicAccessBlockConfiguration access_conf;
public:
int verify_permission(optional_yield y) override;
const char* name() const override { return "put_bucket_public_access_block";}
virtual RGWOpType get_type() override { return RGW_OP_PUT_BUCKET_PUBLIC_ACCESS_BLOCK; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
int get_params(optional_yield y);
void execute(optional_yield y) override;
dmc::client_id dmclock_client() override { return dmc::client_id::metadata; }
};
class RGWGetBucketPublicAccessBlock : public RGWOp {
protected:
PublicAccessBlockConfiguration access_conf;
public:
int verify_permission(optional_yield y) override;
const char* name() const override { return "get_bucket_public_access_block";}
virtual RGWOpType get_type() override { return RGW_OP_GET_BUCKET_PUBLIC_ACCESS_BLOCK; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
int get_params(optional_yield y);
void execute(optional_yield y) override;
dmc::client_id dmclock_client() override { return dmc::client_id::metadata; }
};
class RGWDeleteBucketPublicAccessBlock : public RGWOp {
protected:
PublicAccessBlockConfiguration access_conf;
public:
int verify_permission(optional_yield y) override;
const char* name() const override { return "delete_bucket_public_access_block";}
virtual RGWOpType get_type() override { return RGW_OP_DELETE_BUCKET_PUBLIC_ACCESS_BLOCK; }
virtual uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
int get_params(optional_yield y);
void execute(optional_yield y) override;
void send_response() override;
dmc::client_id dmclock_client() override { return dmc::client_id::metadata; }
};
inline int parse_value_and_bound(
const std::string &input,
int &output,
const long lower_bound,
const long upper_bound,
const long default_val)
{
if (!input.empty()) {
char *endptr;
output = strtol(input.c_str(), &endptr, 10);
if (endptr) {
if (endptr == input.c_str()) return -EINVAL;
while (*endptr && isspace(*endptr)) // ignore white space
endptr++;
if (*endptr) {
return -EINVAL;
}
}
if(output > upper_bound) {
output = upper_bound;
}
if(output < lower_bound) {
output = lower_bound;
}
} else {
output = default_val;
}
return 0;
}
int rgw_policy_from_attrset(const DoutPrefixProvider *dpp,
CephContext *cct,
std::map<std::string, bufferlist>& attrset,
RGWAccessControlPolicy *policy);
| 80,195 | 29.002245 | 138 |
h
|
null |
ceph-main/src/rgw/rgw_op_type.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
enum RGWOpType {
RGW_OP_UNKNOWN = 0,
RGW_OP_GET_OBJ,
RGW_OP_LIST_BUCKETS,
RGW_OP_STAT_ACCOUNT,
RGW_OP_LIST_BUCKET,
RGW_OP_GET_BUCKET_LOGGING,
RGW_OP_GET_BUCKET_LOCATION,
RGW_OP_GET_BUCKET_VERSIONING,
RGW_OP_SET_BUCKET_VERSIONING,
RGW_OP_GET_BUCKET_WEBSITE,
RGW_OP_SET_BUCKET_WEBSITE,
RGW_OP_STAT_BUCKET,
RGW_OP_CREATE_BUCKET,
RGW_OP_DELETE_BUCKET,
RGW_OP_PUT_OBJ,
RGW_OP_STAT_OBJ,
RGW_OP_POST_OBJ,
RGW_OP_PUT_METADATA_ACCOUNT,
RGW_OP_PUT_METADATA_BUCKET,
RGW_OP_PUT_METADATA_OBJECT,
RGW_OP_SET_TEMPURL,
RGW_OP_DELETE_OBJ,
RGW_OP_COPY_OBJ,
RGW_OP_GET_ACLS,
RGW_OP_PUT_ACLS,
RGW_OP_GET_CORS,
RGW_OP_PUT_CORS,
RGW_OP_DELETE_CORS,
RGW_OP_OPTIONS_CORS,
RGW_OP_GET_BUCKET_ENCRYPTION,
RGW_OP_PUT_BUCKET_ENCRYPTION,
RGW_OP_DELETE_BUCKET_ENCRYPTION,
RGW_OP_GET_REQUEST_PAYMENT,
RGW_OP_SET_REQUEST_PAYMENT,
RGW_OP_INIT_MULTIPART,
RGW_OP_COMPLETE_MULTIPART,
RGW_OP_ABORT_MULTIPART,
RGW_OP_LIST_MULTIPART,
RGW_OP_LIST_BUCKET_MULTIPARTS,
RGW_OP_DELETE_MULTI_OBJ,
RGW_OP_BULK_DELETE,
RGW_OP_GET_KEYS,
RGW_OP_GET_ATTRS,
RGW_OP_DELETE_ATTRS,
RGW_OP_SET_ATTRS,
RGW_OP_GET_CROSS_DOMAIN_POLICY,
RGW_OP_GET_HEALTH_CHECK,
RGW_OP_GET_INFO,
RGW_OP_CREATE_ROLE,
RGW_OP_DELETE_ROLE,
RGW_OP_GET_ROLE,
RGW_OP_MODIFY_ROLE_TRUST_POLICY,
RGW_OP_LIST_ROLES,
RGW_OP_PUT_ROLE_POLICY,
RGW_OP_GET_ROLE_POLICY,
RGW_OP_LIST_ROLE_POLICIES,
RGW_OP_DELETE_ROLE_POLICY,
RGW_OP_TAG_ROLE,
RGW_OP_LIST_ROLE_TAGS,
RGW_OP_UNTAG_ROLE,
RGW_OP_UPDATE_ROLE,
RGW_OP_PUT_BUCKET_POLICY,
RGW_OP_GET_BUCKET_POLICY,
RGW_OP_DELETE_BUCKET_POLICY,
RGW_OP_PUT_OBJ_TAGGING,
RGW_OP_GET_OBJ_TAGGING,
RGW_OP_DELETE_OBJ_TAGGING,
RGW_OP_PUT_LC,
RGW_OP_GET_LC,
RGW_OP_DELETE_LC,
RGW_OP_PUT_USER_POLICY,
RGW_OP_GET_USER_POLICY,
RGW_OP_LIST_USER_POLICIES,
RGW_OP_DELETE_USER_POLICY,
RGW_OP_PUT_BUCKET_OBJ_LOCK,
RGW_OP_GET_BUCKET_OBJ_LOCK,
RGW_OP_PUT_OBJ_RETENTION,
RGW_OP_GET_OBJ_RETENTION,
RGW_OP_PUT_OBJ_LEGAL_HOLD,
RGW_OP_GET_OBJ_LEGAL_HOLD,
/* rgw specific */
RGW_OP_ADMIN_SET_METADATA,
RGW_OP_GET_OBJ_LAYOUT,
RGW_OP_BULK_UPLOAD,
RGW_OP_METADATA_SEARCH,
RGW_OP_CONFIG_BUCKET_META_SEARCH,
RGW_OP_GET_BUCKET_META_SEARCH,
RGW_OP_DEL_BUCKET_META_SEARCH,
RGW_OP_SYNC_DATALOG_NOTIFY,
RGW_OP_SYNC_DATALOG_NOTIFY2,
RGW_OP_SYNC_MDLOG_NOTIFY,
RGW_OP_PERIOD_POST,
/* sts specific*/
RGW_STS_ASSUME_ROLE,
RGW_STS_GET_SESSION_TOKEN,
RGW_STS_ASSUME_ROLE_WEB_IDENTITY,
/* pubsub */
RGW_OP_PUBSUB_TOPIC_CREATE,
RGW_OP_PUBSUB_TOPICS_LIST,
RGW_OP_PUBSUB_TOPIC_GET,
RGW_OP_PUBSUB_TOPIC_DELETE,
RGW_OP_PUBSUB_SUB_CREATE,
RGW_OP_PUBSUB_SUB_GET,
RGW_OP_PUBSUB_SUB_DELETE,
RGW_OP_PUBSUB_SUB_PULL,
RGW_OP_PUBSUB_SUB_ACK,
RGW_OP_PUBSUB_NOTIF_CREATE,
RGW_OP_PUBSUB_NOTIF_DELETE,
RGW_OP_PUBSUB_NOTIF_LIST,
RGW_OP_GET_BUCKET_TAGGING,
RGW_OP_PUT_BUCKET_TAGGING,
RGW_OP_DELETE_BUCKET_TAGGING,
RGW_OP_GET_BUCKET_REPLICATION,
RGW_OP_PUT_BUCKET_REPLICATION,
RGW_OP_DELETE_BUCKET_REPLICATION,
/* public access */
RGW_OP_GET_BUCKET_POLICY_STATUS,
RGW_OP_PUT_BUCKET_PUBLIC_ACCESS_BLOCK,
RGW_OP_GET_BUCKET_PUBLIC_ACCESS_BLOCK,
RGW_OP_DELETE_BUCKET_PUBLIC_ACCESS_BLOCK,
/*OIDC provider specific*/
RGW_OP_CREATE_OIDC_PROVIDER,
RGW_OP_DELETE_OIDC_PROVIDER,
RGW_OP_GET_OIDC_PROVIDER,
RGW_OP_LIST_OIDC_PROVIDERS,
};
| 3,479 | 24.970149 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_opa.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_opa.h"
#include "rgw_http_client.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
int rgw_opa_authorize(RGWOp *& op,
req_state * const s)
{
ldpp_dout(op, 2) << "authorizing request using OPA" << dendl;
/* get OPA url */
const string& opa_url = s->cct->_conf->rgw_opa_url;
if (opa_url == "") {
ldpp_dout(op, 2) << "OPA_URL not provided" << dendl;
return -ERR_INVALID_REQUEST;
}
ldpp_dout(op, 2) << "OPA URL= " << opa_url.c_str() << dendl;
/* get authentication token for OPA */
const string& opa_token = s->cct->_conf->rgw_opa_token;
int ret;
bufferlist bl;
RGWHTTPTransceiver req(s->cct, "POST", opa_url.c_str(), &bl);
/* set required headers for OPA request */
req.append_header("X-Auth-Token", opa_token);
req.append_header("Content-Type", "application/json");
req.append_header("Expect", "100-continue");
/* check if we want to verify OPA server SSL certificate */
req.set_verify_ssl(s->cct->_conf->rgw_opa_verify_ssl);
/* create json request body */
JSONFormatter jf;
jf.open_object_section("");
jf.open_object_section("input");
const char *request_method = s->info.env->get("REQUEST_METHOD");
if (request_method) {
jf.dump_string("method", request_method);
}
jf.dump_string("relative_uri", s->relative_uri.c_str());
jf.dump_string("decoded_uri", s->decoded_uri.c_str());
jf.dump_string("params", s->info.request_params.c_str());
jf.dump_string("request_uri_aws4", s->info.request_uri_aws4.c_str());
if (s->object) {
jf.dump_string("object_name", s->object->get_name().c_str());
}
if (s->auth.identity) {
jf.dump_string("subuser", s->auth.identity->get_subuser().c_str());
}
if (s->user) {
jf.dump_object("user_info", s->user->get_info());
}
if (s->bucket) {
jf.dump_object("bucket_info", s->bucket->get_info());
}
jf.close_section();
jf.close_section();
std::stringstream ss;
jf.flush(ss);
req.set_post_data(ss.str());
req.set_send_length(ss.str().length());
/* send request */
ret = req.process(null_yield);
if (ret < 0) {
ldpp_dout(op, 2) << "OPA process error:" << bl.c_str() << dendl;
return ret;
}
/* check OPA response */
JSONParser parser;
if (!parser.parse(bl.c_str(), bl.length())) {
ldpp_dout(op, 2) << "OPA parse error: malformed json" << dendl;
return -EINVAL;
}
bool opa_result;
JSONDecoder::decode_json("result", opa_result, &parser);
if (opa_result == false) {
ldpp_dout(op, 2) << "OPA rejecting request" << dendl;
return -EPERM;
}
ldpp_dout(op, 2) << "OPA accepting request" << dendl;
return 0;
}
| 2,787 | 27.44898 | 71 |
cc
|
null |
ceph-main/src/rgw/rgw_opa.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"
#include "rgw_op.h"
/* authorize request using OPA */
int rgw_opa_authorize(RGWOp*& op,
req_state* s);
| 270 | 21.583333 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_orphan.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string>
#include "common/config.h"
#include "common/Formatter.h"
#include "common/errno.h"
#include "rgw_op.h"
#include "rgw_multi.h"
#include "rgw_orphan.h"
#include "rgw_zone.h"
#include "rgw_bucket.h"
#include "rgw_sal_rados.h"
#include "services/svc_zone.h"
#define dout_subsys ceph_subsys_rgw
#define DEFAULT_NUM_SHARDS 64
using namespace std;
static string obj_fingerprint(const string& oid, const char *force_ns = NULL)
{
ssize_t pos = oid.find('_');
if (pos < 0) {
cerr << "ERROR: object does not have a bucket marker: " << oid << std::endl;
}
string obj_marker = oid.substr(0, pos);
rgw_obj_key key;
rgw_obj_key::parse_raw_oid(oid.substr(pos + 1), &key);
if (key.ns.empty()) {
return oid;
}
string s = oid;
if (force_ns) {
rgw_bucket b;
rgw_obj new_obj(b, key);
s = obj_marker + "_" + new_obj.get_oid();
}
/* cut out suffix */
size_t i = s.size() - 1;
for (; i >= s.size() - 10; --i) {
char c = s[i];
if (!isdigit(c) && c != '.' && c != '_') {
break;
}
}
return s.substr(0, i + 1);
}
int RGWOrphanStore::read_job(const string& job_name, RGWOrphanSearchState & state)
{
set<string> keys;
map<string, bufferlist> vals;
keys.insert(job_name);
int r = ioctx.omap_get_vals_by_keys(oid, keys, &vals);
if (r < 0) {
return r;
}
map<string, bufferlist>::iterator iter = vals.find(job_name);
if (iter == vals.end()) {
return -ENOENT;
}
try {
bufferlist& bl = iter->second;
decode(state, bl);
} catch (buffer::error& err) {
lderr(store->ctx()) << "ERROR: could not decode buffer" << dendl;
return -EIO;
}
return 0;
}
int RGWOrphanStore::write_job(const string& job_name, const RGWOrphanSearchState& state)
{
map<string, bufferlist> vals;
bufferlist bl;
encode(state, bl);
vals[job_name] = bl;
int r = ioctx.omap_set(oid, vals);
if (r < 0) {
return r;
}
return 0;
}
int RGWOrphanStore::remove_job(const string& job_name)
{
set<string> keys;
keys.insert(job_name);
int r = ioctx.omap_rm_keys(oid, keys);
if (r < 0) {
return r;
}
return 0;
}
int RGWOrphanStore::list_jobs(map <string,RGWOrphanSearchState>& job_list)
{
map <string,bufferlist> vals;
int MAX_READ=1024;
string marker="";
int r = 0;
// loop through all the omap vals from index object, storing them to job_list,
// read in batches of 1024, we update the marker every iteration and exit the
// loop when we find that total size read out is less than batch size
do {
r = ioctx.omap_get_vals(oid, marker, MAX_READ, &vals);
if (r < 0) {
return r;
}
r = vals.size();
for (const auto &it : vals) {
marker=it.first;
RGWOrphanSearchState state;
try {
bufferlist bl = it.second;
decode(state, bl);
} catch (buffer::error& err) {
lderr(store->ctx()) << "ERROR: could not decode buffer" << dendl;
return -EIO;
}
job_list[it.first] = state;
}
} while (r == MAX_READ);
return 0;
}
int RGWOrphanStore::init(const DoutPrefixProvider *dpp)
{
const rgw_pool& log_pool = static_cast<rgw::sal::RadosStore*>(store)->svc()->zone->get_zone_params().log_pool;
int r = rgw_init_ioctx(dpp, static_cast<rgw::sal::RadosStore*>(store)->getRados()->get_rados_handle(), log_pool, ioctx);
if (r < 0) {
cerr << "ERROR: failed to open log pool (" << log_pool << " ret=" << r << std::endl;
return r;
}
return 0;
}
int RGWOrphanStore::store_entries(const DoutPrefixProvider *dpp, const string& oid, const map<string, bufferlist>& entries)
{
librados::ObjectWriteOperation op;
op.omap_set(entries);
cout << "storing " << entries.size() << " entries at " << oid << std::endl;
ldpp_dout(dpp, 20) << "storing " << entries.size() << " entries at " << oid << ": " << dendl;
for (map<string, bufferlist>::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) {
ldpp_dout(dpp, 20) << " > " << iter->first << dendl;
}
int ret = rgw_rados_operate(dpp, ioctx, oid, &op, null_yield);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: " << __func__ << "(" << oid << ") returned ret=" << ret << dendl;
}
return 0;
}
int RGWOrphanStore::read_entries(const string& oid, const string& marker, map<string, bufferlist> *entries, bool *truncated)
{
#define MAX_OMAP_GET 100
int ret = ioctx.omap_get_vals(oid, marker, MAX_OMAP_GET, entries);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: " << __func__ << "(" << oid << ") returned ret=" << cpp_strerror(-ret) << std::endl;
}
*truncated = (entries->size() == MAX_OMAP_GET);
return 0;
}
int RGWOrphanSearch::init(const DoutPrefixProvider *dpp, const string& job_name, RGWOrphanSearchInfo *info, bool _detailed_mode)
{
int r = orphan_store.init(dpp);
if (r < 0) {
return r;
}
constexpr int64_t MAX_LIST_OBJS_ENTRIES=100;
max_list_bucket_entries = std::max(store->ctx()->_conf->rgw_list_bucket_min_readahead,
MAX_LIST_OBJS_ENTRIES);
detailed_mode = _detailed_mode;
RGWOrphanSearchState state;
r = orphan_store.read_job(job_name, state);
if (r < 0 && r != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: failed to read state ret=" << r << dendl;
return r;
}
if (r == 0) {
search_info = state.info;
search_stage = state.stage;
} else if (info) { /* r == -ENOENT, initiate a new job if info was provided */
search_info = *info;
search_info.job_name = job_name;
search_info.num_shards = (info->num_shards ? info->num_shards : DEFAULT_NUM_SHARDS);
search_info.start_time = ceph_clock_now();
search_stage = RGWOrphanSearchStage(ORPHAN_SEARCH_STAGE_INIT);
r = save_state();
if (r < 0) {
ldpp_dout(dpp, -1) << "ERROR: failed to write state ret=" << r << dendl;
return r;
}
} else {
ldpp_dout(dpp, -1) << "ERROR: job not found" << dendl;
return r;
}
index_objs_prefix = RGW_ORPHAN_INDEX_PREFIX + string(".");
index_objs_prefix += job_name;
for (int i = 0; i < search_info.num_shards; i++) {
char buf[128];
snprintf(buf, sizeof(buf), "%s.rados.%d", index_objs_prefix.c_str(), i);
all_objs_index[i] = buf;
snprintf(buf, sizeof(buf), "%s.buckets.%d", index_objs_prefix.c_str(), i);
buckets_instance_index[i] = buf;
snprintf(buf, sizeof(buf), "%s.linked.%d", index_objs_prefix.c_str(), i);
linked_objs_index[i] = buf;
}
return 0;
}
int RGWOrphanSearch::log_oids(const DoutPrefixProvider *dpp, map<int, string>& log_shards, map<int, list<string> >& oids)
{
map<int, list<string> >::iterator miter = oids.begin();
list<log_iter_info> liters; /* a list of iterator pairs for begin and end */
for (; miter != oids.end(); ++miter) {
log_iter_info info;
info.oid = log_shards[miter->first];
info.cur = miter->second.begin();
info.end = miter->second.end();
liters.push_back(info);
}
list<log_iter_info>::iterator list_iter;
while (!liters.empty()) {
list_iter = liters.begin();
while (list_iter != liters.end()) {
log_iter_info& cur_info = *list_iter;
list<string>::iterator& cur = cur_info.cur;
list<string>::iterator& end = cur_info.end;
map<string, bufferlist> entries;
#define MAX_OMAP_SET_ENTRIES 100
for (int j = 0; cur != end && j != MAX_OMAP_SET_ENTRIES; ++cur, ++j) {
ldpp_dout(dpp, 20) << "adding obj: " << *cur << dendl;
entries[*cur] = bufferlist();
}
int ret = orphan_store.store_entries(dpp, cur_info.oid, entries);
if (ret < 0) {
return ret;
}
list<log_iter_info>::iterator tmp = list_iter;
++list_iter;
if (cur == end) {
liters.erase(tmp);
}
}
}
return 0;
}
int RGWOrphanSearch::build_all_oids_index(const DoutPrefixProvider *dpp)
{
librados::IoCtx ioctx;
int ret = rgw_init_ioctx(dpp, static_cast<rgw::sal::RadosStore*>(store)->getRados()->get_rados_handle(), search_info.pool, ioctx);
if (ret < 0) {
ldpp_dout(dpp, -1) << __func__ << ": rgw_init_ioctx() returned ret=" << ret << dendl;
return ret;
}
ioctx.set_namespace(librados::all_nspaces);
librados::NObjectIterator i = ioctx.nobjects_begin();
librados::NObjectIterator i_end = ioctx.nobjects_end();
map<int, list<string> > oids;
int count = 0;
uint64_t total = 0;
cout << "logging all objects in the pool" << std::endl;
for (; i != i_end; ++i) {
string nspace = i->get_nspace();
string oid = i->get_oid();
string locator = i->get_locator();
ssize_t pos = oid.find('_');
if (pos < 0) {
cout << "unidentified oid: " << oid << ", skipping" << std::endl;
/* what is this object, oids should be in the format of <bucket marker>_<obj>,
* skip this entry
*/
continue;
}
string stripped_oid = oid.substr(pos + 1);
rgw_obj_key key;
if (!rgw_obj_key::parse_raw_oid(stripped_oid, &key)) {
cout << "cannot parse oid: " << oid << ", skipping" << std::endl;
continue;
}
if (key.ns.empty()) {
/* skipping head objects, we don't want to remove these as they are mutable and
* cleaning them up is racy (can race with object removal and a later recreation)
*/
cout << "skipping head object: oid=" << oid << std::endl;
continue;
}
string oid_fp = obj_fingerprint(oid);
ldout(store->ctx(), 20) << "oid_fp=" << oid_fp << dendl;
int shard = orphan_shard(oid_fp);
oids[shard].push_back(oid);
#define COUNT_BEFORE_FLUSH 1000
++total;
if (++count >= COUNT_BEFORE_FLUSH) {
ldout(store->ctx(), 1) << "iterated through " << total << " objects" << dendl;
ret = log_oids(dpp, all_objs_index, oids);
if (ret < 0) {
cerr << __func__ << ": ERROR: log_oids() returned ret=" << ret << std::endl;
return ret;
}
count = 0;
oids.clear();
}
}
ret = log_oids(dpp, all_objs_index, oids);
if (ret < 0) {
cerr << __func__ << ": ERROR: log_oids() returned ret=" << ret << std::endl;
return ret;
}
return 0;
}
int RGWOrphanSearch::build_buckets_instance_index(const DoutPrefixProvider *dpp)
{
void *handle;
int max = 1000;
string section = "bucket.instance";
int ret = store->meta_list_keys_init(dpp, section, string(), &handle);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: can't get key: " << cpp_strerror(-ret) << dendl;
return ret;
}
map<int, list<string> > instances;
bool truncated;
RGWObjectCtx obj_ctx(store);
int count = 0;
uint64_t total = 0;
do {
list<string> keys;
ret = store->meta_list_keys_next(dpp, handle, max, keys, &truncated);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: lists_keys_next(): " << cpp_strerror(-ret) << dendl;
return ret;
}
for (list<string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) {
++total;
ldpp_dout(dpp, 10) << "bucket_instance=" << *iter << " total=" << total << dendl;
int shard = orphan_shard(*iter);
instances[shard].push_back(*iter);
if (++count >= COUNT_BEFORE_FLUSH) {
ret = log_oids(dpp, buckets_instance_index, instances);
if (ret < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: log_oids() returned ret=" << ret << dendl;
return ret;
}
count = 0;
instances.clear();
}
}
} while (truncated);
store->meta_list_keys_complete(handle);
ret = log_oids(dpp, buckets_instance_index, instances);
if (ret < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: log_oids() returned ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWOrphanSearch::handle_stat_result(const DoutPrefixProvider *dpp, map<int, list<string> >& oids, RGWRados::Object::Stat::Result& result)
{
set<string> obj_oids;
rgw_bucket& bucket = result.obj.bucket;
if (!result.manifest) { /* a very very old object, or part of a multipart upload during upload */
const string loc = bucket.bucket_id + "_" + result.obj.get_oid();
obj_oids.insert(obj_fingerprint(loc));
/*
* multipart parts don't have manifest on them, it's in the meta object. Instead of reading the
* meta object, just add a "shadow" object to the mix
*/
obj_oids.insert(obj_fingerprint(loc, "shadow"));
} else {
RGWObjManifest& manifest = *result.manifest;
if (!detailed_mode &&
manifest.get_obj_size() <= manifest.get_head_size()) {
ldpp_dout(dpp, 5) << "skipping object as it fits in a head" << dendl;
return 0;
}
RGWObjManifest::obj_iterator miter;
for (miter = manifest.obj_begin(dpp); miter != manifest.obj_end(dpp); ++miter) {
const rgw_raw_obj& loc = miter.get_location().get_raw_obj(store->getRados());
string s = loc.oid;
obj_oids.insert(obj_fingerprint(s));
}
}
for (set<string>::iterator iter = obj_oids.begin(); iter != obj_oids.end(); ++iter) {
ldpp_dout(dpp, 20) << __func__ << ": oid for obj=" << result.obj << ": " << *iter << dendl;
int shard = orphan_shard(*iter);
oids[shard].push_back(*iter);
}
return 0;
}
int RGWOrphanSearch::pop_and_handle_stat_op(const DoutPrefixProvider *dpp, map<int, list<string> >& oids, std::deque<RGWRados::Object::Stat>& ops)
{
RGWRados::Object::Stat& front_op = ops.front();
int ret = front_op.wait(dpp);
if (ret < 0) {
if (ret != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " << cpp_strerror(-ret) << dendl;
}
goto done;
}
ret = handle_stat_result(dpp, oids, front_op.result);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: handle_stat_response() returned error: " << cpp_strerror(-ret) << dendl;
}
done:
ops.pop_front();
return ret;
}
int RGWOrphanSearch::build_linked_oids_for_bucket(const DoutPrefixProvider *dpp, const string& bucket_instance_id, map<int, list<string> >& oids)
{
RGWObjectCtx obj_ctx(store);
rgw_bucket orphan_bucket;
int shard_id;
int ret = rgw_bucket_parse_bucket_key(store->ctx(), bucket_instance_id,
&orphan_bucket, &shard_id);
if (ret < 0) {
ldpp_dout(dpp, 0) << __func__ << " failed to parse bucket instance: "
<< bucket_instance_id << " skipping" << dendl;
return ret;
}
std::unique_ptr<rgw::sal::Bucket> cur_bucket;
ret = store->get_bucket(dpp, nullptr, orphan_bucket, &cur_bucket, null_yield);
if (ret < 0) {
if (ret == -ENOENT) {
/* probably raced with bucket removal */
return 0;
}
ldpp_dout(dpp, -1) << __func__ << ": ERROR: RGWRados::get_bucket_instance_info() returned ret=" << ret << dendl;
return ret;
}
if (cur_bucket->get_bucket_id() != orphan_bucket.bucket_id) {
ldpp_dout(dpp, 0) << __func__ << ": Skipping stale bucket instance: "
<< orphan_bucket.name << ": "
<< orphan_bucket.bucket_id << dendl;
return 0;
}
if (cur_bucket->get_info().layout.resharding != rgw::BucketReshardState::None) {
ldpp_dout(dpp, 0) << __func__ << ": reshard in progress. Skipping "
<< orphan_bucket.name << ": "
<< orphan_bucket.bucket_id << dendl;
return 0;
}
rgw_bucket b;
rgw_bucket_parse_bucket_key(store->ctx(), bucket_instance_id, &b, nullptr);
std::unique_ptr<rgw::sal::Bucket> bucket;
ret = store->get_bucket(dpp, nullptr, b, &bucket, null_yield);
if (ret < 0) {
if (ret == -ENOENT) {
/* probably raced with bucket removal */
return 0;
}
ldpp_dout(dpp, -1) << __func__ << ": ERROR: RGWRados::get_bucket_instance_info() returned ret=" << ret << dendl;
return ret;
}
ldpp_dout(dpp, 10) << "building linked oids for bucket instance: " << bucket_instance_id << dendl;
RGWRados::Bucket target(store->getRados(), cur_bucket->get_info());
RGWRados::Bucket::List list_op(&target);
string marker;
list_op.params.marker = rgw_obj_key(marker);
list_op.params.list_versions = true;
list_op.params.enforce_ns = false;
bool truncated;
deque<RGWRados::Object::Stat> stat_ops;
do {
vector<rgw_bucket_dir_entry> result;
ret = list_op.list_objects(dpp, max_list_bucket_entries,
&result, nullptr, &truncated, null_yield);
if (ret < 0) {
cerr << "ERROR: store->list_objects(): " << cpp_strerror(-ret) << std::endl;
return ret;
}
for (vector<rgw_bucket_dir_entry>::iterator iter = result.begin(); iter != result.end(); ++iter) {
rgw_bucket_dir_entry& entry = *iter;
if (entry.key.instance.empty()) {
ldpp_dout(dpp, 20) << "obj entry: " << entry.key.name << dendl;
} else {
ldpp_dout(dpp, 20) << "obj entry: " << entry.key.name << " [" << entry.key.instance << "]" << dendl;
}
ldpp_dout(dpp, 20) << __func__ << ": entry.key.name=" << entry.key.name << " entry.key.instance=" << entry.key.instance << dendl;
if (!detailed_mode &&
entry.meta.accounted_size <= (uint64_t)store->ctx()->_conf->rgw_max_chunk_size) {
ldpp_dout(dpp, 5) << __func__ << "skipping stat as the object " << entry.key.name
<< "fits in a head" << dendl;
continue;
}
rgw_obj obj(cur_bucket->get_key(), entry.key);
RGWRados::Object op_target(store->getRados(), cur_bucket->get_info(), obj_ctx, obj);
stat_ops.push_back(RGWRados::Object::Stat(&op_target));
RGWRados::Object::Stat& op = stat_ops.back();
ret = op.stat_async(dpp);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " << cpp_strerror(-ret) << dendl;
return ret;
}
if (stat_ops.size() >= max_concurrent_ios) {
ret = pop_and_handle_stat_op(dpp, oids, stat_ops);
if (ret < 0) {
if (ret != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " << cpp_strerror(-ret) << dendl;
}
}
}
if (oids.size() >= COUNT_BEFORE_FLUSH) {
ret = log_oids(dpp, linked_objs_index, oids);
if (ret < 0) {
cerr << __func__ << ": ERROR: log_oids() returned ret=" << ret << std::endl;
return ret;
}
oids.clear();
}
}
} while (truncated);
while (!stat_ops.empty()) {
ret = pop_and_handle_stat_op(dpp, oids, stat_ops);
if (ret < 0) {
if (ret != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " << cpp_strerror(-ret) << dendl;
}
}
}
return 0;
}
int RGWOrphanSearch::build_linked_oids_index(const DoutPrefixProvider *dpp)
{
map<int, list<string> > oids;
map<int, string>::iterator iter = buckets_instance_index.find(search_stage.shard);
for (; iter != buckets_instance_index.end(); ++iter) {
ldpp_dout(dpp, 0) << "building linked oids index: " << iter->first << "/" << buckets_instance_index.size() << dendl;
bool truncated;
string oid = iter->second;
do {
map<string, bufferlist> entries;
int ret = orphan_store.read_entries(oid, search_stage.marker, &entries, &truncated);
if (ret == -ENOENT) {
truncated = false;
ret = 0;
}
if (ret < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: read_entries() oid=" << oid << " returned ret=" << ret << dendl;
return ret;
}
if (entries.empty()) {
break;
}
for (map<string, bufferlist>::iterator eiter = entries.begin(); eiter != entries.end(); ++eiter) {
ldpp_dout(dpp, 20) << " indexed entry: " << eiter->first << dendl;
ret = build_linked_oids_for_bucket(dpp, eiter->first, oids);
if (ret < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: build_linked_oids_for_bucket() indexed entry=" << eiter->first
<< " returned ret=" << ret << dendl;
return ret;
}
}
search_stage.shard = iter->first;
search_stage.marker = entries.rbegin()->first; /* last entry */
} while (truncated);
search_stage.marker.clear();
}
int ret = log_oids(dpp, linked_objs_index, oids);
if (ret < 0) {
cerr << __func__ << ": ERROR: log_oids() returned ret=" << ret << std::endl;
return ret;
}
ret = save_state();
if (ret < 0) {
cerr << __func__ << ": ERROR: failed to write state ret=" << ret << std::endl;
return ret;
}
return 0;
}
class OMAPReader {
librados::IoCtx ioctx;
string oid;
map<string, bufferlist> entries;
map<string, bufferlist>::iterator iter;
string marker;
bool truncated;
public:
OMAPReader(librados::IoCtx& _ioctx, const string& _oid) : ioctx(_ioctx), oid(_oid), truncated(true) {
iter = entries.end();
}
int get_next(string *key, bufferlist *pbl, bool *done);
};
int OMAPReader::get_next(string *key, bufferlist *pbl, bool *done)
{
if (iter != entries.end()) {
*key = iter->first;
if (pbl) {
*pbl = iter->second;
}
++iter;
*done = false;
marker = *key;
return 0;
}
if (!truncated) {
*done = true;
return 0;
}
#define MAX_OMAP_GET_ENTRIES 100
int ret = ioctx.omap_get_vals(oid, marker, MAX_OMAP_GET_ENTRIES, &entries);
if (ret < 0) {
if (ret == -ENOENT) {
*done = true;
return 0;
}
return ret;
}
truncated = (entries.size() == MAX_OMAP_GET_ENTRIES);
iter = entries.begin();
return get_next(key, pbl, done);
}
int RGWOrphanSearch::compare_oid_indexes(const DoutPrefixProvider *dpp)
{
ceph_assert(linked_objs_index.size() == all_objs_index.size());
librados::IoCtx& ioctx = orphan_store.get_ioctx();
librados::IoCtx data_ioctx;
int ret = rgw_init_ioctx(dpp, static_cast<rgw::sal::RadosStore*>(store)->getRados()->get_rados_handle(), search_info.pool, data_ioctx);
if (ret < 0) {
ldpp_dout(dpp, -1) << __func__ << ": rgw_init_ioctx() returned ret=" << ret << dendl;
return ret;
}
uint64_t time_threshold = search_info.start_time.sec() - stale_secs;
map<int, string>::iterator liter = linked_objs_index.begin();
map<int, string>::iterator aiter = all_objs_index.begin();
for (; liter != linked_objs_index.end(); ++liter, ++aiter) {
OMAPReader linked_entries(ioctx, liter->second);
OMAPReader all_entries(ioctx, aiter->second);
bool done;
string cur_linked;
bool linked_done = false;
do {
string key;
int r = all_entries.get_next(&key, NULL, &done);
if (r < 0) {
return r;
}
if (done) {
break;
}
string key_fp = obj_fingerprint(key);
while (cur_linked < key_fp && !linked_done) {
r = linked_entries.get_next(&cur_linked, NULL, &linked_done);
if (r < 0) {
return r;
}
}
if (cur_linked == key_fp) {
ldpp_dout(dpp, 20) << "linked: " << key << dendl;
continue;
}
time_t mtime;
r = data_ioctx.stat(key, NULL, &mtime);
if (r < 0) {
if (r != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: ioctx.stat(" << key << ") returned ret=" << r << dendl;
}
continue;
}
if (stale_secs && (uint64_t)mtime >= time_threshold) {
ldpp_dout(dpp, 20) << "skipping: " << key << " (mtime=" << mtime << " threshold=" << time_threshold << ")" << dendl;
continue;
}
ldpp_dout(dpp, 20) << "leaked: " << key << dendl;
cout << "leaked: " << key << std::endl;
} while (!done);
}
return 0;
}
int RGWOrphanSearch::run(const DoutPrefixProvider *dpp)
{
int r;
switch (search_stage.stage) {
case ORPHAN_SEARCH_STAGE_INIT:
ldpp_dout(dpp, 0) << __func__ << "(): initializing state" << dendl;
search_stage = RGWOrphanSearchStage(ORPHAN_SEARCH_STAGE_LSPOOL);
r = save_state();
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: failed to save state, ret=" << r << dendl;
return r;
}
// fall through
case ORPHAN_SEARCH_STAGE_LSPOOL:
ldpp_dout(dpp, 0) << __func__ << "(): building index of all objects in pool" << dendl;
r = build_all_oids_index(dpp);
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: build_all_objs_index returned ret=" << r << dendl;
return r;
}
search_stage = RGWOrphanSearchStage(ORPHAN_SEARCH_STAGE_LSBUCKETS);
r = save_state();
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: failed to save state, ret=" << r << dendl;
return r;
}
// fall through
case ORPHAN_SEARCH_STAGE_LSBUCKETS:
ldpp_dout(dpp, 0) << __func__ << "(): building index of all bucket indexes" << dendl;
r = build_buckets_instance_index(dpp);
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: build_all_objs_index returned ret=" << r << dendl;
return r;
}
search_stage = RGWOrphanSearchStage(ORPHAN_SEARCH_STAGE_ITERATE_BI);
r = save_state();
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: failed to save state, ret=" << r << dendl;
return r;
}
// fall through
case ORPHAN_SEARCH_STAGE_ITERATE_BI:
ldpp_dout(dpp, 0) << __func__ << "(): building index of all linked objects" << dendl;
r = build_linked_oids_index(dpp);
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: build_all_objs_index returned ret=" << r << dendl;
return r;
}
search_stage = RGWOrphanSearchStage(ORPHAN_SEARCH_STAGE_COMPARE);
r = save_state();
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: failed to save state, ret=" << r << dendl;
return r;
}
// fall through
case ORPHAN_SEARCH_STAGE_COMPARE:
r = compare_oid_indexes(dpp);
if (r < 0) {
ldpp_dout(dpp, -1) << __func__ << ": ERROR: build_all_objs_index returned ret=" << r << dendl;
return r;
}
break;
default:
ceph_abort();
};
return 0;
}
int RGWOrphanSearch::remove_index(map<int, string>& index)
{
librados::IoCtx& ioctx = orphan_store.get_ioctx();
for (map<int, string>::iterator iter = index.begin(); iter != index.end(); ++iter) {
int r = ioctx.remove(iter->second);
if (r < 0) {
if (r != -ENOENT) {
ldout(store->ctx(), 0) << "ERROR: couldn't remove " << iter->second << ": ret=" << r << dendl;
}
}
}
return 0;
}
int RGWOrphanSearch::finish()
{
int r = remove_index(all_objs_index);
if (r < 0) {
ldout(store->ctx(), 0) << "ERROR: remove_index(" << all_objs_index << ") returned ret=" << r << dendl;
}
r = remove_index(buckets_instance_index);
if (r < 0) {
ldout(store->ctx(), 0) << "ERROR: remove_index(" << buckets_instance_index << ") returned ret=" << r << dendl;
}
r = remove_index(linked_objs_index);
if (r < 0) {
ldout(store->ctx(), 0) << "ERROR: remove_index(" << linked_objs_index << ") returned ret=" << r << dendl;
}
r = orphan_store.remove_job(search_info.job_name);
if (r < 0) {
ldout(store->ctx(), 0) << "ERROR: could not remove job name (" << search_info.job_name << ") ret=" << r << dendl;
}
return r;
}
int RGWRadosList::handle_stat_result(const DoutPrefixProvider *dpp,
RGWRados::Object::Stat::Result& result,
std::string& bucket_name,
rgw_obj_key& obj_key,
std::set<string>& obj_oids)
{
obj_oids.clear();
rgw_bucket& bucket = result.obj.bucket;
ldpp_dout(dpp, 20) << "RGWRadosList::" << __func__ <<
" bucket=" << bucket <<
", has_manifest=" << result.manifest.has_value() <<
dendl;
// iterator to store result of dlo/slo attribute find
decltype(result.attrs)::iterator attr_it = result.attrs.end();
const std::string oid = bucket.marker + "_" + result.obj.get_oid();
ldpp_dout(dpp, 20) << "radoslist processing object=\"" <<
oid << "\"" << dendl;
if (visited_oids.find(oid) != visited_oids.end()) {
// apparently we hit a loop; don't continue with this oid
ldpp_dout(dpp, 15) <<
"radoslist stopped loop at already visited object=\"" <<
oid << "\"" << dendl;
return 0;
}
bucket_name = bucket.name;
obj_key = result.obj.key;
if (!result.manifest) {
/* a very very old object, or part of a multipart upload during upload */
obj_oids.insert(oid);
/*
* multipart parts don't have manifest on them, it's in the meta
* object; we'll process them in
* RGWRadosList::do_incomplete_multipart
*/
} else if ((attr_it = result.attrs.find(RGW_ATTR_USER_MANIFEST)) !=
result.attrs.end()) {
// *** handle DLO object ***
obj_oids.insert(oid);
visited_oids.insert(oid); // prevent dlo loops
ldpp_dout(dpp, 15) << "radoslist added to visited list DLO=\"" <<
oid << "\"" << dendl;
char* prefix_path_c = attr_it->second.c_str();
const std::string& prefix_path = prefix_path_c;
const size_t sep_pos = prefix_path.find('/');
if (string::npos == sep_pos) {
return -EINVAL;
}
const std::string bucket_name = prefix_path.substr(0, sep_pos);
const std::string prefix = prefix_path.substr(sep_pos + 1);
add_bucket_prefix(bucket_name, prefix);
ldpp_dout(dpp, 25) << "radoslist DLO oid=\"" << oid <<
"\" added bucket=\"" << bucket_name << "\" prefix=\"" <<
prefix << "\" to process list" << dendl;
} else if ((attr_it = result.attrs.find(RGW_ATTR_USER_MANIFEST)) !=
result.attrs.end()) {
// *** handle SLO object ***
obj_oids.insert(oid);
visited_oids.insert(oid); // prevent slo loops
ldpp_dout(dpp, 15) << "radoslist added to visited list SLO=\"" <<
oid << "\"" << dendl;
RGWSLOInfo slo_info;
bufferlist::const_iterator bliter = attr_it->second.begin();
try {
::decode(slo_info, bliter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) <<
"ERROR: failed to decode slo manifest for " << oid << dendl;
return -EIO;
}
for (const auto& iter : slo_info.entries) {
const string& path_str = iter.path;
const size_t sep_pos = path_str.find('/', 1 /* skip initial slash */);
if (string::npos == sep_pos) {
return -EINVAL;
}
std::string bucket_name;
std::string obj_name;
bucket_name = url_decode(path_str.substr(1, sep_pos - 1));
obj_name = url_decode(path_str.substr(sep_pos + 1));
const rgw_obj_key obj_key(obj_name);
add_bucket_filter(bucket_name, obj_key);
ldpp_dout(dpp, 25) << "radoslist SLO oid=\"" << oid <<
"\" added bucket=\"" << bucket_name << "\" obj_key=\"" <<
obj_key << "\" to process list" << dendl;
}
} else {
RGWObjManifest& manifest = *result.manifest;
// in multipart, the head object contains no data and just has the
// manifest AND empty objects have no manifest, but they're
// realized as empty rados objects
if (0 == manifest.get_max_head_size() ||
manifest.obj_begin(dpp) == manifest.obj_end(dpp)) {
obj_oids.insert(oid);
// first_insert = true;
}
RGWObjManifest::obj_iterator miter;
for (miter = manifest.obj_begin(dpp); miter != manifest.obj_end(dpp); ++miter) {
const rgw_raw_obj& loc =
miter.get_location().get_raw_obj(store->getRados());
string s = loc.oid;
obj_oids.insert(s);
}
}
return 0;
} // RGWRadosList::handle_stat_result
int RGWRadosList::pop_and_handle_stat_op(
const DoutPrefixProvider *dpp,
RGWObjectCtx& obj_ctx,
std::deque<RGWRados::Object::Stat>& ops)
{
std::string bucket_name;
rgw_obj_key obj_key;
std::set<std::string> obj_oids;
RGWRados::Object::Stat& front_op = ops.front();
int ret = front_op.wait(dpp);
if (ret < 0) {
if (ret != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " <<
cpp_strerror(-ret) << dendl;
}
goto done;
}
ret = handle_stat_result(dpp, front_op.result, bucket_name, obj_key, obj_oids);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: handle_stat_result() returned error: " <<
cpp_strerror(-ret) << dendl;
}
// output results
for (const auto& o : obj_oids) {
if (include_rgw_obj_name) {
std::cout << o <<
field_separator << bucket_name <<
field_separator << obj_key <<
std::endl;
} else {
std::cout << o << std::endl;
}
}
done:
// invalidate object context for this object to avoid memory leak
// (see pr https://github.com/ceph/ceph/pull/30174)
obj_ctx.invalidate(front_op.result.obj);
ops.pop_front();
return ret;
}
#if 0 // code that may be the basis for expansion
int RGWRadosList::build_buckets_instance_index()
{
void *handle;
int max = 1000;
string section = "bucket.instance";
int ret = store->meta_mgr->list_keys_init(section, &handle);
if (ret < 0) {
lderr(store->ctx()) << "ERROR: can't get key: " << cpp_strerror(-ret) << dendl;
return ret;
}
map<int, list<string> > instances;
bool truncated;
RGWObjectCtx obj_ctx(store);
int count = 0;
uint64_t total = 0;
do {
list<string> keys;
ret = store->meta_mgr->list_keys_next(handle, max, keys, &truncated);
if (ret < 0) {
lderr(store->ctx()) << "ERROR: lists_keys_next(): " << cpp_strerror(-ret) << dendl;
return ret;
}
for (list<string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) {
++total;
ldout(store->ctx(), 10) << "bucket_instance=" << *iter << " total=" << total << dendl;
int shard = orphan_shard(*iter);
instances[shard].push_back(*iter);
if (++count >= COUNT_BEFORE_FLUSH) {
ret = log_oids(buckets_instance_index, instances);
if (ret < 0) {
lderr(store->ctx()) << __func__ << ": ERROR: log_oids() returned ret=" << ret << dendl;
return ret;
}
count = 0;
instances.clear();
}
}
} while (truncated);
ret = log_oids(buckets_instance_index, instances);
if (ret < 0) {
lderr(store->ctx()) << __func__ << ": ERROR: log_oids() returned ret=" << ret << dendl;
return ret;
}
store->meta_mgr->list_keys_complete(handle);
return 0;
}
#endif
int RGWRadosList::process_bucket(
const DoutPrefixProvider *dpp,
const std::string& bucket_instance_id,
const std::string& prefix,
const std::set<rgw_obj_key>& entries_filter)
{
ldpp_dout(dpp, 10) << "RGWRadosList::" << __func__ <<
" bucket_instance_id=" << bucket_instance_id <<
", prefix=" << prefix <<
", entries_filter.size=" << entries_filter.size() << dendl;
RGWBucketInfo bucket_info;
int ret = store->getRados()->get_bucket_instance_info(bucket_instance_id,
bucket_info,
nullptr,
nullptr,
null_yield,
dpp);
if (ret < 0) {
if (ret == -ENOENT) {
// probably raced with bucket removal
return 0;
}
ldpp_dout(dpp, -1) << __func__ <<
": ERROR: RGWRados::get_bucket_instance_info() returned ret=" <<
ret << dendl;
return ret;
}
RGWRados::Bucket target(store->getRados(), bucket_info);
RGWRados::Bucket::List list_op(&target);
std::string marker;
list_op.params.marker = rgw_obj_key(marker);
list_op.params.list_versions = true;
list_op.params.enforce_ns = false;
list_op.params.allow_unordered = false;
list_op.params.prefix = prefix;
bool truncated;
std::deque<RGWRados::Object::Stat> stat_ops;
std::string prev_versioned_key_name = "";
RGWObjectCtx obj_ctx(store);
do {
std::vector<rgw_bucket_dir_entry> result;
constexpr int64_t LIST_OBJS_MAX_ENTRIES = 100;
ret = list_op.list_objects(dpp, LIST_OBJS_MAX_ENTRIES, &result,
NULL, &truncated, null_yield);
if (ret == -ENOENT) {
// race with bucket delete?
ret = 0;
break;
} else if (ret < 0) {
std::cerr << "ERROR: store->list_objects(): " << cpp_strerror(-ret) <<
std::endl;
return ret;
}
for (std::vector<rgw_bucket_dir_entry>::iterator iter = result.begin();
iter != result.end();
++iter) {
rgw_bucket_dir_entry& entry = *iter;
if (entry.key.instance.empty()) {
ldpp_dout(dpp, 20) << "obj entry: " << entry.key.name << dendl;
} else {
ldpp_dout(dpp, 20) << "obj entry: " << entry.key.name <<
" [" << entry.key.instance << "]" << dendl;
}
ldpp_dout(dpp, 20) << __func__ << ": entry.key.name=" <<
entry.key.name << " entry.key.instance=" << entry.key.instance <<
dendl;
// ignore entries that are not in the filter if there is a filter
if (!entries_filter.empty() &&
entries_filter.find(entry.key) == entries_filter.cend()) {
continue;
}
std::unique_ptr<rgw::sal::Bucket> bucket;
store->get_bucket(nullptr, bucket_info, &bucket);
// we need to do this in two cases below, so use a lambda
auto do_stat_key =
[&](const rgw_obj_key& key) -> int {
int ret;
rgw_obj obj(bucket_info.bucket, key);
RGWRados::Object op_target(store->getRados(), bucket_info,
obj_ctx, obj);
stat_ops.push_back(RGWRados::Object::Stat(&op_target));
RGWRados::Object::Stat& op = stat_ops.back();
ret = op.stat_async(dpp);
if (ret < 0) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " <<
cpp_strerror(-ret) << dendl;
return ret;
}
if (stat_ops.size() >= max_concurrent_ios) {
ret = pop_and_handle_stat_op(dpp, obj_ctx, stat_ops);
if (ret < 0) {
if (ret != -ENOENT) {
ldpp_dout(dpp, -1) <<
"ERROR: pop_and_handle_stat_op() returned error: " <<
cpp_strerror(-ret) << dendl;
}
// clear error, so we'll continue processing directory
ret = 0;
}
}
return ret;
}; // do_stat_key lambda
// for versioned objects, make sure the head object is handled
// as well by ignoring the instance identifier
if (!entry.key.instance.empty() &&
entry.key.name != prev_versioned_key_name) {
// don't do the same key twice; even though out bucket index
// listing allows unordered, since all versions of an object
// use the same bucket index key, they'll all end up together
// and sorted
prev_versioned_key_name = entry.key.name;
rgw_obj_key uninstanced(entry.key.name);
ret = do_stat_key(uninstanced);
if (ret < 0) {
return ret;
}
}
ret = do_stat_key(entry.key);
if (ret < 0) {
return ret;
}
} // for iter loop
} while (truncated);
while (!stat_ops.empty()) {
ret = pop_and_handle_stat_op(dpp, obj_ctx, stat_ops);
if (ret < 0) {
if (ret != -ENOENT) {
ldpp_dout(dpp, -1) << "ERROR: stat_async() returned error: " <<
cpp_strerror(-ret) << dendl;
}
}
}
return 0;
}
int RGWRadosList::run(const DoutPrefixProvider *dpp,
const bool yes_i_really_mean_it)
{
int ret;
void* handle = nullptr;
ret = store->meta_list_keys_init(dpp, "bucket", string(), &handle);
if (ret < 0) {
ldpp_dout(dpp, -1) << "RGWRadosList::" << __func__ <<
" ERROR: list_keys_init returned " <<
cpp_strerror(-ret) << dendl;
return ret;
}
constexpr int max_keys = 1000;
bool truncated = true;
bool warned_indexless = false;
do {
std::list<std::string> buckets;
ret = store->meta_list_keys_next(dpp, handle, max_keys, buckets, &truncated);
for (std::string& bucket_id : buckets) {
ret = run(dpp, bucket_id, true);
if (ret == -ENOENT) {
continue;
} else if (ret == -EINVAL) {
if (! warned_indexless) {
if (yes_i_really_mean_it) {
std::cerr <<
"WARNING: because there is at least one indexless bucket (" <<
bucket_id <<
") the results of radoslist are *incomplete*; continuing due to --yes-i-really-mean-it" <<
std::endl;
warned_indexless = true;
} else {
std::cerr << "ERROR: because there is at least one indexless bucket (" <<
bucket_id <<
") the results of radoslist are *incomplete*; use --yes-i-really-mean-it to bypass error" <<
std::endl;
return ret;
}
}
continue;
} else if (ret < 0) {
return ret;
}
}
} while (truncated);
return 0;
} // RGWRadosList::run(DoutPrefixProvider, bool)
int RGWRadosList::run(const DoutPrefixProvider *dpp,
const std::string& start_bucket_name,
const bool silent_indexless)
{
int ret;
add_bucket_entire(start_bucket_name);
while (! bucket_process_map.empty()) {
// pop item from map and capture its key data
auto front = bucket_process_map.begin();
std::string bucket_name = front->first;
process_t process;
std::swap(process, front->second);
bucket_process_map.erase(front);
std::unique_ptr<rgw::sal::Bucket> bucket;
ret = store->get_bucket(dpp, nullptr, tenant_name, bucket_name, &bucket, null_yield);
if (ret == -ENOENT) {
std::cerr << "WARNING: bucket " << bucket_name <<
" does not exist; could it have been deleted very recently?" <<
std::endl;
continue;
} else if (ret < 0) {
std::cerr << "ERROR: could not get info for bucket " << bucket_name <<
" -- " << cpp_strerror(-ret) << std::endl;
return ret;
} else if (bucket->get_info().is_indexless()) {
if (! silent_indexless) {
std::cerr << "ERROR: unable to run radoslist on indexless bucket " <<
bucket_name << std::endl;
}
return -EINVAL;
}
const std::string bucket_id = bucket->get_key().get_key();
static const std::set<rgw_obj_key> empty_filter;
static const std::string empty_prefix;
auto do_process_bucket =
[dpp, &bucket_id, this]
(const std::string& prefix,
const std::set<rgw_obj_key>& entries_filter) -> int {
int ret = process_bucket(dpp, bucket_id, prefix, entries_filter);
if (ret == -ENOENT) {
// bucket deletion race?
return 0;
} if (ret < 0) {
ldpp_dout(dpp, -1) << "RGWRadosList::" << __func__ <<
": ERROR: process_bucket(); bucket_id=" <<
bucket_id << " returned ret=" << ret << dendl;
}
return ret;
};
// either process the whole bucket *or* process the filters and/or
// the prefixes
if (process.entire_container) {
ret = do_process_bucket(empty_prefix, empty_filter);
if (ret < 0) {
return ret;
}
} else {
if (! process.filter_keys.empty()) {
ret = do_process_bucket(empty_prefix, process.filter_keys);
if (ret < 0) {
return ret;
}
}
for (const auto& p : process.prefixes) {
ret = do_process_bucket(p, empty_filter);
if (ret < 0) {
return ret;
}
}
}
} // while (! bucket_process_map.empty())
if (include_rgw_obj_name) {
return 0;
}
// now handle incomplete multipart uploads by going back to the
// initial bucket
std::unique_ptr<rgw::sal::Bucket> bucket;
ret = store->get_bucket(dpp, nullptr, tenant_name, start_bucket_name, &bucket, null_yield);
if (ret == -ENOENT) {
// bucket deletion race?
return 0;
} else if (ret < 0) {
ldpp_dout(dpp, -1) << "RGWRadosList::" << __func__ <<
": ERROR: get_bucket_info returned ret=" << ret << dendl;
return ret;
}
ret = do_incomplete_multipart(dpp, bucket.get());
if (ret < 0) {
ldpp_dout(dpp, -1) << "RGWRadosList::" << __func__ <<
": ERROR: do_incomplete_multipart returned ret=" << ret << dendl;
return ret;
}
return 0;
} // RGWRadosList::run(DoutPrefixProvider, string, bool)
int RGWRadosList::do_incomplete_multipart(const DoutPrefixProvider *dpp,
rgw::sal::Bucket* bucket)
{
constexpr int max_uploads = 1000;
constexpr int max_parts = 1000;
std::string marker;
vector<std::unique_ptr<rgw::sal::MultipartUpload>> uploads;
bool is_truncated;
int ret;
// use empty strings for params.{prefix,delim}
do {
ret = bucket->list_multiparts(dpp, string(), marker, string(), max_uploads, uploads, nullptr, &is_truncated, null_yield);
if (ret == -ENOENT) {
// could bucket have been removed while this is running?
ldpp_dout(dpp, 5) << "RGWRadosList::" << __func__ <<
": WARNING: call to list_objects of multipart namespace got ENOENT; "
"assuming bucket removal race" << dendl;
break;
} else if (ret < 0) {
ldpp_dout(dpp, -1) << "RGWRadosList::" << __func__ <<
": ERROR: list_objects op returned ret=" << ret << dendl;
return ret;
}
if (!uploads.empty()) {
// now process the uploads vector
for (const auto& upload : uploads) {
int parts_marker = 0;
bool is_parts_truncated = false;
do { // while (is_parts_truncated);
ret = upload->list_parts(dpp, store->ctx(), max_parts, parts_marker,
&parts_marker, &is_parts_truncated, null_yield);
if (ret == -ENOENT) {
ldpp_dout(dpp, 5) << "RGWRadosList::" << __func__ <<
": WARNING: list_multipart_parts returned ret=-ENOENT "
"for " << upload->get_upload_id() << ", moving on" << dendl;
break;
} else if (ret < 0) {
ldpp_dout(dpp, -1) << "RGWRadosList::" << __func__ <<
": ERROR: list_multipart_parts returned ret=" << ret <<
dendl;
return ret;
}
for (auto& p : upload->get_parts()) {
rgw::sal::RadosMultipartPart* part =
dynamic_cast<rgw::sal::RadosMultipartPart*>(p.second.get());
RGWObjManifest& manifest = part->get_manifest();
for (auto obj_it = manifest.obj_begin(dpp);
obj_it != manifest.obj_end(dpp);
++obj_it) {
const rgw_raw_obj& loc =
obj_it.get_location().get_raw_obj(store->getRados());
std::cout << loc.oid << std::endl;
} // for (auto obj_it
} // for (auto& p
} while (is_parts_truncated);
} // for (const auto& upload
} // if objs not empty
} while (is_truncated);
return 0;
} // RGWRadosList::do_incomplete_multipart
void RGWOrphanSearchStage::dump(Formatter *f) const
{
f->open_object_section("orphan_search_stage");
string s;
switch(stage){
case ORPHAN_SEARCH_STAGE_INIT:
s = "init";
break;
case ORPHAN_SEARCH_STAGE_LSPOOL:
s = "lspool";
break;
case ORPHAN_SEARCH_STAGE_LSBUCKETS:
s = "lsbuckets";
break;
case ORPHAN_SEARCH_STAGE_ITERATE_BI:
s = "iterate_bucket_index";
break;
case ORPHAN_SEARCH_STAGE_COMPARE:
s = "comparing";
break;
default:
s = "unknown";
}
f->dump_string("search_stage", s);
f->dump_int("shard",shard);
f->dump_string("marker",marker);
f->close_section();
}
void RGWOrphanSearchInfo::dump(Formatter *f) const
{
f->open_object_section("orphan_search_info");
f->dump_string("job_name", job_name);
encode_json("pool", pool, f);
f->dump_int("num_shards", num_shards);
encode_json("start_time", start_time, f);
f->close_section();
}
void RGWOrphanSearchState::dump(Formatter *f) const
{
f->open_object_section("orphan_search_state");
encode_json("info", info, f);
encode_json("stage", stage, f);
f->close_section();
}
| 46,918 | 28.342714 | 146 |
cc
|
null |
ceph-main/src/rgw/rgw_orphan.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) 2015 Red Hat
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "common/config.h"
#include "common/Formatter.h"
#include "common/errno.h"
#include "rgw_sal_rados.h"
#define RGW_ORPHAN_INDEX_OID "orphan.index"
#define RGW_ORPHAN_INDEX_PREFIX "orphan.scan"
enum RGWOrphanSearchStageId {
ORPHAN_SEARCH_STAGE_UNKNOWN = 0,
ORPHAN_SEARCH_STAGE_INIT = 1,
ORPHAN_SEARCH_STAGE_LSPOOL = 2,
ORPHAN_SEARCH_STAGE_LSBUCKETS = 3,
ORPHAN_SEARCH_STAGE_ITERATE_BI = 4,
ORPHAN_SEARCH_STAGE_COMPARE = 5,
};
struct RGWOrphanSearchStage {
RGWOrphanSearchStageId stage;
int shard;
std::string marker;
RGWOrphanSearchStage() : stage(ORPHAN_SEARCH_STAGE_UNKNOWN), shard(0) {}
explicit RGWOrphanSearchStage(RGWOrphanSearchStageId _stage) : stage(_stage), shard(0) {}
RGWOrphanSearchStage(RGWOrphanSearchStageId _stage, int _shard, const std::string& _marker) : stage(_stage), shard(_shard), marker(_marker) {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode((int)stage, bl);
encode(shard, bl);
encode(marker, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
int s;
decode(s, bl);
stage = (RGWOrphanSearchStageId)s;
decode(shard, bl);
decode(marker, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(RGWOrphanSearchStage)
struct RGWOrphanSearchInfo {
std::string job_name;
rgw_pool pool;
uint16_t num_shards;
utime_t start_time;
void encode(bufferlist& bl) const {
ENCODE_START(2, 1, bl);
encode(job_name, bl);
encode(pool.to_str(), bl);
encode(num_shards, bl);
encode(start_time, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(job_name, bl);
std::string s;
decode(s, bl);
pool.from_str(s);
decode(num_shards, bl);
decode(start_time, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(RGWOrphanSearchInfo)
struct RGWOrphanSearchState {
RGWOrphanSearchInfo info;
RGWOrphanSearchStage stage;
RGWOrphanSearchState() : stage(ORPHAN_SEARCH_STAGE_UNKNOWN) {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(info, bl);
encode(stage, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(info, bl);
decode(stage, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(RGWOrphanSearchState)
class RGWOrphanStore {
rgw::sal::RadosStore* store;
librados::IoCtx ioctx;
std::string oid;
public:
explicit RGWOrphanStore(rgw::sal::RadosStore* _store) : store(_store), oid(RGW_ORPHAN_INDEX_OID) {}
librados::IoCtx& get_ioctx() { return ioctx; }
int init(const DoutPrefixProvider *dpp);
int read_job(const std::string& job_name, RGWOrphanSearchState& state);
int write_job(const std::string& job_name, const RGWOrphanSearchState& state);
int remove_job(const std::string& job_name);
int list_jobs(std::map<std::string,RGWOrphanSearchState> &job_list);
int store_entries(const DoutPrefixProvider *dpp, const std::string& oid, const std::map<std::string, bufferlist>& entries);
int read_entries(const std::string& oid, const std::string& marker, std::map<std::string, bufferlist> *entries, bool *truncated);
};
class RGWOrphanSearch {
rgw::sal::RadosStore* store;
RGWOrphanStore orphan_store;
RGWOrphanSearchInfo search_info;
RGWOrphanSearchStage search_stage;
std::map<int, std::string> all_objs_index;
std::map<int, std::string> buckets_instance_index;
std::map<int, std::string> linked_objs_index;
std::string index_objs_prefix;
uint16_t max_concurrent_ios;
uint64_t stale_secs;
int64_t max_list_bucket_entries;
bool detailed_mode;
struct log_iter_info {
std::string oid;
std::list<std::string>::iterator cur;
std::list<std::string>::iterator end;
};
int log_oids(const DoutPrefixProvider *dpp, std::map<int, std::string>& log_shards, std::map<int, std::list<std::string> >& oids);
#define RGW_ORPHANSEARCH_HASH_PRIME 7877
int orphan_shard(const std::string& str) {
return ceph_str_hash_linux(str.c_str(), str.size()) % RGW_ORPHANSEARCH_HASH_PRIME % search_info.num_shards;
}
int handle_stat_result(const DoutPrefixProvider *dpp, std::map<int, std::list<std::string> >& oids, RGWRados::Object::Stat::Result& result);
int pop_and_handle_stat_op(const DoutPrefixProvider *dpp, std::map<int, std::list<std::string> >& oids, std::deque<RGWRados::Object::Stat>& ops);
int remove_index(std::map<int, std::string>& index);
public:
RGWOrphanSearch(rgw::sal::RadosStore* _store, int _max_ios, uint64_t _stale_secs) : store(_store), orphan_store(store), max_concurrent_ios(_max_ios), stale_secs(_stale_secs) {}
int save_state() {
RGWOrphanSearchState state;
state.info = search_info;
state.stage = search_stage;
return orphan_store.write_job(search_info.job_name, state);
}
int init(const DoutPrefixProvider *dpp, const std::string& job_name, RGWOrphanSearchInfo *info, bool _detailed_mode=false);
int create(const std::string& job_name, int num_shards);
int build_all_oids_index(const DoutPrefixProvider *dpp);
int build_buckets_instance_index(const DoutPrefixProvider *dpp);
int build_linked_oids_for_bucket(const DoutPrefixProvider *dpp, const std::string& bucket_instance_id, std::map<int, std::list<std::string> >& oids);
int build_linked_oids_index(const DoutPrefixProvider *dpp);
int compare_oid_indexes(const DoutPrefixProvider *dpp);
int run(const DoutPrefixProvider *dpp);
int finish();
};
class RGWRadosList {
/*
* process_t describes how to process a irectory, we will either
* process the whole thing (entire_container == true) or a portion
* of it (entire_container == false). When we only process a
* portion, we will list the specific keys and/or specific lexical
* prefixes.
*/
struct process_t {
bool entire_container;
std::set<rgw_obj_key> filter_keys;
std::set<std::string> prefixes;
process_t() :
entire_container(false)
{}
};
std::map<std::string,process_t> bucket_process_map;
std::set<std::string> visited_oids;
void add_bucket_entire(const std::string& bucket_name) {
auto p = bucket_process_map.emplace(std::make_pair(bucket_name,
process_t()));
p.first->second.entire_container = true;
}
void add_bucket_prefix(const std::string& bucket_name,
const std::string& prefix) {
auto p = bucket_process_map.emplace(std::make_pair(bucket_name,
process_t()));
p.first->second.prefixes.insert(prefix);
}
void add_bucket_filter(const std::string& bucket_name,
const rgw_obj_key& obj_key) {
auto p = bucket_process_map.emplace(std::make_pair(bucket_name,
process_t()));
p.first->second.filter_keys.insert(obj_key);
}
rgw::sal::RadosStore* store;
uint16_t max_concurrent_ios;
uint64_t stale_secs;
std::string tenant_name;
bool include_rgw_obj_name;
std::string field_separator;
int handle_stat_result(const DoutPrefixProvider *dpp,
RGWRados::Object::Stat::Result& result,
std::string& bucket_name,
rgw_obj_key& obj_key,
std::set<std::string>& obj_oids);
int pop_and_handle_stat_op(const DoutPrefixProvider *dpp,
RGWObjectCtx& obj_ctx,
std::deque<RGWRados::Object::Stat>& ops);
public:
RGWRadosList(rgw::sal::RadosStore* _store,
int _max_ios,
uint64_t _stale_secs,
const std::string& _tenant_name) :
store(_store),
max_concurrent_ios(_max_ios),
stale_secs(_stale_secs),
tenant_name(_tenant_name),
include_rgw_obj_name(false)
{}
int process_bucket(const DoutPrefixProvider *dpp,
const std::string& bucket_instance_id,
const std::string& prefix,
const std::set<rgw_obj_key>& entries_filter);
int do_incomplete_multipart(const DoutPrefixProvider *dpp,
rgw::sal::Bucket* bucket);
int build_linked_oids_index();
int run(const DoutPrefixProvider *dpp,
const std::string& bucket_id,
const bool silent_indexless = false);
int run(const DoutPrefixProvider *dpp,
const bool yes_i_really_mean_it = false);
// if there's a non-empty field separator, that means we'll display
// bucket and object names
void set_field_separator(const std::string& fs) {
field_separator = fs;
include_rgw_obj_name = !field_separator.empty();
}
}; // class RGWRadosList
| 8,950 | 28.347541 | 178 |
h
|
null |
ceph-main/src/rgw/rgw_os_lib.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_rest.h"
#include "rgw_rest_s3.h"
#include "rgw_rest_user.h"
#include "rgw_os_lib.h"
#include "rgw_file.h"
#include "rgw_lib_frontend.h"
namespace rgw {
/* static */
int RGWHandler_Lib::init_from_header(rgw::sal::Driver* driver,
req_state *s)
{
string req;
string first;
const char *req_name = s->relative_uri.c_str();
const char *p;
/* skip request_params parsing, rgw_file should not be
* seeing any */
if (*req_name == '?') {
p = req_name;
} else {
p = s->info.request_params.c_str();
}
s->info.args.set(p);
s->info.args.parse(s);
if (*req_name != '/')
return 0;
req_name++;
if (!*req_name)
return 0;
req = req_name;
int pos = req.find('/');
if (pos >= 0) {
first = req.substr(0, pos);
} else {
first = req;
}
if (s->bucket_name.empty()) {
s->bucket_name = std::move(first);
if (pos >= 0) {
// XXX ugh, another copy
string encoded_obj_str = req.substr(pos+1);
s->object = driver->get_object(rgw_obj_key(encoded_obj_str, s->info.args.get("versionId")));
}
} else {
s->object = driver->get_object(rgw_obj_key(req_name, s->info.args.get("versionId")));
}
return 0;
} /* init_from_header */
} /* namespace rgw */
| 1,415 | 21.125 | 93 |
cc
|
null |
ceph-main/src/rgw/rgw_os_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 <functional>
#include "rgw_common.h"
#include "rgw_lib.h"
| 188 | 17.9 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_perf_counters.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_perf_counters.h"
#include "common/perf_counters.h"
#include "common/ceph_context.h"
PerfCounters *perfcounter = NULL;
int rgw_perf_start(CephContext *cct)
{
PerfCountersBuilder plb(cct, "rgw", l_rgw_first, l_rgw_last);
// RGW emits comparatively few metrics, so let's be generous
// and mark them all USEFUL to get transmission to ceph-mgr by default.
plb.set_prio_default(PerfCountersBuilder::PRIO_USEFUL);
plb.add_u64_counter(l_rgw_req, "req", "Requests");
plb.add_u64_counter(l_rgw_failed_req, "failed_req", "Aborted requests");
plb.add_u64_counter(l_rgw_get, "get", "Gets");
plb.add_u64_counter(l_rgw_get_b, "get_b", "Size of gets");
plb.add_time_avg(l_rgw_get_lat, "get_initial_lat", "Get latency");
plb.add_u64_counter(l_rgw_put, "put", "Puts");
plb.add_u64_counter(l_rgw_put_b, "put_b", "Size of puts");
plb.add_time_avg(l_rgw_put_lat, "put_initial_lat", "Put latency");
plb.add_u64(l_rgw_qlen, "qlen", "Queue length");
plb.add_u64(l_rgw_qactive, "qactive", "Active requests queue");
plb.add_u64_counter(l_rgw_cache_hit, "cache_hit", "Cache hits");
plb.add_u64_counter(l_rgw_cache_miss, "cache_miss", "Cache miss");
plb.add_u64_counter(l_rgw_keystone_token_cache_hit, "keystone_token_cache_hit", "Keystone token cache hits");
plb.add_u64_counter(l_rgw_keystone_token_cache_miss, "keystone_token_cache_miss", "Keystone token cache miss");
plb.add_u64_counter(l_rgw_gc_retire, "gc_retire_object", "GC object retires");
plb.add_u64_counter(l_rgw_lc_expire_current, "lc_expire_current",
"Lifecycle current expiration");
plb.add_u64_counter(l_rgw_lc_expire_noncurrent, "lc_expire_noncurrent",
"Lifecycle non-current expiration");
plb.add_u64_counter(l_rgw_lc_expire_dm, "lc_expire_dm",
"Lifecycle delete-marker expiration");
plb.add_u64_counter(l_rgw_lc_transition_current, "lc_transition_current",
"Lifecycle current transition");
plb.add_u64_counter(l_rgw_lc_transition_noncurrent,
"lc_transition_noncurrent",
"Lifecycle non-current transition");
plb.add_u64_counter(l_rgw_lc_abort_mpu, "lc_abort_mpu",
"Lifecycle abort multipart upload");
plb.add_u64_counter(l_rgw_pubsub_event_triggered, "pubsub_event_triggered", "Pubsub events with at least one topic");
plb.add_u64_counter(l_rgw_pubsub_event_lost, "pubsub_event_lost", "Pubsub events lost");
plb.add_u64_counter(l_rgw_pubsub_store_ok, "pubsub_store_ok", "Pubsub events successfully stored");
plb.add_u64_counter(l_rgw_pubsub_store_fail, "pubsub_store_fail", "Pubsub events failed to be stored");
plb.add_u64(l_rgw_pubsub_events, "pubsub_events", "Pubsub events in store");
plb.add_u64_counter(l_rgw_pubsub_push_ok, "pubsub_push_ok", "Pubsub events pushed to an endpoint");
plb.add_u64_counter(l_rgw_pubsub_push_failed, "pubsub_push_failed", "Pubsub events failed to be pushed to an endpoint");
plb.add_u64(l_rgw_pubsub_push_pending, "pubsub_push_pending", "Pubsub events pending reply from endpoint");
plb.add_u64_counter(l_rgw_pubsub_missing_conf, "pubsub_missing_conf", "Pubsub events could not be handled because of missing configuration");
plb.add_u64_counter(l_rgw_lua_script_ok, "lua_script_ok", "Successfull executions of lua scripts");
plb.add_u64_counter(l_rgw_lua_script_fail, "lua_script_fail", "Failed executions of lua scripts");
plb.add_u64(l_rgw_lua_current_vms, "lua_current_vms", "Number of Lua VMs currently being executed");
perfcounter = plb.create_perf_counters();
cct->get_perfcounters_collection()->add(perfcounter);
return 0;
}
void rgw_perf_stop(CephContext *cct)
{
ceph_assert(perfcounter);
cct->get_perfcounters_collection()->remove(perfcounter);
delete perfcounter;
}
| 3,837 | 47.582278 | 143 |
cc
|
null |
ceph-main/src/rgw/rgw_perf_counters.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/common_fwd.h"
extern PerfCounters *perfcounter;
extern int rgw_perf_start(CephContext *cct);
extern void rgw_perf_stop(CephContext *cct);
enum {
l_rgw_first = 15000,
l_rgw_req,
l_rgw_failed_req,
l_rgw_get,
l_rgw_get_b,
l_rgw_get_lat,
l_rgw_put,
l_rgw_put_b,
l_rgw_put_lat,
l_rgw_qlen,
l_rgw_qactive,
l_rgw_cache_hit,
l_rgw_cache_miss,
l_rgw_keystone_token_cache_hit,
l_rgw_keystone_token_cache_miss,
l_rgw_gc_retire,
l_rgw_lc_expire_current,
l_rgw_lc_expire_noncurrent,
l_rgw_lc_expire_dm,
l_rgw_lc_transition_current,
l_rgw_lc_transition_noncurrent,
l_rgw_lc_abort_mpu,
l_rgw_pubsub_event_triggered,
l_rgw_pubsub_event_lost,
l_rgw_pubsub_store_ok,
l_rgw_pubsub_store_fail,
l_rgw_pubsub_events,
l_rgw_pubsub_push_ok,
l_rgw_pubsub_push_failed,
l_rgw_pubsub_push_pending,
l_rgw_pubsub_missing_conf,
l_rgw_lua_current_vms,
l_rgw_lua_script_ok,
l_rgw_lua_script_fail,
l_rgw_last,
};
| 1,101 | 17.065574 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_period.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_sync.h"
using namespace std;
using namespace rgw_zone_defaults;
std::string period_latest_epoch_info_oid = ".latest_epoch";
std::string period_info_oid_prefix = "periods.";
#define FIRST_EPOCH 1
int RGWPeriod::init(const DoutPrefixProvider *dpp,
CephContext *_cct, RGWSI_SysObj *_sysobj_svc,
optional_yield y, bool setup_obj)
{
cct = _cct;
sysobj_svc = _sysobj_svc;
if (!setup_obj)
return 0;
if (id.empty()) {
RGWRealm realm(realm_id, realm_name);
int ret = realm.init(dpp, cct, sysobj_svc, y);
if (ret < 0) {
ldpp_dout(dpp, 4) << "RGWPeriod::init failed to init realm " << realm_name << " id " << realm_id << " : " <<
cpp_strerror(-ret) << dendl;
return ret;
}
id = realm.get_current_period();
realm_id = realm.get_id();
}
if (!epoch) {
int ret = use_latest_epoch(dpp, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "failed to use_latest_epoch period id " << id << " realm " << realm_name << " id " << realm_id
<< " : " << cpp_strerror(-ret) << dendl;
return ret;
}
}
return read_info(dpp, y);
}
int RGWPeriod::init(const DoutPrefixProvider *dpp, CephContext *_cct, RGWSI_SysObj *_sysobj_svc,
const string& period_realm_id, optional_yield y,
const string& period_realm_name, bool setup_obj)
{
cct = _cct;
sysobj_svc = _sysobj_svc;
realm_id = period_realm_id;
realm_name = period_realm_name;
if (!setup_obj)
return 0;
return init(dpp, _cct, _sysobj_svc, y, setup_obj);
}
const string& RGWPeriod::get_latest_epoch_oid() const
{
if (cct->_conf->rgw_period_latest_epoch_info_oid.empty()) {
return period_latest_epoch_info_oid;
}
return cct->_conf->rgw_period_latest_epoch_info_oid;
}
const string& RGWPeriod::get_info_oid_prefix() const
{
return period_info_oid_prefix;
}
const string RGWPeriod::get_period_oid_prefix() const
{
return get_info_oid_prefix() + id;
}
const string RGWPeriod::get_period_oid() const
{
std::ostringstream oss;
oss << get_period_oid_prefix();
// skip the epoch for the staging period
if (id != get_staging_id(realm_id))
oss << "." << epoch;
return oss.str();
}
bool RGWPeriod::find_zone(const DoutPrefixProvider *dpp,
const rgw_zone_id& zid,
RGWZoneGroup *pzonegroup,
optional_yield y) const
{
RGWZoneGroup zg;
RGWZone zone;
bool found = period_map.find_zone_by_id(zid, &zg, &zone);
if (found) {
*pzonegroup = zg;
}
return found;
}
rgw_pool RGWPeriod::get_pool(CephContext *cct) const
{
if (cct->_conf->rgw_period_root_pool.empty()) {
return rgw_pool(RGW_DEFAULT_PERIOD_ROOT_POOL);
}
return rgw_pool(cct->_conf->rgw_period_root_pool);
}
int RGWPeriod::set_latest_epoch(const DoutPrefixProvider *dpp,
optional_yield y,
epoch_t epoch, bool exclusive,
RGWObjVersionTracker *objv)
{
string oid = get_period_oid_prefix() + get_latest_epoch_oid();
rgw_pool pool(get_pool(cct));
bufferlist bl;
RGWPeriodLatestEpochInfo info;
info.epoch = epoch;
using ceph::encode;
encode(info, bl);
auto sysobj = sysobj_svc->get_obj(rgw_raw_obj(pool, oid));
return sysobj.wop()
.set_exclusive(exclusive)
.write(dpp, bl, y);
}
int RGWPeriod::read_info(const DoutPrefixProvider *dpp, optional_yield y)
{
rgw_pool pool(get_pool(cct));
bufferlist bl;
auto sysobj = sysobj_svc->get_obj(rgw_raw_obj{pool, get_period_oid()});
int ret = sysobj.rop().read(dpp, &bl, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "failed reading obj info from " << pool << ":" << get_period_oid() << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
try {
using ceph::decode;
auto iter = bl.cbegin();
decode(*this, iter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: failed to decode obj from " << pool << ":" << get_period_oid() << dendl;
return -EIO;
}
return 0;
}
int RGWPeriod::store_info(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y)
{
rgw_pool pool(get_pool(cct));
string oid = get_period_oid();
bufferlist bl;
using ceph::encode;
encode(*this, bl);
auto sysobj = sysobj_svc->get_obj(rgw_raw_obj(pool, oid));
return sysobj.wop()
.set_exclusive(exclusive)
.write(dpp, bl, y);
}
int RGWPeriod::create(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive)
{
int ret;
/* create unique id */
uuid_d new_uuid;
char uuid_str[37];
new_uuid.generate_random();
new_uuid.print(uuid_str);
id = uuid_str;
epoch = FIRST_EPOCH;
period_map.id = id;
ret = store_info(dpp, exclusive, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: storing info for " << id << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
ret = set_latest_epoch(dpp, y, epoch);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: setting latest epoch " << id << ": " << cpp_strerror(-ret) << dendl;
}
return ret;
}
int RGWPeriod::reflect(const DoutPrefixProvider *dpp, optional_yield y)
{
for (auto& iter : period_map.zonegroups) {
RGWZoneGroup& zg = iter.second;
zg.reinit_instance(cct, sysobj_svc);
int r = zg.write(dpp, false, y);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to store zonegroup info for zonegroup=" << iter.first << ": " << cpp_strerror(-r) << dendl;
return r;
}
if (zg.is_master_zonegroup()) {
// set master as default if no default exists
r = zg.set_as_default(dpp, y, true);
if (r == 0) {
ldpp_dout(dpp, 1) << "Set the period's master zonegroup " << zg.get_id()
<< " as the default" << dendl;
}
}
}
int r = period_config.write(dpp, sysobj_svc, realm_id, y);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to store period config: "
<< cpp_strerror(-r) << dendl;
return r;
}
return 0;
}
void RGWPeriod::dump(Formatter *f) const
{
encode_json("id", id, f);
encode_json("epoch", epoch , f);
encode_json("predecessor_uuid", predecessor_uuid, f);
encode_json("sync_status", sync_status, f);
encode_json("period_map", period_map, f);
encode_json("master_zonegroup", master_zonegroup, f);
encode_json("master_zone", master_zone, f);
encode_json("period_config", period_config, f);
encode_json("realm_id", realm_id, f);
encode_json("realm_name", realm_name, f);
encode_json("realm_epoch", realm_epoch, f);
}
void RGWPeriod::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("id", id, obj);
JSONDecoder::decode_json("epoch", epoch, obj);
JSONDecoder::decode_json("predecessor_uuid", predecessor_uuid, obj);
JSONDecoder::decode_json("sync_status", sync_status, obj);
JSONDecoder::decode_json("period_map", period_map, obj);
JSONDecoder::decode_json("master_zonegroup", master_zonegroup, obj);
JSONDecoder::decode_json("master_zone", master_zone, obj);
JSONDecoder::decode_json("period_config", period_config, obj);
JSONDecoder::decode_json("realm_id", realm_id, obj);
JSONDecoder::decode_json("realm_name", realm_name, obj);
JSONDecoder::decode_json("realm_epoch", realm_epoch, obj);
}
int RGWPeriod::update_latest_epoch(const DoutPrefixProvider *dpp, epoch_t epoch, optional_yield y)
{
static constexpr int MAX_RETRIES = 20;
for (int i = 0; i < MAX_RETRIES; i++) {
RGWPeriodLatestEpochInfo info;
RGWObjVersionTracker objv;
bool exclusive = false;
// read existing epoch
int r = read_latest_epoch(dpp, info, y, &objv);
if (r == -ENOENT) {
// use an exclusive create to set the epoch atomically
exclusive = true;
ldpp_dout(dpp, 20) << "creating initial latest_epoch=" << epoch
<< " for period=" << id << dendl;
} else if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to read latest_epoch" << dendl;
return r;
} else if (epoch <= info.epoch) {
r = -EEXIST; // fail with EEXIST if epoch is not newer
ldpp_dout(dpp, 10) << "found existing latest_epoch " << info.epoch
<< " >= given epoch " << epoch << ", returning r=" << r << dendl;
return r;
} else {
ldpp_dout(dpp, 20) << "updating latest_epoch from " << info.epoch
<< " -> " << epoch << " on period=" << id << dendl;
}
r = set_latest_epoch(dpp, y, epoch, exclusive, &objv);
if (r == -EEXIST) {
continue; // exclusive create raced with another update, retry
} else if (r == -ECANCELED) {
continue; // write raced with a conflicting version, retry
}
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to write latest_epoch" << dendl;
return r;
}
return 0; // return success
}
return -ECANCELED; // fail after max retries
}
int RGWPeriod::read_latest_epoch(const DoutPrefixProvider *dpp,
RGWPeriodLatestEpochInfo& info,
optional_yield y,
RGWObjVersionTracker *objv)
{
string oid = get_period_oid_prefix() + get_latest_epoch_oid();
rgw_pool pool(get_pool(cct));
bufferlist bl;
auto sysobj = sysobj_svc->get_obj(rgw_raw_obj{pool, oid});
int ret = sysobj.rop().read(dpp, &bl, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "error read_lastest_epoch " << pool << ":" << oid << dendl;
return ret;
}
try {
auto iter = bl.cbegin();
using ceph::decode;
decode(info, iter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "error decoding data from " << pool << ":" << oid << dendl;
return -EIO;
}
return 0;
}
int RGWPeriod::use_latest_epoch(const DoutPrefixProvider *dpp, optional_yield y)
{
RGWPeriodLatestEpochInfo info;
int ret = read_latest_epoch(dpp, info, y);
if (ret < 0) {
return ret;
}
epoch = info.epoch;
return 0;
}
| 9,923 | 27.273504 | 133 |
cc
|
null |
ceph-main/src/rgw/rgw_period_history.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_period_history.h"
#include "rgw_zone.h"
#include "include/ceph_assert.h"
#define dout_subsys ceph_subsys_rgw
#undef dout_prefix
#define dout_prefix (*_dout << "rgw period history: ")
/// an ordered history of consecutive periods
class RGWPeriodHistory::History : public bi::avl_set_base_hook<> {
public:
std::deque<RGWPeriod> periods;
epoch_t get_oldest_epoch() const {
return periods.front().get_realm_epoch();
}
epoch_t get_newest_epoch() const {
return periods.back().get_realm_epoch();
}
bool contains(epoch_t epoch) const {
return get_oldest_epoch() <= epoch && epoch <= get_newest_epoch();
}
RGWPeriod& get(epoch_t epoch) {
return periods[epoch - get_oldest_epoch()];
}
const RGWPeriod& get(epoch_t epoch) const {
return periods[epoch - get_oldest_epoch()];
}
const std::string& get_predecessor_id() const {
return periods.front().get_predecessor();
}
};
/// value comparison for avl_set
bool operator<(const RGWPeriodHistory::History& lhs,
const RGWPeriodHistory::History& rhs)
{
return lhs.get_newest_epoch() < rhs.get_newest_epoch();
}
/// key-value comparison for avl_set
struct NewestEpochLess {
bool operator()(const RGWPeriodHistory::History& value, epoch_t key) const {
return value.get_newest_epoch() < key;
}
};
using Cursor = RGWPeriodHistory::Cursor;
const RGWPeriod& Cursor::get_period() const
{
std::lock_guard<std::mutex> lock(*mutex);
return history->get(epoch);
}
bool Cursor::has_prev() const
{
std::lock_guard<std::mutex> lock(*mutex);
return epoch > history->get_oldest_epoch();
}
bool Cursor::has_next() const
{
std::lock_guard<std::mutex> lock(*mutex);
return epoch < history->get_newest_epoch();
}
bool operator==(const Cursor& lhs, const Cursor& rhs)
{
return lhs.history == rhs.history && lhs.epoch == rhs.epoch;
}
bool operator!=(const Cursor& lhs, const Cursor& rhs)
{
return !(lhs == rhs);
}
class RGWPeriodHistory::Impl final {
public:
Impl(CephContext* cct, Puller* puller, const RGWPeriod& current_period);
~Impl();
Cursor get_current() const { return current_cursor; }
Cursor attach(const DoutPrefixProvider *dpp, RGWPeriod&& period, optional_yield y);
Cursor insert(RGWPeriod&& period);
Cursor lookup(epoch_t realm_epoch);
private:
/// an intrusive set of histories, ordered by their newest epoch. although
/// the newest epoch of each history is mutable, the ordering cannot change
/// because we prevent the histories from overlapping
using Set = bi::avl_set<RGWPeriodHistory::History>;
/// insert the given period into the period history, creating new unconnected
/// histories or merging existing histories as necessary. expects the caller
/// to hold a lock on mutex. returns a valid cursor regardless of whether it
/// ends up in current_history, though cursors in other histories are only
/// valid within the context of the lock
Cursor insert_locked(RGWPeriod&& period);
/// merge the periods from the src history onto the end of the dst history,
/// and return an iterator to the merged history
Set::iterator merge(Set::iterator dst, Set::iterator src);
/// construct a Cursor object using Cursor's private constuctor
Cursor make_cursor(Set::const_iterator history, epoch_t epoch);
CephContext *const cct;
Puller *const puller; //< interface for pulling missing periods
Cursor current_cursor; //< Cursor to realm's current period
mutable std::mutex mutex; //< protects the histories
/// set of disjoint histories that are missing intermediate periods needed to
/// connect them together
Set histories;
/// iterator to the history that contains the realm's current period
Set::const_iterator current_history;
};
RGWPeriodHistory::Impl::Impl(CephContext* cct, Puller* puller,
const RGWPeriod& current_period)
: cct(cct), puller(puller)
{
if (!current_period.get_id().empty()) {
// copy the current period into a new history
auto history = new History;
history->periods.push_back(current_period);
// insert as our current history
// coverity[leaked_storage:SUPPRESS]
current_history = histories.insert(*history).first;
// get a cursor to the current period
current_cursor = make_cursor(current_history, current_period.get_realm_epoch());
} else {
current_history = histories.end();
}
}
RGWPeriodHistory::Impl::~Impl()
{
// clear the histories and delete each entry
histories.clear_and_dispose(std::default_delete<History>{});
}
Cursor RGWPeriodHistory::Impl::attach(const DoutPrefixProvider *dpp, RGWPeriod&& period, optional_yield y)
{
if (current_history == histories.end()) {
return Cursor{-EINVAL};
}
const auto epoch = period.get_realm_epoch();
std::string predecessor_id;
for (;;) {
{
// hold the lock over insert, and while accessing the unsafe cursor
std::lock_guard<std::mutex> lock(mutex);
auto cursor = insert_locked(std::move(period));
if (!cursor) {
return cursor;
}
if (current_history->contains(epoch)) {
break; // the history is complete
}
// take the predecessor id of the most recent history
if (cursor.get_epoch() > current_cursor.get_epoch()) {
predecessor_id = cursor.history->get_predecessor_id();
} else {
predecessor_id = current_history->get_predecessor_id();
}
}
if (predecessor_id.empty()) {
ldpp_dout(dpp, -1) << "reached a period with an empty predecessor id" << dendl;
return Cursor{-EINVAL};
}
// pull the period outside of the lock
int r = puller->pull(dpp, predecessor_id, period, y);
if (r < 0) {
return Cursor{r};
}
}
// return a cursor to the requested period
return make_cursor(current_history, epoch);
}
Cursor RGWPeriodHistory::Impl::insert(RGWPeriod&& period)
{
if (current_history == histories.end()) {
return Cursor{-EINVAL};
}
std::lock_guard<std::mutex> lock(mutex);
auto cursor = insert_locked(std::move(period));
if (cursor.get_error()) {
return cursor;
}
// we can only provide cursors that are safe to use outside of the mutex if
// they're within the current_history, because other histories can disappear
// in a merge. see merge() for the special handling of current_history
if (cursor.history == &*current_history) {
return cursor;
}
return Cursor{};
}
Cursor RGWPeriodHistory::Impl::lookup(epoch_t realm_epoch)
{
if (current_history != histories.end() &&
current_history->contains(realm_epoch)) {
return make_cursor(current_history, realm_epoch);
}
return Cursor{};
}
Cursor RGWPeriodHistory::Impl::insert_locked(RGWPeriod&& period)
{
auto epoch = period.get_realm_epoch();
// find the first history whose newest epoch comes at or after this period
auto i = histories.lower_bound(epoch, NewestEpochLess{});
if (i == histories.end()) {
// epoch is past the end of our newest history
auto last = --Set::iterator{i}; // last = i - 1
if (epoch == last->get_newest_epoch() + 1) {
// insert at the back of the last history
last->periods.emplace_back(std::move(period));
return make_cursor(last, epoch);
}
// create a new history for this period
auto history = new History;
history->periods.emplace_back(std::move(period));
// coverity[leaked_storage:SUPPRESS]
histories.insert(last, *history);
i = Set::s_iterator_to(*history);
return make_cursor(i, epoch);
}
if (i->contains(epoch)) {
// already resident in this history
auto& existing = i->get(epoch);
// verify that the period ids match; otherwise we've forked the history
if (period.get_id() != existing.get_id()) {
lderr(cct) << "Got two different periods, " << period.get_id()
<< " and " << existing.get_id() << ", with the same realm epoch "
<< epoch << "! This indicates a fork in the period history." << dendl;
return Cursor{-EEXIST};
}
// update the existing period if we got a newer period epoch
if (period.get_epoch() > existing.get_epoch()) {
existing = std::move(period);
}
return make_cursor(i, epoch);
}
if (epoch + 1 == i->get_oldest_epoch()) {
// insert at the front of this history
i->periods.emplace_front(std::move(period));
// try to merge with the previous history
if (i != histories.begin()) {
auto prev = --Set::iterator{i};
if (epoch == prev->get_newest_epoch() + 1) {
i = merge(prev, i);
}
}
return make_cursor(i, epoch);
}
if (i != histories.begin()) {
auto prev = --Set::iterator{i};
if (epoch == prev->get_newest_epoch() + 1) {
// insert at the back of the previous history
prev->periods.emplace_back(std::move(period));
return make_cursor(prev, epoch);
}
}
// create a new history for this period
auto history = new History;
history->periods.emplace_back(std::move(period));
// coverity[leaked_storage:SUPPRESS]
histories.insert(i, *history);
i = Set::s_iterator_to(*history);
return make_cursor(i, epoch);
}
RGWPeriodHistory::Impl::Set::iterator
RGWPeriodHistory::Impl::merge(Set::iterator dst, Set::iterator src)
{
ceph_assert(dst->get_newest_epoch() + 1 == src->get_oldest_epoch());
// always merge into current_history
if (src == current_history) {
// move the periods from dst onto the front of src
src->periods.insert(src->periods.begin(),
std::make_move_iterator(dst->periods.begin()),
std::make_move_iterator(dst->periods.end()));
histories.erase_and_dispose(dst, std::default_delete<History>{});
return src;
}
// move the periods from src onto the end of dst
dst->periods.insert(dst->periods.end(),
std::make_move_iterator(src->periods.begin()),
std::make_move_iterator(src->periods.end()));
histories.erase_and_dispose(src, std::default_delete<History>{});
return dst;
}
Cursor RGWPeriodHistory::Impl::make_cursor(Set::const_iterator history,
epoch_t epoch) {
return Cursor{&*history, &mutex, epoch};
}
RGWPeriodHistory::RGWPeriodHistory(CephContext* cct, Puller* puller,
const RGWPeriod& current_period)
: impl(new Impl(cct, puller, current_period)) {}
RGWPeriodHistory::~RGWPeriodHistory() = default;
Cursor RGWPeriodHistory::get_current() const
{
return impl->get_current();
}
Cursor RGWPeriodHistory::attach(const DoutPrefixProvider *dpp, RGWPeriod&& period, optional_yield y)
{
return impl->attach(dpp, std::move(period), y);
}
Cursor RGWPeriodHistory::insert(RGWPeriod&& period)
{
return impl->insert(std::move(period));
}
Cursor RGWPeriodHistory::lookup(epoch_t realm_epoch)
{
return impl->lookup(realm_epoch);
}
| 10,999 | 29.812325 | 106 |
cc
|
null |
ceph-main/src/rgw/rgw_period_history.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 <deque>
#include <mutex>
#include <system_error>
#include <boost/intrusive/avl_set.hpp>
#include "include/ceph_assert.h"
#include "include/types.h"
#include "common/async/yield_context.h"
#include "common/dout.h"
namespace bi = boost::intrusive;
class RGWPeriod;
/**
* RGWPeriodHistory tracks the relative history of all inserted periods,
* coordinates the pulling of missing intermediate periods, and provides a
* Cursor object for traversing through the connected history.
*/
class RGWPeriodHistory final {
private:
/// an ordered history of consecutive periods
class History;
// comparisons for avl_set ordering
friend bool operator<(const History& lhs, const History& rhs);
friend struct NewestEpochLess;
class Impl;
std::unique_ptr<Impl> impl;
public:
/**
* Puller is a synchronous interface for pulling periods from the master
* zone. The abstraction exists mainly to support unit testing.
*/
class Puller {
public:
virtual ~Puller() = default;
virtual int pull(const DoutPrefixProvider *dpp, const std::string& period_id, RGWPeriod& period,
optional_yield y) = 0;
};
RGWPeriodHistory(CephContext* cct, Puller* puller,
const RGWPeriod& current_period);
~RGWPeriodHistory();
/**
* Cursor tracks a position in the period history and allows forward and
* backward traversal. Only periods that are fully connected to the
* current_period are reachable via a Cursor, because other histories are
* temporary and can be merged away. Cursors to periods in disjoint
* histories, as provided by insert() or lookup(), are therefore invalid and
* their operator bool() will return false.
*/
class Cursor final {
public:
Cursor() = default;
explicit Cursor(int error) : error(error) {}
int get_error() const { return error; }
/// return false for a default-constructed or error Cursor
operator bool() const { return history != nullptr; }
epoch_t get_epoch() const { return epoch; }
const RGWPeriod& get_period() const;
bool has_prev() const;
bool has_next() const;
void prev() { epoch--; }
void next() { epoch++; }
friend bool operator==(const Cursor& lhs, const Cursor& rhs);
friend bool operator!=(const Cursor& lhs, const Cursor& rhs);
private:
// private constructors for RGWPeriodHistory
friend class RGWPeriodHistory::Impl;
Cursor(const History* history, std::mutex* mutex, epoch_t epoch)
: history(history), mutex(mutex), epoch(epoch) {}
int error{0};
const History* history{nullptr};
std::mutex* mutex{nullptr};
epoch_t epoch{0}; //< realm epoch of cursor position
};
/// return a cursor to the current period
Cursor get_current() const;
/// build up a connected period history that covers the span between
/// current_period and the given period, reading predecessor periods or
/// fetching them from the master as necessary. returns a cursor at the
/// given period that can be used to traverse the current_history
Cursor attach(const DoutPrefixProvider *dpp, RGWPeriod&& period, optional_yield y);
/// insert the given period into an existing history, or create a new
/// unconnected history. similar to attach(), but it doesn't try to fetch
/// missing periods. returns a cursor to the inserted period iff it's in
/// the current_history
Cursor insert(RGWPeriod&& period);
/// search for a period by realm epoch, returning a valid Cursor iff it's in
/// the current_history
Cursor lookup(epoch_t realm_epoch);
};
| 3,694 | 31.130435 | 100 |
h
|
null |
ceph-main/src/rgw/rgw_period_puller.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_rados.h"
#include "rgw_zone.h"
#include "rgw_rest_conn.h"
#include "common/ceph_json.h"
#include "common/errno.h"
#include "services/svc_zone.h"
#define dout_subsys ceph_subsys_rgw
#undef dout_prefix
#define dout_prefix (*_dout << "rgw period puller: ")
RGWPeriodPuller::RGWPeriodPuller(RGWSI_Zone *zone_svc, RGWSI_SysObj *sysobj_svc)
{
cct = zone_svc->ctx();
svc.zone = zone_svc;
svc.sysobj = sysobj_svc;
}
namespace {
// pull the given period over the connection
int pull_period(const DoutPrefixProvider *dpp, RGWRESTConn* conn, const std::string& period_id,
const std::string& realm_id, RGWPeriod& period,
optional_yield y)
{
rgw_user user;
RGWEnv env;
req_info info(conn->get_ctx(), &env);
info.method = "GET";
info.request_uri = "/admin/realm/period";
auto& params = info.args.get_params();
params["realm_id"] = realm_id;
params["period_id"] = period_id;
bufferlist data;
#define MAX_REST_RESPONSE (128 * 1024)
int r = conn->forward(dpp, user, info, nullptr, MAX_REST_RESPONSE, nullptr, &data, y);
if (r < 0) {
return r;
}
JSONParser parser;
r = parser.parse(data.c_str(), data.length());
if (r < 0) {
ldpp_dout(dpp, -1) << "request failed: " << cpp_strerror(-r) << dendl;
return r;
}
try {
decode_json_obj(period, &parser);
} catch (const JSONDecoder::err& e) {
ldpp_dout(dpp, -1) << "failed to decode JSON input: "
<< e.what() << dendl;
return -EINVAL;
}
return 0;
}
} // anonymous namespace
int RGWPeriodPuller::pull(const DoutPrefixProvider *dpp, const std::string& period_id, RGWPeriod& period,
optional_yield y)
{
// try to read the period from rados
period.set_id(period_id);
period.set_epoch(0);
int r = period.init(dpp, cct, svc.sysobj, y);
if (r < 0) {
if (svc.zone->is_meta_master()) {
// can't pull if we're the master
ldpp_dout(dpp, 1) << "metadata master failed to read period "
<< period_id << " from local storage: " << cpp_strerror(r) << dendl;
return r;
}
ldpp_dout(dpp, 14) << "pulling period " << period_id
<< " from master" << dendl;
// request the period from the master zone
r = pull_period(dpp, svc.zone->get_master_conn(), period_id,
svc.zone->get_realm().get_id(), period, y);
if (r < 0) {
ldpp_dout(dpp, -1) << "failed to pull period " << period_id << dendl;
return r;
}
// write the period to rados
r = period.store_info(dpp, true, y);
if (r == -EEXIST) {
r = 0;
} else if (r < 0) {
ldpp_dout(dpp, -1) << "failed to store period " << period_id << dendl;
return r;
}
// update latest epoch
r = period.update_latest_epoch(dpp, period.get_epoch(), y);
if (r == -EEXIST) {
// already have this epoch (or a more recent one)
return 0;
}
if (r < 0) {
ldpp_dout(dpp, -1) << "failed to update latest_epoch for period "
<< period_id << dendl;
return r;
}
// reflect period objects if this is the latest version
if (svc.zone->get_realm().get_current_period() == period_id) {
r = period.reflect(dpp, y);
if (r < 0) {
return r;
}
}
ldpp_dout(dpp, 14) << "period " << period_id
<< " pulled and written to local storage" << dendl;
} else {
ldpp_dout(dpp, 14) << "found period " << period_id
<< " in local storage" << dendl;
}
return 0;
}
| 3,559 | 27.709677 | 105 |
cc
|
null |
ceph-main/src/rgw/rgw_period_puller.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_period_history.h"
#include "include/common_fwd.h"
#include "rgw/services/svc_sys_obj.h"
class RGWPeriod;
class RGWPeriodPuller : public RGWPeriodHistory::Puller {
CephContext *cct;
struct {
RGWSI_Zone *zone;
RGWSI_SysObj *sysobj;
} svc;
public:
explicit RGWPeriodPuller(RGWSI_Zone *zone_svc, RGWSI_SysObj *sysobj_svc);
int pull(const DoutPrefixProvider *dpp, const std::string& period_id, RGWPeriod& period, optional_yield y) override;
};
| 597 | 22.92 | 118 |
h
|
null |
ceph-main/src/rgw/rgw_period_pusher.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <map>
#include <thread>
#include "rgw_period_pusher.h"
#include "rgw_cr_rest.h"
#include "rgw_zone.h"
#include "rgw_sal.h"
#include "rgw_sal_rados.h"
#include "services/svc_zone.h"
#include "common/errno.h"
#include <boost/asio/yield.hpp>
#define dout_subsys ceph_subsys_rgw
#undef dout_prefix
#define dout_prefix (*_dout << "rgw period pusher: ")
/// A coroutine to post the period over the given connection.
using PushCR = RGWPostRESTResourceCR<RGWPeriod, int>;
/// A coroutine that calls PushCR, and retries with backoff until success.
class PushAndRetryCR : public RGWCoroutine {
const std::string& zone;
RGWRESTConn *const conn;
RGWHTTPManager *const http;
RGWPeriod& period;
const std::string epoch; //< epoch string for params
double timeout; //< current interval between retries
const double timeout_max; //< maximum interval between retries
uint32_t counter; //< number of failures since backoff increased
public:
PushAndRetryCR(CephContext* cct, const std::string& zone, RGWRESTConn* conn,
RGWHTTPManager* http, RGWPeriod& period)
: RGWCoroutine(cct), zone(zone), conn(conn), http(http), period(period),
epoch(std::to_string(period.get_epoch())),
timeout(cct->_conf->rgw_period_push_interval),
timeout_max(cct->_conf->rgw_period_push_interval_max),
counter(0)
{}
int operate(const DoutPrefixProvider *dpp) override;
};
int PushAndRetryCR::operate(const DoutPrefixProvider *dpp)
{
reenter(this) {
for (;;) {
yield {
ldpp_dout(dpp, 10) << "pushing period " << period.get_id()
<< " to " << zone << dendl;
// initialize the http params
rgw_http_param_pair params[] = {
{ "period", period.get_id().c_str() },
{ "epoch", epoch.c_str() },
{ nullptr, nullptr }
};
call(new PushCR(cct, conn, http, "/admin/realm/period",
params, period, nullptr));
}
// stop on success
if (get_ret_status() == 0) {
ldpp_dout(dpp, 10) << "push to " << zone << " succeeded" << dendl;
return set_cr_done();
}
// try each endpoint in the connection before waiting
if (++counter < conn->get_endpoint_count())
continue;
counter = 0;
// wait with exponential backoff up to timeout_max
yield {
utime_t dur;
dur.set_from_double(timeout);
ldpp_dout(dpp, 10) << "waiting " << dur << "s for retry.." << dendl;
wait(dur);
timeout *= 2;
if (timeout > timeout_max)
timeout = timeout_max;
}
}
}
return 0;
}
/**
* PushAllCR is a coroutine that sends the period over all of the given
* connections, retrying until they are all marked as completed.
*/
class PushAllCR : public RGWCoroutine {
RGWHTTPManager *const http;
RGWPeriod period; //< period object to push
std::map<std::string, RGWRESTConn> conns; //< zones that need the period
public:
PushAllCR(CephContext* cct, RGWHTTPManager* http, RGWPeriod&& period,
std::map<std::string, RGWRESTConn>&& conns)
: RGWCoroutine(cct), http(http),
period(std::move(period)),
conns(std::move(conns))
{}
int operate(const DoutPrefixProvider *dpp) override;
};
int PushAllCR::operate(const DoutPrefixProvider *dpp)
{
reenter(this) {
// spawn a coroutine to push the period over each connection
yield {
ldpp_dout(dpp, 4) << "sending " << conns.size() << " periods" << dendl;
for (auto& c : conns)
spawn(new PushAndRetryCR(cct, c.first, &c.second, http, period), false);
}
// wait for all to complete
drain_all();
return set_cr_done();
}
return 0;
}
/// A background thread to run the PushAllCR coroutine and exit.
class RGWPeriodPusher::CRThread : public DoutPrefixProvider {
CephContext* cct;
RGWCoroutinesManager coroutines;
RGWHTTPManager http;
boost::intrusive_ptr<PushAllCR> push_all;
std::thread thread;
public:
CRThread(CephContext* cct, RGWPeriod&& period,
std::map<std::string, RGWRESTConn>&& conns)
: cct(cct), coroutines(cct, NULL),
http(cct, coroutines.get_completion_mgr()),
push_all(new PushAllCR(cct, &http, std::move(period), std::move(conns)))
{
http.start();
// must spawn the CR thread after start
thread = std::thread([this]() noexcept { coroutines.run(this, push_all.get()); });
}
~CRThread()
{
push_all.reset();
coroutines.stop();
http.stop();
if (thread.joinable())
thread.join();
}
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 period pusher CR thread: "; }
};
RGWPeriodPusher::RGWPeriodPusher(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
optional_yield y)
: cct(driver->ctx()), driver(driver)
{
rgw::sal::Zone* zone = driver->get_zone();
auto& realm_id = zone->get_realm_id();
if (realm_id.empty()) // no realm configuration
return;
// always send out the current period on startup
RGWPeriod period;
// XXX dang
int r = period.init(dpp, cct, static_cast<rgw::sal::RadosStore* >(driver)->svc()->sysobj, realm_id, y, zone->get_realm_name());
if (r < 0) {
ldpp_dout(dpp, -1) << "failed to load period for realm " << realm_id << dendl;
return;
}
std::lock_guard<std::mutex> lock(mutex);
handle_notify(std::move(period));
}
// destructor is here because CRThread is incomplete in the header
RGWPeriodPusher::~RGWPeriodPusher() = default;
void RGWPeriodPusher::handle_notify(RGWRealmNotify type,
bufferlist::const_iterator& p)
{
// decode the period
RGWZonesNeedPeriod info;
try {
decode(info, p);
} catch (buffer::error& e) {
lderr(cct) << "Failed to decode the period: " << e.what() << dendl;
return;
}
std::lock_guard<std::mutex> lock(mutex);
// we can't process this notification without access to our current realm
// configuration. queue it until resume()
if (driver == nullptr) {
pending_periods.emplace_back(std::move(info));
return;
}
handle_notify(std::move(info));
}
// expects the caller to hold a lock on mutex
void RGWPeriodPusher::handle_notify(RGWZonesNeedPeriod&& period)
{
if (period.get_realm_epoch() < realm_epoch) {
ldout(cct, 10) << "period's realm epoch " << period.get_realm_epoch()
<< " is not newer than current realm epoch " << realm_epoch
<< ", discarding update" << dendl;
return;
}
if (period.get_realm_epoch() == realm_epoch &&
period.get_epoch() <= period_epoch) {
ldout(cct, 10) << "period epoch " << period.get_epoch() << " is not newer "
"than current epoch " << period_epoch << ", discarding update" << dendl;
return;
}
// find our zonegroup in the new period
auto& zonegroups = period.get_map().zonegroups;
auto i = zonegroups.find(driver->get_zone()->get_zonegroup().get_id());
if (i == zonegroups.end()) {
lderr(cct) << "The new period does not contain my zonegroup!" << dendl;
return;
}
auto& my_zonegroup = i->second;
// if we're not a master zone, we're not responsible for pushing any updates
if (my_zonegroup.master_zone != driver->get_zone()->get_id())
return;
// construct a map of the zones that need this period. the map uses the same
// keys/ordering as the zone[group] map, so we can use a hint for insertions
std::map<std::string, RGWRESTConn> conns;
auto hint = conns.end();
// are we the master zonegroup in this period?
if (period.get_map().master_zonegroup == driver->get_zone()->get_zonegroup().get_id()) {
// update other zonegroup endpoints
for (auto& zg : zonegroups) {
auto& zonegroup = zg.second;
if (zonegroup.get_id() == driver->get_zone()->get_zonegroup().get_id())
continue;
if (zonegroup.endpoints.empty())
continue;
hint = conns.emplace_hint(
hint, std::piecewise_construct,
std::forward_as_tuple(zonegroup.get_id()),
std::forward_as_tuple(cct, driver, zonegroup.get_id(), zonegroup.endpoints, zonegroup.api_name));
}
}
// update other zone endpoints
for (auto& z : my_zonegroup.zones) {
auto& zone = z.second;
if (zone.id == driver->get_zone()->get_id())
continue;
if (zone.endpoints.empty())
continue;
hint = conns.emplace_hint(
hint, std::piecewise_construct,
std::forward_as_tuple(zone.id),
std::forward_as_tuple(cct, driver, zone.id, zone.endpoints, my_zonegroup.api_name));
}
if (conns.empty()) {
ldout(cct, 4) << "No zones to update" << dendl;
return;
}
realm_epoch = period.get_realm_epoch();
period_epoch = period.get_epoch();
ldout(cct, 4) << "Zone master pushing period " << period.get_id()
<< " epoch " << period_epoch << " to "
<< conns.size() << " other zones" << dendl;
// spawn a new coroutine thread, destroying the previous one
cr_thread.reset(new CRThread(cct, std::move(period), std::move(conns)));
}
void RGWPeriodPusher::pause()
{
ldout(cct, 4) << "paused for realm update" << dendl;
std::lock_guard<std::mutex> lock(mutex);
driver = nullptr;
}
void RGWPeriodPusher::resume(rgw::sal::Driver* driver)
{
std::lock_guard<std::mutex> lock(mutex);
this->driver = driver;
ldout(cct, 4) << "resume with " << pending_periods.size()
<< " periods pending" << dendl;
// process notification queue
for (auto& info : pending_periods) {
handle_notify(std::move(info));
}
pending_periods.clear();
}
| 9,760 | 29.791798 | 129 |
cc
|
null |
ceph-main/src/rgw/rgw_period_pusher.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 <memory>
#include <mutex>
#include <vector>
#include "common/async/yield_context.h"
#include "rgw_realm_reloader.h"
#include "rgw_sal_fwd.h"
class RGWPeriod;
// RGWRealmNotify payload for push coordination
using RGWZonesNeedPeriod = RGWPeriod;
/**
* RGWPeriodPusher coordinates with other nodes via the realm watcher to manage
* the responsibility for pushing period updates to other zones or zonegroups.
*/
class RGWPeriodPusher final : public RGWRealmWatcher::Watcher,
public RGWRealmReloader::Pauser {
public:
explicit RGWPeriodPusher(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y);
~RGWPeriodPusher() override;
/// respond to realm notifications by pushing new periods to other zones
void handle_notify(RGWRealmNotify type, bufferlist::const_iterator& p) override;
/// avoid accessing RGWRados while dynamic reconfiguration is in progress.
/// notifications will be enqueued until resume()
void pause() override;
/// continue processing notifications with a new RGWRados instance
void resume(rgw::sal::Driver* driver) override;
private:
void handle_notify(RGWZonesNeedPeriod&& period);
CephContext *const cct;
rgw::sal::Driver* driver;
std::mutex mutex;
epoch_t realm_epoch{0}; //< the current realm epoch being sent
epoch_t period_epoch{0}; //< the current period epoch being sent
/// while paused for reconfiguration, we need to queue up notifications
std::vector<RGWZonesNeedPeriod> pending_periods;
class CRThread; //< contains thread, coroutine manager, http manager
std::unique_ptr<CRThread> cr_thread; //< thread to run the push coroutines
};
| 1,796 | 31.672727 | 102 |
h
|
null |
ceph-main/src/rgw/rgw_placement_types.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 "include/types.h"
#include "common/Formatter.h"
static std::string RGW_STORAGE_CLASS_STANDARD = "STANDARD";
struct rgw_placement_rule {
std::string name;
std::string storage_class;
rgw_placement_rule() {}
rgw_placement_rule(const std::string& _n, const std::string& _sc) : name(_n), storage_class(_sc) {}
rgw_placement_rule(const rgw_placement_rule& _r, const std::string& _sc) : name(_r.name) {
if (!_sc.empty()) {
storage_class = _sc;
} else {
storage_class = _r.storage_class;
}
}
bool empty() const {
return name.empty() && storage_class.empty();
}
void inherit_from(const rgw_placement_rule& r) {
if (name.empty()) {
name = r.name;
}
if (storage_class.empty()) {
storage_class = r.storage_class;
}
}
void clear() {
name.clear();
storage_class.clear();
}
void init(const std::string& n, const std::string& c) {
name = n;
storage_class = c;
}
static const std::string& get_canonical_storage_class(const std::string& storage_class) {
if (storage_class.empty()) {
return RGW_STORAGE_CLASS_STANDARD;
}
return storage_class;
}
const std::string& get_storage_class() const {
return get_canonical_storage_class(storage_class);
}
int compare(const rgw_placement_rule& r) const {
int c = name.compare(r.name);
if (c != 0) {
return c;
}
return get_storage_class().compare(r.get_storage_class());
}
bool operator==(const rgw_placement_rule& r) const {
return (name == r.name &&
get_storage_class() == r.get_storage_class());
}
bool operator!=(const rgw_placement_rule& r) const {
return !(*this == r);
}
void encode(bufferlist& bl) const {
/* no ENCODE_START/END due to backward compatibility */
std::string s = to_str();
ceph::encode(s, bl);
}
void decode(bufferlist::const_iterator& bl) {
std::string s;
ceph::decode(s, bl);
from_str(s);
}
std::string to_str() const {
if (standard_storage_class()) {
return name;
}
return to_str_explicit();
}
std::string to_str_explicit() const {
return name + "/" + storage_class;
}
void from_str(const std::string& s) {
size_t pos = s.find("/");
if (pos == std::string::npos) {
name = s;
storage_class.clear();
return;
}
name = s.substr(0, pos);
storage_class = s.substr(pos + 1);
}
bool standard_storage_class() const {
return storage_class.empty() || storage_class == RGW_STORAGE_CLASS_STANDARD;
}
};
WRITE_CLASS_ENCODER(rgw_placement_rule)
| 2,739 | 22.02521 | 101 |
h
|
null |
ceph-main/src/rgw/rgw_policy_s3.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 "common/ceph_json.h"
#include "rgw_policy_s3.h"
#include "rgw_common.h"
#include "rgw_crypt_sanitize.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
class RGWPolicyCondition {
protected:
string v1;
string v2;
virtual bool check(const string& first, const string& second, string& err_msg) = 0;
public:
virtual ~RGWPolicyCondition() {}
void set_vals(const string& _v1, const string& _v2) {
v1 = _v1;
v2 = _v2;
}
bool check(RGWPolicyEnv *env, map<string, bool, ltstr_nocase>& checked_vars, string& err_msg) {
string first, second;
env->get_value(v1, first, checked_vars);
env->get_value(v2, second, checked_vars);
dout(1) << "policy condition check " << v1 << " ["
<< rgw::crypt_sanitize::s3_policy{v1, first}
<< "] " << v2 << " ["
<< rgw::crypt_sanitize::s3_policy{v2, second}
<< "]" << dendl;
bool ret = check(first, second, err_msg);
if (!ret) {
err_msg.append(": ");
err_msg.append(v1);
err_msg.append(", ");
err_msg.append(v2);
}
return ret;
}
};
class RGWPolicyCondition_StrEqual : public RGWPolicyCondition {
protected:
bool check(const string& first, const string& second, string& msg) override {
bool ret = first.compare(second) == 0;
if (!ret) {
msg = "Policy condition failed: eq";
}
return ret;
}
};
class RGWPolicyCondition_StrStartsWith : public RGWPolicyCondition {
protected:
bool check(const string& first, const string& second, string& msg) override {
bool ret = first.compare(0, second.size(), second) == 0;
if (!ret) {
msg = "Policy condition failed: starts-with";
}
return ret;
}
};
void RGWPolicyEnv::add_var(const string& name, const string& value)
{
vars[name] = value;
}
bool RGWPolicyEnv::get_var(const string& name, string& val)
{
map<string, string, ltstr_nocase>::iterator iter = vars.find(name);
if (iter == vars.end())
return false;
val = iter->second;
return true;
}
bool RGWPolicyEnv::get_value(const string& s, string& val, map<string, bool, ltstr_nocase>& checked_vars)
{
if (s.empty() || s[0] != '$') {
val = s;
return true;
}
const string& var = s.substr(1);
checked_vars[var] = true;
return get_var(var, val);
}
bool RGWPolicyEnv::match_policy_vars(map<string, bool, ltstr_nocase>& policy_vars, string& err_msg)
{
map<string, string, ltstr_nocase>::iterator iter;
string ignore_prefix = "x-ignore-";
for (iter = vars.begin(); iter != vars.end(); ++iter) {
const string& var = iter->first;
if (strncasecmp(ignore_prefix.c_str(), var.c_str(), ignore_prefix.size()) == 0)
continue;
if (policy_vars.count(var) == 0) {
err_msg = "Policy missing condition: ";
err_msg.append(iter->first);
dout(1) << "env var missing in policy: " << iter->first << dendl;
return false;
}
}
return true;
}
RGWPolicy::~RGWPolicy()
{
list<RGWPolicyCondition *>::iterator citer;
for (citer = conditions.begin(); citer != conditions.end(); ++citer) {
RGWPolicyCondition *cond = *citer;
delete cond;
}
}
int RGWPolicy::set_expires(const string& e)
{
struct tm t;
if (!parse_iso8601(e.c_str(), &t))
return -EINVAL;
expires = internal_timegm(&t);
return 0;
}
int RGWPolicy::add_condition(const string& op, const string& first, const string& second, string& err_msg)
{
RGWPolicyCondition *cond = NULL;
if (stringcasecmp(op, "eq") == 0) {
cond = new RGWPolicyCondition_StrEqual;
} else if (stringcasecmp(op, "starts-with") == 0) {
cond = new RGWPolicyCondition_StrStartsWith;
} else if (stringcasecmp(op, "content-length-range") == 0) {
off_t min, max;
int r = stringtoll(first, &min);
if (r < 0) {
err_msg = "Bad content-length-range param";
dout(0) << "bad content-length-range param: " << first << dendl;
return r;
}
r = stringtoll(second, &max);
if (r < 0) {
err_msg = "Bad content-length-range param";
dout(0) << "bad content-length-range param: " << second << dendl;
return r;
}
if (min > min_length)
min_length = min;
if (max < max_length)
max_length = max;
return 0;
}
if (!cond) {
err_msg = "Invalid condition: ";
err_msg.append(op);
dout(0) << "invalid condition: " << op << dendl;
return -EINVAL;
}
cond->set_vals(first, second);
conditions.push_back(cond);
return 0;
}
int RGWPolicy::check(RGWPolicyEnv *env, string& err_msg)
{
uint64_t now = ceph_clock_now().sec();
if (expires <= now) {
dout(0) << "NOTICE: policy calculated as expired: " << expiration_str << dendl;
err_msg = "Policy expired";
return -EACCES; // change to condition about expired policy following S3
}
list<pair<string, string> >::iterator viter;
for (viter = var_checks.begin(); viter != var_checks.end(); ++viter) {
pair<string, string>& p = *viter;
const string& name = p.first;
const string& check_val = p.second;
string val;
if (!env->get_var(name, val)) {
dout(20) << " policy check failed, variable not found: '" << name << "'" << dendl;
err_msg = "Policy check failed, variable not found: ";
err_msg.append(name);
return -EACCES;
}
set_var_checked(name);
dout(20) << "comparing " << name << " [" << val << "], " << check_val << dendl;
if (val.compare(check_val) != 0) {
err_msg = "Policy check failed, variable not met condition: ";
err_msg.append(name);
dout(1) << "policy check failed, val=" << val << " != " << check_val << dendl;
return -EACCES;
}
}
list<RGWPolicyCondition *>::iterator citer;
for (citer = conditions.begin(); citer != conditions.end(); ++citer) {
RGWPolicyCondition *cond = *citer;
if (!cond->check(env, checked_vars, err_msg)) {
return -EACCES;
}
}
if (!env->match_policy_vars(checked_vars, err_msg)) {
dout(1) << "missing policy condition" << dendl;
return -EACCES;
}
return 0;
}
int RGWPolicy::from_json(bufferlist& bl, string& err_msg)
{
JSONParser parser;
if (!parser.parse(bl.c_str(), bl.length())) {
err_msg = "Malformed JSON";
dout(0) << "malformed json" << dendl;
return -EINVAL;
}
// as no time was included in the request, we hope that the user has included a short timeout
JSONObjIter iter = parser.find_first("expiration");
if (iter.end()) {
err_msg = "Policy missing expiration";
dout(0) << "expiration not found" << dendl;
return -EINVAL; // change to a "no expiration" error following S3
}
JSONObj *obj = *iter;
expiration_str = obj->get_data();
int r = set_expires(expiration_str);
if (r < 0) {
err_msg = "Failed to parse policy expiration";
return r;
}
iter = parser.find_first("conditions");
if (iter.end()) {
err_msg = "Policy missing conditions";
dout(0) << "conditions not found" << dendl;
return -EINVAL; // change to a "no conditions" error following S3
}
obj = *iter;
iter = obj->find_first();
for (; !iter.end(); ++iter) {
JSONObj *child = *iter;
dout(20) << "data=" << child->get_data() << dendl;
dout(20) << "is_object=" << child->is_object() << dendl;
dout(20) << "is_array=" << child->is_array() << dendl;
JSONObjIter citer = child->find_first();
if (child->is_array()) {
vector<string> v;
int i;
for (i = 0; !citer.end() && i < 3; ++citer, ++i) {
JSONObj *o = *citer;
v.push_back(o->get_data());
}
if (i != 3 || !citer.end()) { /* we expect exactly 3 arguments here */
err_msg = "Bad condition array, expecting 3 arguments";
return -EINVAL;
}
int r = add_condition(v[0], v[1], v[2], err_msg);
if (r < 0)
return r;
} else if (!citer.end()) {
JSONObj *c = *citer;
dout(20) << "adding simple_check: " << c->get_name() << " : " << c->get_data() << dendl;
add_simple_check(c->get_name(), c->get_data());
} else {
return -EINVAL;
}
}
return 0;
}
| 8,222 | 25.872549 | 106 |
cc
|
null |
ceph-main/src/rgw/rgw_policy_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 <limits.h>
#include <map>
#include <list>
#include <string>
#include "include/utime.h"
#include "rgw_string.h"
class RGWPolicyEnv {
std::map<std::string, std::string, ltstr_nocase> vars;
public:
void add_var(const std::string& name, const std::string& value);
bool get_var(const std::string& name, std::string& val);
bool get_value(const std::string& s, std::string& val, std::map<std::string, bool, ltstr_nocase>& checked_vars);
bool match_policy_vars(std::map<std::string, bool, ltstr_nocase>& policy_vars, std::string& err_msg);
};
class RGWPolicyCondition;
class RGWPolicy {
uint64_t expires;
std::string expiration_str;
std::list<RGWPolicyCondition *> conditions;
std::list<std::pair<std::string, std::string> > var_checks;
std::map<std::string, bool, ltstr_nocase> checked_vars;
public:
off_t min_length;
off_t max_length;
RGWPolicy() : expires(0), min_length(0), max_length(LLONG_MAX) {}
~RGWPolicy();
int set_expires(const std::string& e);
void set_var_checked(const std::string& var) {
checked_vars[var] = true;
}
int add_condition(const std::string& op, const std::string& first, const std::string& second, std::string& err_msg);
void add_simple_check(const std::string& var, const std::string& value) {
var_checks.emplace_back(var, value);
}
int check(RGWPolicyEnv *env, std::string& err_msg);
int from_json(bufferlist& bl, std::string& err_msg);
};
| 1,557 | 25.862069 | 118 |
h
|
null |
ceph-main/src/rgw/rgw_polparser.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include "include/buffer.h"
#include "common/ceph_argparse.h"
#include "common/common_init.h"
#include "global/global_init.h"
#include "rgw/rgw_iam_policy.h"
// Returns true on success
bool parse(CephContext* cct, const std::string& tenant,
const std::string& fname, std::istream& in) noexcept
{
bufferlist bl;
bl.append(in);
try {
auto p = rgw::IAM::Policy(
cct, tenant, bl,
cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
} catch (const rgw::IAM::PolicyParseException& e) {
std::cerr << fname << ": " << e.what() << std::endl;
return false;
} catch (const std::exception& e) {
std::cerr << fname << ": caught exception: " << e.what() << std::endl;;
return false;
}
return true;
}
void helpful_exit(std::string_view cmdname)
{
std::cerr << cmdname << "-h for usage" << std::endl;
exit(1);
}
void usage(std::string_view cmdname)
{
std::cout << "usage: " << cmdname << " -t <tenant> [filename]"
<< std::endl;
}
int main(int argc, const char** argv)
{
std::string_view cmdname = argv[0];
std::string tenant;
auto args = argv_to_vec(argc, argv);
if (ceph_argparse_need_usage(args)) {
usage(cmdname);
exit(0);
}
auto cct = global_init(nullptr, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_UTILITY,
CINIT_FLAG_NO_DAEMON_ACTIONS |
CINIT_FLAG_NO_MON_CONFIG);
common_init_finish(cct.get());
std::string val;
for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
if (ceph_argparse_double_dash(args, i)) {
break;
} else if (ceph_argparse_witharg(args, i, &val, "--tenant", "-t",
(char*)nullptr)) {
tenant = std::move(val);
} else {
++i;
}
}
if (tenant.empty()) {
std::cerr << cmdname << ": must specify tenant name" << std::endl;
helpful_exit(cmdname);
}
bool success = true;
if (args.empty()) {
success = parse(cct.get(), tenant, "(stdin)", std::cin);
} else {
for (const auto& file : args) {
std::ifstream in;
in.open(file, std::ifstream::in);
if (!in.is_open()) {
std::cerr << "Can't read " << file << std::endl;
success = false;
}
if (!parse(cct.get(), tenant, file, in)) {
success = false;
}
}
}
return success ? 0 : 1;
}
| 2,541 | 22.981132 | 80 |
cc
|
null |
ceph-main/src/rgw/rgw_pool_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.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* introduce changes or include files which can only be compiled in
* radosgw or OSD contexts (e.g., rgw_sal.h, rgw_common.h)
*/
#pragma once
#include <string>
#include <fmt/format.h>
#include "include/types.h"
#include "common/Formatter.h"
class JSONObj;
struct rgw_pool {
std::string name;
std::string ns;
rgw_pool() = default;
rgw_pool(const rgw_pool& _p) : name(_p.name), ns(_p.ns) {}
rgw_pool(rgw_pool&&) = default;
rgw_pool(const std::string& _s) {
from_str(_s);
}
rgw_pool(const std::string& _name, const std::string& _ns) : name(_name), ns(_ns) {}
std::string to_str() const;
void from_str(const std::string& s);
void init(const std::string& _s) {
from_str(_s);
}
bool empty() const {
return name.empty();
}
int compare(const rgw_pool& p) const {
int r = name.compare(p.name);
if (r != 0) {
return r;
}
return ns.compare(p.ns);
}
void encode(ceph::buffer::list& bl) const {
ENCODE_START(10, 10, bl);
encode(name, bl);
encode(ns, bl);
ENCODE_FINISH(bl);
}
void decode_from_bucket(ceph::buffer::list::const_iterator& bl);
void decode(ceph::buffer::list::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(10, 3, 3, bl);
decode(name, bl);
if (struct_v < 10) {
/*
* note that rgw_pool can be used where rgw_bucket was used before
* therefore we inherit rgw_bucket's old versions. However, we only
* need the first field from rgw_bucket. unless we add more fields
* in which case we'll need to look at struct_v, and check the actual
* version. Anything older than 10 needs to be treated as old rgw_bucket
*/
} else {
decode(ns, bl);
}
DECODE_FINISH(bl);
}
rgw_pool& operator=(const rgw_pool&) = default;
bool operator==(const rgw_pool& p) const {
return (compare(p) == 0);
}
bool operator!=(const rgw_pool& p) const {
return !(*this == p);
}
bool operator<(const rgw_pool& p) const {
int r = name.compare(p.name);
if (r == 0) {
return (ns.compare(p.ns) < 0);
}
return (r < 0);
}
};
WRITE_CLASS_ENCODER(rgw_pool)
inline std::ostream& operator<<(std::ostream& out, const rgw_pool& p) {
out << p.to_str();
return out;
}
struct rgw_data_placement_target {
rgw_pool data_pool;
rgw_pool data_extra_pool;
rgw_pool index_pool;
rgw_data_placement_target() = default;
rgw_data_placement_target(const rgw_data_placement_target&) = default;
rgw_data_placement_target(rgw_data_placement_target&&) = default;
rgw_data_placement_target(const rgw_pool& data_pool,
const rgw_pool& data_extra_pool,
const rgw_pool& index_pool)
: data_pool(data_pool),
data_extra_pool(data_extra_pool),
index_pool(index_pool) {
}
rgw_data_placement_target&
operator=(const rgw_data_placement_target&) = default;
const rgw_pool& get_data_extra_pool() const {
if (data_extra_pool.empty()) {
return data_pool;
}
return data_extra_pool;
}
int compare(const rgw_data_placement_target& t) {
int c = data_pool.compare(t.data_pool);
if (c != 0) {
return c;
}
c = data_extra_pool.compare(t.data_extra_pool);
if (c != 0) {
return c;
}
return index_pool.compare(t.index_pool);
};
void dump(ceph::Formatter *f) const;
void decode_json(JSONObj *obj);
};
| 3,886 | 23.601266 | 86 |
h
|
null |
ceph-main/src/rgw/rgw_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 "include/scope_guard.h"
#include <utility>
#include "rgw_auth_registry.h"
#include "rgw_dmclock_scheduler.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_opa.h"
#include "rgw_perf_counters.h"
#include "rgw_lua.h"
#include "rgw_lua_request.h"
#include "rgw_tracer.h"
#include "rgw_ratelimit.h"
#include "services/svc_zone_utils.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
using rgw::dmclock::Scheduler;
void RGWProcess::RGWWQ::_dump_queue()
{
if (!g_conf()->subsys.should_gather<ceph_subsys_rgw, 20>()) {
return;
}
deque<RGWRequest *>::iterator iter;
if (process->m_req_queue.empty()) {
dout(20) << "RGWWQ: empty" << dendl;
return;
}
dout(20) << "RGWWQ:" << dendl;
for (iter = process->m_req_queue.begin();
iter != process->m_req_queue.end(); ++iter) {
dout(20) << "req: " << hex << *iter << dec << dendl;
}
} /* RGWProcess::RGWWQ::_dump_queue */
auto schedule_request(Scheduler *scheduler, req_state *s, RGWOp *op)
{
using rgw::dmclock::SchedulerCompleter;
if (!scheduler)
return std::make_pair(0,SchedulerCompleter{});
const auto client = op->dmclock_client();
const auto cost = op->dmclock_cost();
if (s->cct->_conf->subsys.should_gather(ceph_subsys_rgw, 10)) {
ldpp_dout(op,10) << "scheduling with "
<< s->cct->_conf.get_val<std::string>("rgw_scheduler_type")
<< " client=" << static_cast<int>(client)
<< " cost=" << cost << dendl;
}
return scheduler->schedule_request(client, {},
req_state::Clock::to_double(s->time),
cost,
s->yield);
}
bool RGWProcess::RGWWQ::_enqueue(RGWRequest* req) {
process->m_req_queue.push_back(req);
perfcounter->inc(l_rgw_qlen);
dout(20) << "enqueued request req=" << hex << req << dec << dendl;
_dump_queue();
return true;
}
RGWRequest* RGWProcess::RGWWQ::_dequeue() {
if (process->m_req_queue.empty())
return NULL;
RGWRequest *req = process->m_req_queue.front();
process->m_req_queue.pop_front();
dout(20) << "dequeued request req=" << hex << req << dec << dendl;
_dump_queue();
perfcounter->inc(l_rgw_qlen, -1);
return req;
}
void RGWProcess::RGWWQ::_process(RGWRequest *req, ThreadPool::TPHandle &) {
perfcounter->inc(l_rgw_qactive);
process->handle_request(this, req);
process->req_throttle.put(1);
perfcounter->inc(l_rgw_qactive, -1);
}
bool rate_limit(rgw::sal::Driver* driver, req_state* s) {
// we dont want to limit health check or system or admin requests
const auto& is_admin_or_system = s->user->get_info();
if ((s->op_type == RGW_OP_GET_HEALTH_CHECK) || is_admin_or_system.admin || is_admin_or_system.system)
return false;
std::string userfind;
RGWRateLimitInfo global_user;
RGWRateLimitInfo global_bucket;
RGWRateLimitInfo global_anon;
RGWRateLimitInfo* bucket_ratelimit;
RGWRateLimitInfo* user_ratelimit;
driver->get_ratelimit(global_bucket, global_user, global_anon);
bucket_ratelimit = &global_bucket;
user_ratelimit = &global_user;
s->user->get_id().to_str(userfind);
userfind = "u" + userfind;
s->ratelimit_user_name = userfind;
std::string bucketfind = !rgw::sal::Bucket::empty(s->bucket.get()) ? "b" + s->bucket->get_marker() : "";
s->ratelimit_bucket_marker = bucketfind;
const char *method = s->info.method;
auto iter = s->user->get_attrs().find(RGW_ATTR_RATELIMIT);
if(iter != s->user->get_attrs().end()) {
try {
RGWRateLimitInfo user_ratelimit_temp;
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(user_ratelimit_temp, biter);
// override global rate limiting only if local rate limiting is enabled
if (user_ratelimit_temp.enabled)
*user_ratelimit = user_ratelimit_temp;
} catch (buffer::error& err) {
ldpp_dout(s, 0) << "ERROR: failed to decode rate limit" << dendl;
return -EIO;
}
}
if (s->user->get_id().id == RGW_USER_ANON_ID && global_anon.enabled) {
*user_ratelimit = global_anon;
}
bool limit_bucket = false;
bool limit_user = s->ratelimit_data->should_rate_limit(method, s->ratelimit_user_name, s->time, user_ratelimit);
if(!rgw::sal::Bucket::empty(s->bucket.get()))
{
iter = s->bucket->get_attrs().find(RGW_ATTR_RATELIMIT);
if(iter != s->bucket->get_attrs().end()) {
try {
RGWRateLimitInfo bucket_ratelimit_temp;
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(bucket_ratelimit_temp, biter);
// override global rate limiting only if local rate limiting is enabled
if (bucket_ratelimit_temp.enabled)
*bucket_ratelimit = bucket_ratelimit_temp;
} catch (buffer::error& err) {
ldpp_dout(s, 0) << "ERROR: failed to decode rate limit" << dendl;
return -EIO;
}
}
if (!limit_user) {
limit_bucket = s->ratelimit_data->should_rate_limit(method, s->ratelimit_bucket_marker, s->time, bucket_ratelimit);
}
}
if(limit_bucket && !limit_user) {
s->ratelimit_data->giveback_tokens(method, s->ratelimit_user_name);
}
s->user_ratelimit = *user_ratelimit;
s->bucket_ratelimit = *bucket_ratelimit;
return (limit_user || limit_bucket);
}
int rgw_process_authenticated(RGWHandler_REST * const handler,
RGWOp *& op,
RGWRequest * const req,
req_state * const s,
optional_yield y,
rgw::sal::Driver* driver,
const bool skip_retarget)
{
ldpp_dout(op, 2) << "init permissions" << dendl;
int ret = handler->init_permissions(op, y);
if (ret < 0) {
return ret;
}
/**
* Only some accesses support website mode, and website mode does NOT apply
* if you are using the REST endpoint either (ergo, no authenticated access)
*/
if (! skip_retarget) {
ldpp_dout(op, 2) << "recalculating target" << dendl;
ret = handler->retarget(op, &op, y);
if (ret < 0) {
return ret;
}
req->op = op;
} else {
ldpp_dout(op, 2) << "retargeting skipped because of SubOp mode" << dendl;
}
/* If necessary extract object ACL and put them into req_state. */
ldpp_dout(op, 2) << "reading permissions" << dendl;
ret = handler->read_permissions(op, y);
if (ret < 0) {
return ret;
}
ldpp_dout(op, 2) << "init op" << dendl;
ret = op->init_processing(y);
if (ret < 0) {
return ret;
}
ldpp_dout(op, 2) << "verifying op mask" << dendl;
ret = op->verify_op_mask();
if (ret < 0) {
return ret;
}
/* Check if OPA is used to authorize requests */
if (s->cct->_conf->rgw_use_opa_authz) {
ret = rgw_opa_authorize(op, s);
if (ret < 0) {
return ret;
}
}
ldpp_dout(op, 2) << "verifying op permissions" << dendl;
{
auto span = tracing::rgw::tracer.add_span("verify_permission", s->trace);
std::swap(span, s->trace);
ret = op->verify_permission(y);
std::swap(span, s->trace);
}
if (ret < 0) {
if (s->system_request) {
dout(2) << "overriding permissions due to system operation" << dendl;
} else if (s->auth.identity->is_admin_of(s->user->get_id())) {
dout(2) << "overriding permissions due to admin operation" << dendl;
} else {
return ret;
}
}
ldpp_dout(op, 2) << "verifying op params" << dendl;
ret = op->verify_params();
if (ret < 0) {
return ret;
}
ldpp_dout(op, 2) << "pre-executing" << dendl;
op->pre_exec();
ldpp_dout(op, 2) << "check rate limiting" << dendl;
if (rate_limit(driver, s)) {
return -ERR_RATE_LIMITED;
}
ldpp_dout(op, 2) << "executing" << dendl;
{
auto span = tracing::rgw::tracer.add_span("execute", s->trace);
std::swap(span, s->trace);
op->execute(y);
std::swap(span, s->trace);
}
ldpp_dout(op, 2) << "completing" << dendl;
op->complete();
return 0;
}
int process_request(const RGWProcessEnv& penv,
RGWRequest* const req,
const std::string& frontend_prefix,
RGWRestfulIO* const client_io,
optional_yield yield,
rgw::dmclock::Scheduler *scheduler,
string* user,
ceph::coarse_real_clock::duration* latency,
int* http_ret)
{
int ret = client_io->init(g_ceph_context);
dout(1) << "====== starting new request req=" << hex << req << dec
<< " =====" << dendl;
perfcounter->inc(l_rgw_req);
RGWEnv& rgw_env = client_io->get_env();
req_state rstate(g_ceph_context, penv, &rgw_env, req->id);
req_state *s = &rstate;
s->ratelimit_data = penv.ratelimiting->get_active();
rgw::sal::Driver* driver = penv.driver;
std::unique_ptr<rgw::sal::User> u = driver->get_user(rgw_user());
s->set_user(u);
if (ret < 0) {
s->cio = client_io;
abort_early(s, nullptr, ret, nullptr, yield);
return ret;
}
s->req_id = driver->zone_unique_id(req->id);
s->trans_id = driver->zone_unique_trans_id(req->id);
s->host_id = driver->get_host_id();
s->yield = yield;
ldpp_dout(s, 2) << "initializing for trans_id = " << s->trans_id << dendl;
RGWOp* op = nullptr;
int init_error = 0;
bool should_log = false;
RGWREST* rest = penv.rest;
RGWRESTMgr *mgr;
RGWHandler_REST *handler = rest->get_handler(driver, s,
*penv.auth_registry,
frontend_prefix,
client_io, &mgr, &init_error);
rgw::dmclock::SchedulerCompleter c;
if (init_error != 0) {
abort_early(s, nullptr, init_error, nullptr, yield);
goto done;
}
ldpp_dout(s, 10) << "handler=" << typeid(*handler).name() << dendl;
should_log = mgr->get_logging();
ldpp_dout(s, 2) << "getting op " << s->op << dendl;
op = handler->get_op();
if (!op) {
abort_early(s, NULL, -ERR_METHOD_NOT_ALLOWED, handler, yield);
goto done;
}
{
s->trace_enabled = tracing::rgw::tracer.is_enabled();
std::string script;
auto rc = rgw::lua::read_script(s, penv.lua.manager.get(), s->bucket_tenant, s->yield, rgw::lua::context::preRequest, script);
if (rc == -ENOENT) {
// no script, nothing to do
} else if (rc < 0) {
ldpp_dout(op, 5) << "WARNING: failed to read pre request script. error: " << rc << dendl;
} else {
rc = rgw::lua::request::execute(driver, rest, penv.olog, s, op, script);
if (rc < 0) {
ldpp_dout(op, 5) << "WARNING: failed to execute pre request script. error: " << rc << dendl;
}
}
}
std::tie(ret,c) = schedule_request(scheduler, s, op);
if (ret < 0) {
if (ret == -EAGAIN) {
ret = -ERR_RATE_LIMITED;
}
ldpp_dout(op,0) << "Scheduling request failed with " << ret << dendl;
abort_early(s, op, ret, handler, yield);
goto done;
}
req->op = op;
ldpp_dout(op, 10) << "op=" << typeid(*op).name() << dendl;
s->op_type = op->get_type();
try {
ldpp_dout(op, 2) << "verifying requester" << dendl;
ret = op->verify_requester(*penv.auth_registry, yield);
if (ret < 0) {
dout(10) << "failed to authorize request" << dendl;
abort_early(s, op, ret, handler, yield);
goto done;
}
/* FIXME: remove this after switching all handlers to the new authentication
* infrastructure. */
if (nullptr == s->auth.identity) {
s->auth.identity = rgw::auth::transform_old_authinfo(s);
}
ldpp_dout(op, 2) << "normalizing buckets and tenants" << dendl;
ret = handler->postauth_init(yield);
if (ret < 0) {
dout(10) << "failed to run post-auth init" << dendl;
abort_early(s, op, ret, handler, yield);
goto done;
}
if (s->user->get_info().suspended) {
dout(10) << "user is suspended, uid=" << s->user->get_id() << dendl;
abort_early(s, op, -ERR_USER_SUSPENDED, handler, yield);
goto done;
}
const auto trace_name = std::string(op->name()) + " " + s->trans_id;
s->trace = tracing::rgw::tracer.start_trace(trace_name, s->trace_enabled);
s->trace->SetAttribute(tracing::rgw::OP, op->name());
s->trace->SetAttribute(tracing::rgw::TYPE, tracing::rgw::REQUEST);
ret = rgw_process_authenticated(handler, op, req, s, yield, driver);
if (ret < 0) {
abort_early(s, op, ret, handler, yield);
goto done;
}
} catch (const ceph::crypto::DigestException& e) {
dout(0) << "authentication failed" << e.what() << dendl;
abort_early(s, op, -ERR_INVALID_SECRET_KEY, handler, yield);
}
done:
if (op) {
if (s->trace) {
s->trace->SetAttribute(tracing::rgw::RETURN, op->get_ret());
if (!rgw::sal::User::empty(s->user)) {
s->trace->SetAttribute(tracing::rgw::USER_ID, s->user->get_id().id);
}
if (!rgw::sal::Bucket::empty(s->bucket)) {
s->trace->SetAttribute(tracing::rgw::BUCKET_NAME, s->bucket->get_name());
}
if (!rgw::sal::Object::empty(s->object)) {
s->trace->SetAttribute(tracing::rgw::OBJECT_NAME, s->object->get_name());
}
}
std::string script;
auto rc = rgw::lua::read_script(s, penv.lua.manager.get(), s->bucket_tenant, s->yield, rgw::lua::context::postRequest, script);
if (rc == -ENOENT) {
// no script, nothing to do
} else if (rc < 0) {
ldpp_dout(op, 5) << "WARNING: failed to read post request script. error: " << rc << dendl;
} else {
rc = rgw::lua::request::execute(driver, rest, penv.olog, s, op, script);
if (rc < 0) {
ldpp_dout(op, 5) << "WARNING: failed to execute post request script. error: " << rc << dendl;
}
}
}
try {
client_io->complete_request();
} catch (rgw::io::Exception& e) {
dout(0) << "ERROR: client_io->complete_request() returned "
<< e.what() << dendl;
}
if (should_log) {
rgw_log_op(rest, s, op, penv.olog);
}
if (http_ret != nullptr) {
*http_ret = s->err.http_ret;
}
int op_ret = 0;
if (user && !rgw::sal::User::empty(s->user.get())) {
*user = s->user->get_id().to_str();
}
if (op) {
op_ret = op->get_ret();
ldpp_dout(op, 2) << "op status=" << op_ret << dendl;
ldpp_dout(op, 2) << "http status=" << s->err.http_ret << dendl;
} else {
ldpp_dout(s, 2) << "http status=" << s->err.http_ret << dendl;
}
if (handler)
handler->put_op(op);
rest->put_handler(handler);
const auto lat = s->time_elapsed();
if (latency) {
*latency = lat;
}
dout(1) << "====== req done req=" << hex << req << dec
<< " op status=" << op_ret
<< " http_status=" << s->err.http_ret
<< " latency=" << lat
<< " ======"
<< dendl;
return (ret < 0 ? ret : s->err.ret);
} /* process_request */
| 15,078 | 30.879493 | 131 |
cc
|
null |
ceph-main/src/rgw/rgw_process.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"
#include "rgw_acl.h"
#include "rgw_user.h"
#include "rgw_rest.h"
#include "include/ceph_assert.h"
#include "common/WorkQueue.h"
#include "common/Throttle.h"
#include <atomic>
#define dout_context g_ceph_context
namespace rgw::dmclock {
class Scheduler;
}
struct RGWProcessEnv;
class RGWFrontendConfig;
class RGWRequest;
class RGWProcess {
std::deque<RGWRequest*> m_req_queue;
protected:
CephContext *cct;
RGWProcessEnv& env;
ThreadPool m_tp;
Throttle req_throttle;
RGWFrontendConfig* conf;
int sock_fd;
std::string uri_prefix;
struct RGWWQ : public DoutPrefixProvider, public ThreadPool::WorkQueue<RGWRequest> {
RGWProcess* process;
RGWWQ(RGWProcess* p, ceph::timespan timeout, ceph::timespan suicide_timeout,
ThreadPool* tp)
: ThreadPool::WorkQueue<RGWRequest>("RGWWQ", timeout, suicide_timeout,
tp), process(p) {}
bool _enqueue(RGWRequest* req) override;
void _dequeue(RGWRequest* req) override {
ceph_abort();
}
bool _empty() override {
return process->m_req_queue.empty();
}
RGWRequest* _dequeue() override;
using ThreadPool::WorkQueue<RGWRequest>::_process;
void _process(RGWRequest *req, ThreadPool::TPHandle &) override;
void _dump_queue();
void _clear() override {
ceph_assert(process->m_req_queue.empty());
}
CephContext *get_cct() const override { return process->cct; }
unsigned get_subsys() const { return ceph_subsys_rgw; }
std::ostream& gen_prefix(std::ostream& out) const { return out << "rgw request work queue: ";}
} req_wq;
public:
RGWProcess(CephContext* const cct,
RGWProcessEnv& env,
const int num_threads,
std::string uri_prefix,
RGWFrontendConfig* const conf)
: cct(cct), env(env),
m_tp(cct, "RGWProcess::m_tp", "tp_rgw_process", num_threads),
req_throttle(cct, "rgw_ops", num_threads * 2),
conf(conf),
sock_fd(-1),
uri_prefix(std::move(uri_prefix)),
req_wq(this,
ceph::make_timespan(g_conf()->rgw_op_thread_timeout),
ceph::make_timespan(g_conf()->rgw_op_thread_suicide_timeout),
&m_tp) {
}
virtual ~RGWProcess() = default;
const RGWProcessEnv& get_env() const { return env; }
virtual void run() = 0;
virtual void handle_request(const DoutPrefixProvider *dpp, RGWRequest *req) = 0;
void pause() {
m_tp.pause();
}
void unpause_with_new_config() {
m_tp.unpause();
}
void close_fd() {
if (sock_fd >= 0) {
::close(sock_fd);
sock_fd = -1;
}
}
}; /* RGWProcess */
class RGWProcessControlThread : public Thread {
RGWProcess *pprocess;
public:
explicit RGWProcessControlThread(RGWProcess *_pprocess) : pprocess(_pprocess) {}
void *entry() override {
pprocess->run();
return NULL;
}
};
class RGWLoadGenProcess : public RGWProcess {
RGWAccessKey access_key;
public:
RGWLoadGenProcess(CephContext* cct, RGWProcessEnv& env, int num_threads,
std::string uri_prefix, RGWFrontendConfig* _conf)
: RGWProcess(cct, env, num_threads, std::move(uri_prefix), _conf) {}
void run() override;
void checkpoint();
void handle_request(const DoutPrefixProvider *dpp, RGWRequest* req) override;
void gen_request(const std::string& method, const std::string& resource,
int content_length, std::atomic<bool>* fail_flag);
void set_access_key(RGWAccessKey& key) { access_key = key; }
};
/* process stream request */
extern int process_request(const RGWProcessEnv& penv,
RGWRequest* req,
const std::string& frontend_prefix,
RGWRestfulIO* client_io,
optional_yield y,
rgw::dmclock::Scheduler *scheduler,
std::string* user,
ceph::coarse_real_clock::duration* latency,
int* http_ret = nullptr);
extern int rgw_process_authenticated(RGWHandler_REST* handler,
RGWOp*& op,
RGWRequest* req,
req_state* s,
optional_yield y,
rgw::sal::Driver* driver,
bool skip_retarget = false);
#undef dout_context
| 4,523 | 27.275 | 96 |
h
|
null |
ceph-main/src/rgw/rgw_process_env.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 <memory>
class ActiveRateLimiter;
class OpsLogSink;
class RGWREST;
namespace rgw {
class SiteConfig;
}
namespace rgw::auth {
class StrategyRegistry;
}
namespace rgw::lua {
class Background;
}
namespace rgw::sal {
class ConfigStore;
class Driver;
class LuaManager;
}
#ifdef WITH_ARROW_FLIGHT
namespace rgw::flight {
class FlightServer;
class FlightStore;
}
#endif
struct RGWLuaProcessEnv {
std::string luarocks_path;
rgw::lua::Background* background = nullptr;
std::unique_ptr<rgw::sal::LuaManager> manager;
};
struct RGWProcessEnv {
RGWLuaProcessEnv lua;
rgw::sal::ConfigStore* cfgstore = nullptr;
rgw::sal::Driver* driver = nullptr;
rgw::SiteConfig* site = nullptr;
RGWREST *rest = nullptr;
OpsLogSink *olog = nullptr;
std::unique_ptr<rgw::auth::StrategyRegistry> auth_registry;
ActiveRateLimiter* ratelimiting = nullptr;
#ifdef WITH_ARROW_FLIGHT
// managed by rgw:flight::FlightFrontend in rgw_flight_frontend.cc
rgw::flight::FlightServer* flight_server = nullptr;
rgw::flight::FlightStore* flight_store = nullptr;
#endif
};
| 1,207 | 20.192982 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_public_access.cc
|
#include "rgw_public_access.h"
#include "rgw_xml.h"
void PublicAccessBlockConfiguration::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("BlockPublicAcls", BlockPublicAcls, obj);
RGWXMLDecoder::decode_xml("IgnorePublicAcls", IgnorePublicAcls, obj);
RGWXMLDecoder::decode_xml("BlockPublicPolicy", BlockPublicPolicy, obj);
RGWXMLDecoder::decode_xml("RestrictPublicBuckets", RestrictPublicBuckets, obj);
}
void PublicAccessBlockConfiguration::dump_xml(Formatter *f) const {
Formatter::ObjectSection os(*f, "BlockPublicAccessBlockConfiguration");
// Note: AWS spec mentions the values to be ALL CAPs, but clients seem to
// require all small letters, and S3 itself doesn't seem to follow the API
// spec here
f->dump_bool("BlockPublicAcls", BlockPublicAcls);
f->dump_bool("IgnorePublicAcls", IgnorePublicAcls);
f->dump_bool("BlockPublicPolicy", BlockPublicPolicy);
f->dump_bool("RestrictPublicBuckets", RestrictPublicBuckets);
}
std::ostream& operator<< (std::ostream& os, const PublicAccessBlockConfiguration& access_conf)
{
os << std::boolalpha
<< "BlockPublicAcls: " << access_conf.block_public_acls() << std::endl
<< "IgnorePublicAcls: " << access_conf.ignore_public_acls() << std::endl
<< "BlockPublicPolicy" << access_conf.block_public_policy() << std::endl
<< "RestrictPublicBuckets" << access_conf.restrict_public_buckets() << std::endl;
return os;
}
| 1,425 | 40.941176 | 94 |
cc
|
null |
ceph-main/src/rgw/rgw_public_access.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 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 <include/types.h>
class XMLObj;
class PublicAccessBlockConfiguration {
bool BlockPublicAcls;
bool IgnorePublicAcls;
bool BlockPublicPolicy;
bool RestrictPublicBuckets;
public:
PublicAccessBlockConfiguration():
BlockPublicAcls(false), IgnorePublicAcls(false),
BlockPublicPolicy(false), RestrictPublicBuckets(false)
{}
auto block_public_acls() const {
return BlockPublicAcls;
}
auto ignore_public_acls() const {
return IgnorePublicAcls;
}
auto block_public_policy() const {
return BlockPublicPolicy;
}
auto restrict_public_buckets() const {
return RestrictPublicBuckets;
}
void encode(ceph::bufferlist& bl) const {
ENCODE_START(1,1, bl);
encode(BlockPublicAcls, bl);
encode(IgnorePublicAcls, bl);
encode(BlockPublicPolicy, bl);
encode(RestrictPublicBuckets, bl);
ENCODE_FINISH(bl);
}
void decode(ceph::bufferlist::const_iterator& bl) {
DECODE_START(1,bl);
decode(BlockPublicAcls, bl);
decode(IgnorePublicAcls, bl);
decode(BlockPublicPolicy, bl);
decode(RestrictPublicBuckets, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(PublicAccessBlockConfiguration)
std::ostream& operator<< (std::ostream& os, const PublicAccessBlockConfiguration& access_conf);
| 1,762 | 24.926471 | 95 |
h
|
null |
ceph-main/src/rgw/rgw_pubsub.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "services/svc_zone.h"
#include "rgw_b64.h"
#include "rgw_sal.h"
#include "rgw_pubsub.h"
#include "rgw_tools.h"
#include "rgw_xml.h"
#include "rgw_arn.h"
#include "rgw_pubsub_push.h"
#include <regex>
#include <algorithm>
#define dout_subsys ceph_subsys_rgw
void set_event_id(std::string& id, const std::string& hash, const utime_t& ts) {
char buf[64];
const auto len = snprintf(buf, sizeof(buf), "%010ld.%06ld.%s", (long)ts.sec(), (long)ts.usec(), hash.c_str());
if (len > 0) {
id.assign(buf, len);
}
}
void rgw_s3_key_filter::dump(Formatter *f) const {
if (!prefix_rule.empty()) {
f->open_object_section("FilterRule");
::encode_json("Name", "prefix", f);
::encode_json("Value", prefix_rule, f);
f->close_section();
}
if (!suffix_rule.empty()) {
f->open_object_section("FilterRule");
::encode_json("Name", "suffix", f);
::encode_json("Value", suffix_rule, f);
f->close_section();
}
if (!regex_rule.empty()) {
f->open_object_section("FilterRule");
::encode_json("Name", "regex", f);
::encode_json("Value", regex_rule, f);
f->close_section();
}
}
bool rgw_s3_key_filter::decode_xml(XMLObj* obj) {
XMLObjIter iter = obj->find("FilterRule");
XMLObj *o;
const auto throw_if_missing = true;
auto prefix_not_set = true;
auto suffix_not_set = true;
auto regex_not_set = true;
std::string name;
while ((o = iter.get_next())) {
RGWXMLDecoder::decode_xml("Name", name, o, throw_if_missing);
if (name == "prefix" && prefix_not_set) {
prefix_not_set = false;
RGWXMLDecoder::decode_xml("Value", prefix_rule, o, throw_if_missing);
} else if (name == "suffix" && suffix_not_set) {
suffix_not_set = false;
RGWXMLDecoder::decode_xml("Value", suffix_rule, o, throw_if_missing);
} else if (name == "regex" && regex_not_set) {
regex_not_set = false;
RGWXMLDecoder::decode_xml("Value", regex_rule, o, throw_if_missing);
} else {
throw RGWXMLDecoder::err("invalid/duplicate S3Key filter rule name: '" + name + "'");
}
}
return true;
}
void rgw_s3_key_filter::dump_xml(Formatter *f) const {
if (!prefix_rule.empty()) {
f->open_object_section("FilterRule");
::encode_xml("Name", "prefix", f);
::encode_xml("Value", prefix_rule, f);
f->close_section();
}
if (!suffix_rule.empty()) {
f->open_object_section("FilterRule");
::encode_xml("Name", "suffix", f);
::encode_xml("Value", suffix_rule, f);
f->close_section();
}
if (!regex_rule.empty()) {
f->open_object_section("FilterRule");
::encode_xml("Name", "regex", f);
::encode_xml("Value", regex_rule, f);
f->close_section();
}
}
bool rgw_s3_key_filter::has_content() const {
return !(prefix_rule.empty() && suffix_rule.empty() && regex_rule.empty());
}
void rgw_s3_key_value_filter::dump(Formatter *f) const {
for (const auto& key_value : kv) {
f->open_object_section("FilterRule");
::encode_json("Name", key_value.first, f);
::encode_json("Value", key_value.second, f);
f->close_section();
}
}
bool rgw_s3_key_value_filter::decode_xml(XMLObj* obj) {
kv.clear();
XMLObjIter iter = obj->find("FilterRule");
XMLObj *o;
const auto throw_if_missing = true;
std::string key;
std::string value;
while ((o = iter.get_next())) {
RGWXMLDecoder::decode_xml("Name", key, o, throw_if_missing);
RGWXMLDecoder::decode_xml("Value", value, o, throw_if_missing);
kv.emplace(key, value);
}
return true;
}
void rgw_s3_key_value_filter::dump_xml(Formatter *f) const {
for (const auto& key_value : kv) {
f->open_object_section("FilterRule");
::encode_xml("Name", key_value.first, f);
::encode_xml("Value", key_value.second, f);
f->close_section();
}
}
bool rgw_s3_key_value_filter::has_content() const {
return !kv.empty();
}
void rgw_s3_filter::dump(Formatter *f) const {
encode_json("S3Key", key_filter, f);
encode_json("S3Metadata", metadata_filter, f);
encode_json("S3Tags", tag_filter, f);
}
bool rgw_s3_filter::decode_xml(XMLObj* obj) {
RGWXMLDecoder::decode_xml("S3Key", key_filter, obj);
RGWXMLDecoder::decode_xml("S3Metadata", metadata_filter, obj);
RGWXMLDecoder::decode_xml("S3Tags", tag_filter, obj);
return true;
}
void rgw_s3_filter::dump_xml(Formatter *f) const {
if (key_filter.has_content()) {
::encode_xml("S3Key", key_filter, f);
}
if (metadata_filter.has_content()) {
::encode_xml("S3Metadata", metadata_filter, f);
}
if (tag_filter.has_content()) {
::encode_xml("S3Tags", tag_filter, f);
}
}
bool rgw_s3_filter::has_content() const {
return key_filter.has_content() ||
metadata_filter.has_content() ||
tag_filter.has_content();
}
bool match(const rgw_s3_key_filter& filter, const std::string& key) {
const auto key_size = key.size();
const auto prefix_size = filter.prefix_rule.size();
if (prefix_size != 0) {
// prefix rule exists
if (prefix_size > key_size) {
// if prefix is longer than key, we fail
return false;
}
if (!std::equal(filter.prefix_rule.begin(), filter.prefix_rule.end(), key.begin())) {
return false;
}
}
const auto suffix_size = filter.suffix_rule.size();
if (suffix_size != 0) {
// suffix rule exists
if (suffix_size > key_size) {
// if suffix is longer than key, we fail
return false;
}
if (!std::equal(filter.suffix_rule.begin(), filter.suffix_rule.end(), (key.end() - suffix_size))) {
return false;
}
}
if (!filter.regex_rule.empty()) {
// TODO add regex chaching in the filter
const std::regex base_regex(filter.regex_rule);
if (!std::regex_match(key, base_regex)) {
return false;
}
}
return true;
}
bool match(const rgw_s3_key_value_filter& filter, const KeyValueMap& kv) {
// all filter pairs must exist with the same value in the object's metadata/tags
// object metadata/tags may include items not in the filter
return std::includes(kv.begin(), kv.end(), filter.kv.begin(), filter.kv.end());
}
bool match(const rgw_s3_key_value_filter& filter, const KeyMultiValueMap& kv) {
// all filter pairs must exist with the same value in the object's metadata/tags
// object metadata/tags may include items not in the filter
for (auto& filter : filter.kv) {
auto result = kv.equal_range(filter.first);
if (std::any_of(result.first, result.second, [&filter](const std::pair<std::string, std::string>& p) { return p.second == filter.second;}))
continue;
else
return false;
}
return true;
}
bool match(const rgw::notify::EventTypeList& events, rgw::notify::EventType event) {
// if event list exists, and none of the events in the list matches the event type, filter the message
if (!events.empty() && std::find(events.begin(), events.end(), event) == events.end()) {
return false;
}
return true;
}
void do_decode_xml_obj(rgw::notify::EventTypeList& l, const std::string& name, XMLObj *obj) {
l.clear();
XMLObjIter iter = obj->find(name);
XMLObj *o;
while ((o = iter.get_next())) {
std::string val;
decode_xml_obj(val, o);
l.push_back(rgw::notify::from_string(val));
}
}
bool rgw_pubsub_s3_notification::decode_xml(XMLObj *obj) {
const auto throw_if_missing = true;
RGWXMLDecoder::decode_xml("Id", id, obj, throw_if_missing);
RGWXMLDecoder::decode_xml("Topic", topic_arn, obj, throw_if_missing);
RGWXMLDecoder::decode_xml("Filter", filter, obj);
do_decode_xml_obj(events, "Event", obj);
if (events.empty()) {
// if no events are provided, we assume all events
events.push_back(rgw::notify::ObjectCreated);
events.push_back(rgw::notify::ObjectRemoved);
}
return true;
}
void rgw_pubsub_s3_notification::dump_xml(Formatter *f) const {
::encode_xml("Id", id, f);
::encode_xml("Topic", topic_arn.c_str(), f);
if (filter.has_content()) {
::encode_xml("Filter", filter, f);
}
for (const auto& event : events) {
::encode_xml("Event", rgw::notify::to_string(event), f);
}
}
bool rgw_pubsub_s3_notifications::decode_xml(XMLObj *obj) {
do_decode_xml_obj(list, "TopicConfiguration", obj);
return true;
}
rgw_pubsub_s3_notification::rgw_pubsub_s3_notification(const rgw_pubsub_topic_filter& topic_filter) :
id(topic_filter.s3_id), events(topic_filter.events), topic_arn(topic_filter.topic.arn), filter(topic_filter.s3_filter) {}
void rgw_pubsub_s3_notifications::dump_xml(Formatter *f) const {
do_encode_xml("NotificationConfiguration", list, "TopicConfiguration", f);
}
void rgw_pubsub_s3_event::dump(Formatter *f) const {
encode_json("eventVersion", eventVersion, f);
encode_json("eventSource", eventSource, f);
encode_json("awsRegion", awsRegion, f);
utime_t ut(eventTime);
encode_json("eventTime", ut, f);
encode_json("eventName", eventName, f);
{
Formatter::ObjectSection s(*f, "userIdentity");
encode_json("principalId", userIdentity, f);
}
{
Formatter::ObjectSection s(*f, "requestParameters");
encode_json("sourceIPAddress", sourceIPAddress, f);
}
{
Formatter::ObjectSection s(*f, "responseElements");
encode_json("x-amz-request-id", x_amz_request_id, f);
encode_json("x-amz-id-2", x_amz_id_2, f);
}
{
Formatter::ObjectSection s(*f, "s3");
encode_json("s3SchemaVersion", s3SchemaVersion, f);
encode_json("configurationId", configurationId, f);
{
Formatter::ObjectSection sub_s(*f, "bucket");
encode_json("name", bucket_name, f);
{
Formatter::ObjectSection sub_sub_s(*f, "ownerIdentity");
encode_json("principalId", bucket_ownerIdentity, f);
}
encode_json("arn", bucket_arn, f);
encode_json("id", bucket_id, f);
}
{
Formatter::ObjectSection sub_s(*f, "object");
encode_json("key", object_key, f);
encode_json("size", object_size, f);
encode_json("eTag", object_etag, f);
encode_json("versionId", object_versionId, f);
encode_json("sequencer", object_sequencer, f);
encode_json("metadata", x_meta_map, f);
encode_json("tags", tags, f);
}
}
encode_json("eventId", id, f);
encode_json("opaqueData", opaque_data, f);
}
void rgw_pubsub_topic::dump(Formatter *f) const
{
encode_json("user", user, f);
encode_json("name", name, f);
encode_json("dest", dest, f);
encode_json("arn", arn, f);
encode_json("opaqueData", opaque_data, f);
}
void rgw_pubsub_topic::dump_xml(Formatter *f) const
{
encode_xml("User", user, f);
encode_xml("Name", name, f);
encode_xml("EndPoint", dest, f);
encode_xml("TopicArn", arn, f);
encode_xml("OpaqueData", opaque_data, f);
}
void encode_xml_key_value_entry(const std::string& key, const std::string& value, Formatter *f) {
f->open_object_section("entry");
encode_xml("key", key, f);
encode_xml("value", value, f);
f->close_section(); // entry
}
void rgw_pubsub_topic::dump_xml_as_attributes(Formatter *f) const
{
f->open_array_section("Attributes");
std::string str_user;
user.to_str(str_user);
encode_xml_key_value_entry("User", str_user, f);
encode_xml_key_value_entry("Name", name, f);
encode_xml_key_value_entry("EndPoint", dest.to_json_str(), f);
encode_xml_key_value_entry("TopicArn", arn, f);
encode_xml_key_value_entry("OpaqueData", opaque_data, f);
f->close_section(); // Attributes
}
void encode_json(const char *name, const rgw::notify::EventTypeList& l, Formatter *f)
{
f->open_array_section(name);
for (auto iter = l.cbegin(); iter != l.cend(); ++iter) {
f->dump_string("obj", rgw::notify::to_string(*iter));
}
f->close_section();
}
void rgw_pubsub_topic_filter::dump(Formatter *f) const
{
encode_json("TopicArn", topic.arn, f);
encode_json("Id", s3_id, f);
encode_json("Events", events, f);
encode_json("Filter", s3_filter, f);
}
void rgw_pubsub_bucket_topics::dump(Formatter *f) const
{
Formatter::ArraySection s(*f, "notifications");
for (auto& t : topics) {
encode_json(t.first.c_str(), t.second, f);
}
}
void rgw_pubsub_topics::dump(Formatter *f) const
{
Formatter::ArraySection s(*f, "topics");
for (auto& t : topics) {
auto& topic = t.second;
if (topic.name == topic.dest.arn_topic) {
encode_json(t.first.c_str(), topic, f);
}
}
}
void rgw_pubsub_topics::dump_xml(Formatter *f) const
{
for (auto& t : topics) {
encode_xml("member", t.second, f);
}
}
void rgw_pubsub_dest::dump(Formatter *f) const
{
encode_json("push_endpoint", push_endpoint, f);
encode_json("push_endpoint_args", push_endpoint_args, f);
encode_json("push_endpoint_topic", arn_topic, f);
encode_json("stored_secret", stored_secret, f);
encode_json("persistent", persistent, f);
}
void rgw_pubsub_dest::dump_xml(Formatter *f) const
{
encode_xml("EndpointAddress", push_endpoint, f);
encode_xml("EndpointArgs", push_endpoint_args, f);
encode_xml("EndpointTopic", arn_topic, f);
encode_xml("HasStoredSecret", stored_secret, f);
encode_xml("Persistent", persistent, f);
}
std::string rgw_pubsub_dest::to_json_str() const
{
JSONFormatter f;
f.open_object_section("");
encode_json("EndpointAddress", push_endpoint, &f);
encode_json("EndpointArgs", push_endpoint_args, &f);
encode_json("EndpointTopic", arn_topic, &f);
encode_json("HasStoredSecret", stored_secret, &f);
encode_json("Persistent", persistent, &f);
f.close_section();
std::stringstream ss;
f.flush(ss);
return ss.str();
}
RGWPubSub::RGWPubSub(rgw::sal::Driver* _driver, const std::string& _tenant)
: driver(_driver), tenant(_tenant)
{}
int RGWPubSub::read_topics(const DoutPrefixProvider *dpp, rgw_pubsub_topics& result,
RGWObjVersionTracker *objv_tracker, optional_yield y) const
{
const int ret = driver->read_topics(tenant, result, objv_tracker, y, dpp);
if (ret < 0) {
ldpp_dout(dpp, 10) << "WARNING: failed to read topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::write_topics(const DoutPrefixProvider *dpp, const rgw_pubsub_topics& topics,
RGWObjVersionTracker *objv_tracker, optional_yield y) const
{
const int ret = driver->write_topics(tenant, topics, objv_tracker, y, dpp);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 1) << "ERROR: failed to write topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::Bucket::read_topics(const DoutPrefixProvider *dpp, rgw_pubsub_bucket_topics& result,
RGWObjVersionTracker *objv_tracker, optional_yield y) const
{
const int ret = bucket->read_topics(result, objv_tracker, y, dpp);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 1) << "ERROR: failed to read bucket topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::Bucket::write_topics(const DoutPrefixProvider *dpp, const rgw_pubsub_bucket_topics& topics,
RGWObjVersionTracker *objv_tracker,
optional_yield y) const
{
const int ret = bucket->write_topics(topics, objv_tracker, y, dpp);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to write bucket topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::get_topic(const DoutPrefixProvider *dpp, const std::string& name, rgw_pubsub_topic& result, optional_yield y) const
{
rgw_pubsub_topics topics;
const int ret = read_topics(dpp, topics, nullptr, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to read topics info: ret=" << ret << dendl;
return ret;
}
auto iter = topics.topics.find(name);
if (iter == topics.topics.end()) {
ldpp_dout(dpp, 1) << "ERROR: topic not found" << dendl;
return -ENOENT;
}
result = iter->second;
return 0;
}
// from list of bucket topics, find the one that was auto-generated by a notification
auto find_unique_topic(const rgw_pubsub_bucket_topics &bucket_topics, const std::string ¬ification_id) {
auto it = std::find_if(bucket_topics.topics.begin(), bucket_topics.topics.end(),
[&](const auto& val) { return notification_id == val.second.s3_id; });
return it != bucket_topics.topics.end() ?
std::optional<std::reference_wrapper<const rgw_pubsub_topic_filter>>(it->second):
std::nullopt;
}
int RGWPubSub::Bucket::get_notification_by_id(const DoutPrefixProvider *dpp, const std::string& notification_id,
rgw_pubsub_topic_filter& result, optional_yield y) const {
rgw_pubsub_bucket_topics bucket_topics;
const int ret = read_topics(dpp, bucket_topics, nullptr, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to read bucket_topics info: ret=" << ret << dendl;
return ret;
}
auto iter = find_unique_topic(bucket_topics, notification_id);
if (!iter) {
ldpp_dout(dpp, 1) << "ERROR: notification was not found" << dendl;
return -ENOENT;
}
result = iter->get();
return 0;
}
int RGWPubSub::Bucket::create_notification(const DoutPrefixProvider *dpp, const std::string& topic_name,
const rgw::notify::EventTypeList& events, optional_yield y) const {
return create_notification(dpp, topic_name, events, std::nullopt, "", y);
}
int RGWPubSub::Bucket::create_notification(const DoutPrefixProvider *dpp, const std::string& topic_name,
const rgw::notify::EventTypeList& events, OptionalFilter s3_filter, const std::string& notif_name, optional_yield y) const {
rgw_pubsub_topic topic_info;
int ret = ps.get_topic(dpp, topic_name, topic_info, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to read topic '" << topic_name << "' info: ret=" << ret << dendl;
return ret;
}
ldpp_dout(dpp, 20) << "successfully read topic '" << topic_name << "' info" << dendl;
RGWObjVersionTracker objv_tracker;
rgw_pubsub_bucket_topics bucket_topics;
ret = read_topics(dpp, bucket_topics, &objv_tracker, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to read topics from bucket '" <<
bucket->get_name() << "': ret=" << ret << dendl;
return ret;
}
ldpp_dout(dpp, 20) << "successfully read " << bucket_topics.topics.size() << " topics from bucket '" <<
bucket->get_name() << "'" << dendl;
auto& topic_filter = bucket_topics.topics[topic_name];
topic_filter.topic = topic_info;
topic_filter.events = events;
topic_filter.s3_id = notif_name;
if (s3_filter) {
topic_filter.s3_filter = *s3_filter;
}
ret = write_topics(dpp, bucket_topics, &objv_tracker, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to write topics to bucket '" << bucket->get_name() << "': ret=" << ret << dendl;
return ret;
}
ldpp_dout(dpp, 20) << "successfully wrote " << bucket_topics.topics.size() << " topics to bucket '" << bucket->get_name() << "'" << dendl;
return 0;
}
int RGWPubSub::Bucket::remove_notification(const DoutPrefixProvider *dpp, const std::string& topic_name, optional_yield y) const
{
return remove_notification_inner(dpp, topic_name, false, y);
}
int RGWPubSub::Bucket::remove_notification_inner(const DoutPrefixProvider *dpp, const std::string& notification_id,
bool is_notification_id, optional_yield y) const
{
RGWObjVersionTracker objv_tracker;
rgw_pubsub_bucket_topics bucket_topics;
auto ret = read_topics(dpp, bucket_topics, &objv_tracker, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to read bucket topics info: ret=" << ret << dendl;
return ret;
}
std::unique_ptr<std::string> topic_name = std::make_unique<std::string>(notification_id);
if(is_notification_id) {
auto iter = find_unique_topic(bucket_topics, notification_id);
if (!iter) {
ldpp_dout(dpp, 1) << "ERROR: notification was not found" << dendl;
return -ENOENT;
}
topic_name = std::make_unique<std::string>(iter->get().topic.name);
}
if (bucket_topics.topics.erase(*topic_name) == 0) {
ldpp_dout(dpp, 1) << "INFO: no need to remove, topic does not exist" << dendl;
return 0;
}
if (bucket_topics.topics.empty()) {
// no more topics - delete the notification object of the bucket
ret = bucket->remove_topics(&objv_tracker, y, dpp);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 1) << "ERROR: failed to remove bucket topics: ret=" << ret << dendl;
return ret;
}
return 0;
}
// write back the notifications without the deleted one
ret = write_topics(dpp, bucket_topics, &objv_tracker, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to write topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::Bucket::remove_notification_by_id(const DoutPrefixProvider *dpp, const std::string& notif_id, optional_yield y) const
{
return remove_notification_inner(dpp, notif_id, true, y);
}
int RGWPubSub::Bucket::remove_notifications(const DoutPrefixProvider *dpp, optional_yield y) const
{
// get all topics on a bucket
rgw_pubsub_bucket_topics bucket_topics;
auto ret = get_topics(dpp, bucket_topics, y);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 1) << "ERROR: failed to get list of topics from bucket '" << bucket->get_name() << "', ret=" << ret << dendl;
return ret ;
}
// remove all auto-genrated topics
for (const auto& topic : bucket_topics.topics) {
const auto& topic_name = topic.first;
ret = ps.remove_topic(dpp, topic_name, y);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 5) << "WARNING: failed to remove auto-generated topic '" << topic_name << "', ret=" << ret << dendl;
}
}
// delete the notification object of the bucket
ret = bucket->remove_topics(nullptr, y, dpp);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 1) << "ERROR: failed to remove bucket topics: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::create_topic(const DoutPrefixProvider *dpp, const std::string& name, optional_yield y) const {
return create_topic(dpp, name, rgw_pubsub_dest{}, "", "", y);
}
int RGWPubSub::create_topic(const DoutPrefixProvider *dpp, const std::string& name, const rgw_pubsub_dest& dest,
const std::string& arn, const std::string& opaque_data, optional_yield y) const {
RGWObjVersionTracker objv_tracker;
rgw_pubsub_topics topics;
int ret = read_topics(dpp, topics, &objv_tracker, y);
if (ret < 0 && ret != -ENOENT) {
// its not an error if not topics exist, we create one
ldpp_dout(dpp, 1) << "ERROR: failed to read topics info: ret=" << ret << dendl;
return ret;
}
rgw_pubsub_topic& new_topic = topics.topics[name];
new_topic.user = rgw_user("", tenant);
new_topic.name = name;
new_topic.dest = dest;
new_topic.arn = arn;
new_topic.opaque_data = opaque_data;
ret = write_topics(dpp, topics, &objv_tracker, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to write topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWPubSub::remove_topic(const DoutPrefixProvider *dpp, const std::string& name, optional_yield y) const
{
RGWObjVersionTracker objv_tracker;
rgw_pubsub_topics topics;
int ret = read_topics(dpp, topics, &objv_tracker, y);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 1) << "ERROR: failed to read topics info: ret=" << ret << dendl;
return ret;
} else if (ret == -ENOENT) {
// its not an error if no topics exist, just a no-op
ldpp_dout(dpp, 10) << "WARNING: failed to read topics info, deletion is a no-op: ret=" << ret << dendl;
return 0;
}
topics.topics.erase(name);
ret = write_topics(dpp, topics, &objv_tracker, y);
if (ret < 0) {
ldpp_dout(dpp, 1) << "ERROR: failed to remove topics info: ret=" << ret << dendl;
return ret;
}
return 0;
}
| 23,809 | 31.306649 | 143 |
cc
|
null |
ceph-main/src/rgw/rgw_pubsub.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_sal.h"
#include "rgw_tools.h"
#include "rgw_zone.h"
#include "rgw_notify_event_type.h"
#include <boost/container/flat_map.hpp>
class XMLObj;
struct rgw_s3_key_filter {
std::string prefix_rule;
std::string suffix_rule;
std::string regex_rule;
bool has_content() const;
void dump(Formatter *f) const;
bool decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(prefix_rule, bl);
encode(suffix_rule, bl);
encode(regex_rule, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(prefix_rule, bl);
decode(suffix_rule, bl);
decode(regex_rule, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(rgw_s3_key_filter)
using KeyValueMap = boost::container::flat_map<std::string, std::string>;
using KeyMultiValueMap = std::multimap<std::string, std::string>;
struct rgw_s3_key_value_filter {
KeyValueMap kv;
bool has_content() const;
void dump(Formatter *f) const;
bool decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(kv, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(kv, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(rgw_s3_key_value_filter)
struct rgw_s3_filter {
rgw_s3_key_filter key_filter;
rgw_s3_key_value_filter metadata_filter;
rgw_s3_key_value_filter tag_filter;
bool has_content() const;
void dump(Formatter *f) const;
bool decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
void encode(bufferlist& bl) const {
ENCODE_START(2, 1, bl);
encode(key_filter, bl);
encode(metadata_filter, bl);
encode(tag_filter, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
decode(key_filter, bl);
decode(metadata_filter, bl);
if (struct_v >= 2) {
decode(tag_filter, bl);
}
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(rgw_s3_filter)
using OptionalFilter = std::optional<rgw_s3_filter>;
struct rgw_pubsub_topic_filter;
/* S3 notification configuration
* based on: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html
<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<TopicConfiguration>
<Filter>
<S3Key>
<FilterRule>
<Name>suffix</Name>
<Value>jpg</Value>
</FilterRule>
</S3Key>
<S3Metadata>
<FilterRule>
<Name></Name>
<Value></Value>
</FilterRule>
</S3Metadata>
<S3Tags>
<FilterRule>
<Name></Name>
<Value></Value>
</FilterRule>
</S3Tags>
</Filter>
<Id>notification1</Id>
<Topic>arn:aws:sns:<region>:<account>:<topic></Topic>
<Event>s3:ObjectCreated:*</Event>
<Event>s3:ObjectRemoved:*</Event>
</TopicConfiguration>
</NotificationConfiguration>
*/
struct rgw_pubsub_s3_notification {
// notification id
std::string id;
// types of events
rgw::notify::EventTypeList events;
// topic ARN
std::string topic_arn;
// filter rules
rgw_s3_filter filter;
bool decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
rgw_pubsub_s3_notification() = default;
// construct from rgw_pubsub_topic_filter (used by get/list notifications)
explicit rgw_pubsub_s3_notification(const rgw_pubsub_topic_filter& topic_filter);
};
// return true if the key matches the prefix/suffix/regex rules of the key filter
bool match(const rgw_s3_key_filter& filter, const std::string& key);
// return true if the key matches the metadata rules of the metadata filter
bool match(const rgw_s3_key_value_filter& filter, const KeyValueMap& kv);
// return true if the key matches the tag rules of the tag filter
bool match(const rgw_s3_key_value_filter& filter, const KeyMultiValueMap& kv);
// return true if the event type matches (equal or contained in) one of the events in the list
bool match(const rgw::notify::EventTypeList& events, rgw::notify::EventType event);
struct rgw_pubsub_s3_notifications {
std::list<rgw_pubsub_s3_notification> list;
bool decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
/* S3 event records structure
* based on: https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html
{
"Records":[
{
"eventVersion":""
"eventSource":"",
"awsRegion":"",
"eventTime":"",
"eventName":"",
"userIdentity":{
"principalId":""
},
"requestParameters":{
"sourceIPAddress":""
},
"responseElements":{
"x-amz-request-id":"",
"x-amz-id-2":""
},
"s3":{
"s3SchemaVersion":"1.0",
"configurationId":"",
"bucket":{
"name":"",
"ownerIdentity":{
"principalId":""
},
"arn":""
"id": ""
},
"object":{
"key":"",
"size": ,
"eTag":"",
"versionId":"",
"sequencer": "",
"metadata": ""
"tags": ""
}
},
"eventId":"",
}
]
}*/
struct rgw_pubsub_s3_event {
constexpr static const char* const json_type_plural = "Records";
std::string eventVersion = "2.2";
// aws:s3
std::string eventSource = "ceph:s3";
// zonegroup
std::string awsRegion;
// time of the request
ceph::real_time eventTime;
// type of the event
std::string eventName;
// user that sent the request
std::string userIdentity;
// IP address of source of the request (not implemented)
std::string sourceIPAddress;
// request ID (not implemented)
std::string x_amz_request_id;
// radosgw that received the request
std::string x_amz_id_2;
std::string s3SchemaVersion = "1.0";
// ID received in the notification request
std::string configurationId;
// bucket name
std::string bucket_name;
// bucket owner
std::string bucket_ownerIdentity;
// bucket ARN
std::string bucket_arn;
// object key
std::string object_key;
// object size
uint64_t object_size = 0;
// object etag
std::string object_etag;
// object version id bucket is versioned
std::string object_versionId;
// hexadecimal value used to determine event order for specific key
std::string object_sequencer;
// this is an rgw extension (not S3 standard)
// used to store a globally unique identifier of the event
// that could be used for acking or any other identification of the event
std::string id;
// this is an rgw extension holding the internal bucket id
std::string bucket_id;
// meta data
KeyValueMap x_meta_map;
// tags
KeyMultiValueMap tags;
// opaque data received from the topic
// could be used to identify the gateway
std::string opaque_data;
void encode(bufferlist& bl) const {
ENCODE_START(4, 1, bl);
encode(eventVersion, bl);
encode(eventSource, bl);
encode(awsRegion, bl);
encode(eventTime, bl);
encode(eventName, bl);
encode(userIdentity, bl);
encode(sourceIPAddress, bl);
encode(x_amz_request_id, bl);
encode(x_amz_id_2, bl);
encode(s3SchemaVersion, bl);
encode(configurationId, bl);
encode(bucket_name, bl);
encode(bucket_ownerIdentity, bl);
encode(bucket_arn, bl);
encode(object_key, bl);
encode(object_size, bl);
encode(object_etag, bl);
encode(object_versionId, bl);
encode(object_sequencer, bl);
encode(id, bl);
encode(bucket_id, bl);
encode(x_meta_map, bl);
encode(tags, bl);
encode(opaque_data, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(4, bl);
decode(eventVersion, bl);
decode(eventSource, bl);
decode(awsRegion, bl);
decode(eventTime, bl);
decode(eventName, bl);
decode(userIdentity, bl);
decode(sourceIPAddress, bl);
decode(x_amz_request_id, bl);
decode(x_amz_id_2, bl);
decode(s3SchemaVersion, bl);
decode(configurationId, bl);
decode(bucket_name, bl);
decode(bucket_ownerIdentity, bl);
decode(bucket_arn, bl);
decode(object_key, bl);
decode(object_size, bl);
decode(object_etag, bl);
decode(object_versionId, bl);
decode(object_sequencer, bl);
decode(id, bl);
if (struct_v >= 2) {
decode(bucket_id, bl);
decode(x_meta_map, bl);
}
if (struct_v >= 3) {
decode(tags, bl);
}
if (struct_v >= 4) {
decode(opaque_data, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(rgw_pubsub_s3_event)
// setting a unique ID for an event based on object hash and timestamp
void set_event_id(std::string& id, const std::string& hash, const utime_t& ts);
struct rgw_pubsub_dest {
std::string push_endpoint;
std::string push_endpoint_args;
std::string arn_topic;
bool stored_secret = false;
bool persistent = false;
void encode(bufferlist& bl) const {
ENCODE_START(5, 1, bl);
encode("", bl);
encode("", bl);
encode(push_endpoint, bl);
encode(push_endpoint_args, bl);
encode(arn_topic, bl);
encode(stored_secret, bl);
encode(persistent, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(5, bl);
std::string dummy;
decode(dummy, bl);
decode(dummy, bl);
decode(push_endpoint, bl);
if (struct_v >= 2) {
decode(push_endpoint_args, bl);
}
if (struct_v >= 3) {
decode(arn_topic, bl);
}
if (struct_v >= 4) {
decode(stored_secret, bl);
}
if (struct_v >= 5) {
decode(persistent, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void dump_xml(Formatter *f) const;
std::string to_json_str() const;
};
WRITE_CLASS_ENCODER(rgw_pubsub_dest)
struct rgw_pubsub_topic {
rgw_user user;
std::string name;
rgw_pubsub_dest dest;
std::string arn;
std::string opaque_data;
void encode(bufferlist& bl) const {
ENCODE_START(3, 1, bl);
encode(user, bl);
encode(name, bl);
encode(dest, bl);
encode(arn, bl);
encode(opaque_data, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(3, bl);
decode(user, bl);
decode(name, bl);
if (struct_v >= 2) {
decode(dest, bl);
decode(arn, bl);
}
if (struct_v >= 3) {
decode(opaque_data, bl);
}
DECODE_FINISH(bl);
}
std::string to_str() const {
return user.tenant + "/" + name;
}
void dump(Formatter *f) const;
void dump_xml(Formatter *f) const;
void dump_xml_as_attributes(Formatter *f) const;
bool operator<(const rgw_pubsub_topic& t) const {
return to_str().compare(t.to_str());
}
};
WRITE_CLASS_ENCODER(rgw_pubsub_topic)
// this struct deprecated and remain only for backward compatibility
struct rgw_pubsub_topic_subs {
rgw_pubsub_topic topic;
std::set<std::string> subs;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(topic, bl);
encode(subs, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(topic, bl);
decode(subs, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(rgw_pubsub_topic_subs)
struct rgw_pubsub_topic_filter {
rgw_pubsub_topic topic;
rgw::notify::EventTypeList events;
std::string s3_id;
rgw_s3_filter s3_filter;
void encode(bufferlist& bl) const {
ENCODE_START(3, 1, bl);
encode(topic, bl);
// events are stored as a vector of std::strings
std::vector<std::string> tmp_events;
std::transform(events.begin(), events.end(), std::back_inserter(tmp_events), rgw::notify::to_string);
encode(tmp_events, bl);
encode(s3_id, bl);
encode(s3_filter, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(3, bl);
decode(topic, bl);
// events are stored as a vector of std::strings
events.clear();
std::vector<std::string> tmp_events;
decode(tmp_events, bl);
std::transform(tmp_events.begin(), tmp_events.end(), std::back_inserter(events), rgw::notify::from_string);
if (struct_v >= 2) {
decode(s3_id, bl);
}
if (struct_v >= 3) {
decode(s3_filter, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(rgw_pubsub_topic_filter)
struct rgw_pubsub_bucket_topics {
std::map<std::string, rgw_pubsub_topic_filter> topics;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(topics, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(topics, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
};
WRITE_CLASS_ENCODER(rgw_pubsub_bucket_topics)
struct rgw_pubsub_topics {
std::map<std::string, rgw_pubsub_topic> topics;
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(topics, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(2, bl);
if (struct_v >= 2) {
decode(topics, bl);
} else {
std::map<std::string, rgw_pubsub_topic_subs> v1topics;
decode(v1topics, bl);
std::transform(v1topics.begin(), v1topics.end(), std::inserter(topics, topics.end()),
[](const auto& entry) {
return std::pair<std::string, rgw_pubsub_topic>(entry.first, entry.second.topic);
});
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(rgw_pubsub_topics)
class RGWPubSub
{
friend class Bucket;
rgw::sal::Driver* const driver;
const std::string tenant;
int read_topics(const DoutPrefixProvider *dpp, rgw_pubsub_topics& result,
RGWObjVersionTracker* objv_tracker, optional_yield y) const;
int write_topics(const DoutPrefixProvider *dpp, const rgw_pubsub_topics& topics,
RGWObjVersionTracker* objv_tracker, optional_yield y) const;
public:
RGWPubSub(rgw::sal::Driver* _driver, const std::string& tenant);
class Bucket {
friend class RGWPubSub;
const RGWPubSub& ps;
rgw::sal::Bucket* const bucket;
// read the list of topics associated with a bucket and populate into result
// use version tacker to enforce atomicity between read/write
// return 0 on success or if no topic was associated with the bucket, error code otherwise
int read_topics(const DoutPrefixProvider *dpp, rgw_pubsub_bucket_topics& result,
RGWObjVersionTracker* objv_tracker, optional_yield y) const;
// set the list of topics associated with a bucket
// use version tacker to enforce atomicity between read/write
// return 0 on success, error code otherwise
int write_topics(const DoutPrefixProvider *dpp, const rgw_pubsub_bucket_topics& topics,
RGWObjVersionTracker* objv_tracker, optional_yield y) const;
int remove_notification_inner(const DoutPrefixProvider *dpp, const std::string& notification_id,
bool notif_id_or_topic, optional_yield y) const;
public:
Bucket(const RGWPubSub& _ps, rgw::sal::Bucket* _bucket) :
ps(_ps), bucket(_bucket)
{}
// get the list of topics associated with a bucket and populate into result
// return 0 on success or if no topic was associated with the bucket, error code otherwise
int get_topics(const DoutPrefixProvider *dpp, rgw_pubsub_bucket_topics& result, optional_yield y) const {
return read_topics(dpp, result, nullptr, y);
}
// get a bucket_topic with by its name and populate it into "result"
// return -ENOENT if the topic does not exists
// return 0 on success, error code otherwise
int get_notification_by_id(const DoutPrefixProvider *dpp, const std::string& notification_id, rgw_pubsub_topic_filter& result, optional_yield y) const;
// adds a topic + filter (event list, and possibly name metadata or tags filters) to a bucket
// assigning a notification name is optional (needed for S3 compatible notifications)
// if the topic already exist on the bucket, the filter event list may be updated
// for S3 compliant notifications the version with: s3_filter and notif_name should be used
// return -ENOENT if the topic does not exists
// return 0 on success, error code otherwise
int create_notification(const DoutPrefixProvider *dpp, const std::string& topic_name,
const rgw::notify::EventTypeList& events, optional_yield y) const;
int create_notification(const DoutPrefixProvider *dpp, const std::string& topic_name,
const rgw::notify::EventTypeList& events, OptionalFilter s3_filter, const std::string& notif_name, optional_yield y) const;
// remove a topic and filter from bucket
// if the topic does not exists on the bucket it is a no-op (considered success)
// return -ENOENT if the notification-id/topic does not exists
// return 0 on success, error code otherwise
int remove_notification_by_id(const DoutPrefixProvider *dpp, const std::string& notif_id, optional_yield y) const;
int remove_notification(const DoutPrefixProvider *dpp, const std::string& topic_name, optional_yield y) const;
// remove all notifications (and autogenerated topics) associated with the bucket
// return 0 on success or if no topic was associated with the bucket, error code otherwise
int remove_notifications(const DoutPrefixProvider *dpp, optional_yield y) const;
};
// get the list of topics
// return 0 on success or if no topic was associated with the bucket, error code otherwise
int get_topics(const DoutPrefixProvider *dpp, rgw_pubsub_topics& result, optional_yield y) const {
return read_topics(dpp, result, nullptr, y);
}
// get a topic with by its name and populate it into "result"
// return -ENOENT if the topic does not exists
// return 0 on success, error code otherwise
int get_topic(const DoutPrefixProvider *dpp, const std::string& name, rgw_pubsub_topic& result, optional_yield y) const;
// create a topic with a name only
// if the topic already exists it is a no-op (considered success)
// return 0 on success, error code otherwise
int create_topic(const DoutPrefixProvider *dpp, const std::string& name, optional_yield y) const;
// create a topic with push destination information and ARN
// if the topic already exists the destination and ARN values may be updated (considered succsess)
// return 0 on success, error code otherwise
int create_topic(const DoutPrefixProvider *dpp, const std::string& name, const rgw_pubsub_dest& dest,
const std::string& arn, const std::string& opaque_data, optional_yield y) const;
// remove a topic according to its name
// if the topic does not exists it is a no-op (considered success)
// return 0 on success, error code otherwise
int remove_topic(const DoutPrefixProvider *dpp, const std::string& name, optional_yield y) const;
};
| 19,178 | 29.442857 | 155 |
h
|
null |
ceph-main/src/rgw/rgw_putobj.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) 2018 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "rgw_putobj.h"
namespace rgw::putobj {
int ChunkProcessor::process(bufferlist&& data, uint64_t offset)
{
ceph_assert(offset >= chunk.length());
uint64_t position = offset - chunk.length();
const bool flush = (data.length() == 0);
if (flush) {
if (chunk.length() > 0) {
int r = Pipe::process(std::move(chunk), position);
if (r < 0) {
return r;
}
}
return Pipe::process({}, offset);
}
chunk.claim_append(data);
// write each full chunk
while (chunk.length() >= chunk_size) {
bufferlist bl;
chunk.splice(0, chunk_size, &bl);
int r = Pipe::process(std::move(bl), position);
if (r < 0) {
return r;
}
position += chunk_size;
}
return 0;
}
int StripeProcessor::process(bufferlist&& data, uint64_t offset)
{
ceph_assert(offset >= bounds.first);
const bool flush = (data.length() == 0);
if (flush) {
return Pipe::process({}, offset - bounds.first);
}
auto max = bounds.second - offset;
while (data.length() > max) {
if (max > 0) {
bufferlist bl;
data.splice(0, max, &bl);
int r = Pipe::process(std::move(bl), offset - bounds.first);
if (r < 0) {
return r;
}
offset += max;
}
// flush the current chunk
int r = Pipe::process({}, offset - bounds.first);
if (r < 0) {
return r;
}
// generate the next stripe
uint64_t stripe_size;
r = gen->next(offset, &stripe_size);
if (r < 0) {
return r;
}
ceph_assert(stripe_size > 0);
bounds.first = offset;
bounds.second = offset + stripe_size;
max = stripe_size;
}
if (data.length() == 0) { // don't flush the chunk here
return 0;
}
return Pipe::process(std::move(data), offset - bounds.first);
}
} // namespace rgw::putobj
| 2,219 | 21.2 | 70 |
cc
|
null |
ceph-main/src/rgw/rgw_putobj.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 "include/buffer.h"
#include "rgw_sal.h"
namespace rgw::putobj {
// for composing data processors into a pipeline
class Pipe : public rgw::sal::DataProcessor {
rgw::sal::DataProcessor *next;
public:
explicit Pipe(rgw::sal::DataProcessor *next) : next(next) {}
virtual ~Pipe() override {}
// passes the data on to the next processor
int process(bufferlist&& data, uint64_t offset) override {
return next->process(std::move(data), offset);
}
};
// pipe that writes to the next processor in discrete chunks
class ChunkProcessor : public Pipe {
uint64_t chunk_size;
bufferlist chunk; // leftover bytes from the last call to process()
public:
ChunkProcessor(rgw::sal::DataProcessor *next, uint64_t chunk_size)
: Pipe(next), chunk_size(chunk_size)
{}
virtual ~ChunkProcessor() override {}
int process(bufferlist&& data, uint64_t offset) override;
};
// interface to generate the next stripe description
class StripeGenerator {
public:
virtual ~StripeGenerator() {}
virtual int next(uint64_t offset, uint64_t *stripe_size) = 0;
};
// pipe that respects stripe boundaries and restarts each stripe at offset 0
class StripeProcessor : public Pipe {
StripeGenerator *gen;
std::pair<uint64_t, uint64_t> bounds; // bounds of current stripe
public:
StripeProcessor(rgw::sal::DataProcessor *next, StripeGenerator *gen,
uint64_t first_stripe_size)
: Pipe(next), gen(gen), bounds(0, first_stripe_size)
{}
virtual ~StripeProcessor() override {}
int process(bufferlist&& data, uint64_t data_offset) override;
};
} // namespace rgw::putobj
| 2,040 | 26.581081 | 76 |
h
|
null |
ceph-main/src/rgw/rgw_quota.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 Inktank, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "include/utime.h"
#include "common/lru_map.h"
#include "common/RefCountedObj.h"
#include "common/Thread.h"
#include "common/ceph_mutex.h"
#include "rgw_common.h"
#include "rgw_sal.h"
#include "rgw_sal_rados.h"
#include "rgw_quota.h"
#include "rgw_bucket.h"
#include "rgw_user.h"
#include "services/svc_sys_obj.h"
#include "services/svc_meta.h"
#include <atomic>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
struct RGWQuotaCacheStats {
RGWStorageStats stats;
utime_t expiration;
utime_t async_refresh_time;
};
template<class T>
class RGWQuotaCache {
protected:
rgw::sal::Driver* driver;
lru_map<T, RGWQuotaCacheStats> stats_map;
RefCountedWaitObject *async_refcount;
class StatsAsyncTestSet : public lru_map<T, RGWQuotaCacheStats>::UpdateContext {
int objs_delta;
uint64_t added_bytes;
uint64_t removed_bytes;
public:
StatsAsyncTestSet() : objs_delta(0), added_bytes(0), removed_bytes(0) {}
bool update(RGWQuotaCacheStats *entry) override {
if (entry->async_refresh_time.sec() == 0)
return false;
entry->async_refresh_time = utime_t(0, 0);
return true;
}
};
virtual int fetch_stats_from_storage(const rgw_user& user, const rgw_bucket& bucket, RGWStorageStats& stats, optional_yield y, const DoutPrefixProvider *dpp) = 0;
virtual bool map_find(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs) = 0;
virtual bool map_find_and_update(const rgw_user& user, const rgw_bucket& bucket, typename lru_map<T, RGWQuotaCacheStats>::UpdateContext *ctx) = 0;
virtual void map_add(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs) = 0;
virtual void data_modified(const rgw_user& user, rgw_bucket& bucket) {}
public:
RGWQuotaCache(rgw::sal::Driver* _driver, int size) : driver(_driver), stats_map(size) {
async_refcount = new RefCountedWaitObject;
}
virtual ~RGWQuotaCache() {
async_refcount->put_wait(); /* wait for all pending async requests to complete */
}
int get_stats(const rgw_user& user, const rgw_bucket& bucket, RGWStorageStats& stats, optional_yield y,
const DoutPrefixProvider* dpp);
void adjust_stats(const rgw_user& user, rgw_bucket& bucket, int objs_delta, uint64_t added_bytes, uint64_t removed_bytes);
void set_stats(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs, RGWStorageStats& stats);
int async_refresh(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs);
void async_refresh_response(const rgw_user& user, rgw_bucket& bucket, RGWStorageStats& stats);
void async_refresh_fail(const rgw_user& user, rgw_bucket& bucket);
class AsyncRefreshHandler {
protected:
rgw::sal::Driver* driver;
RGWQuotaCache<T> *cache;
public:
AsyncRefreshHandler(rgw::sal::Driver* _driver, RGWQuotaCache<T> *_cache) : driver(_driver), cache(_cache) {}
virtual ~AsyncRefreshHandler() {}
virtual int init_fetch() = 0;
virtual void drop_reference() = 0;
};
virtual AsyncRefreshHandler *allocate_refresh_handler(const rgw_user& user, const rgw_bucket& bucket) = 0;
};
template<class T>
int RGWQuotaCache<T>::async_refresh(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs)
{
/* protect against multiple updates */
StatsAsyncTestSet test_update;
if (!map_find_and_update(user, bucket, &test_update)) {
/* most likely we just raced with another update */
return 0;
}
async_refcount->get();
AsyncRefreshHandler *handler = allocate_refresh_handler(user, bucket);
int ret = handler->init_fetch();
if (ret < 0) {
async_refcount->put();
handler->drop_reference();
return ret;
}
return 0;
}
template<class T>
void RGWQuotaCache<T>::async_refresh_fail(const rgw_user& user, rgw_bucket& bucket)
{
ldout(driver->ctx(), 20) << "async stats refresh response for bucket=" << bucket << dendl;
async_refcount->put();
}
template<class T>
void RGWQuotaCache<T>::async_refresh_response(const rgw_user& user, rgw_bucket& bucket, RGWStorageStats& stats)
{
ldout(driver->ctx(), 20) << "async stats refresh response for bucket=" << bucket << dendl;
RGWQuotaCacheStats qs;
map_find(user, bucket, qs);
set_stats(user, bucket, qs, stats);
async_refcount->put();
}
template<class T>
void RGWQuotaCache<T>::set_stats(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs, RGWStorageStats& stats)
{
qs.stats = stats;
qs.expiration = ceph_clock_now();
qs.async_refresh_time = qs.expiration;
qs.expiration += driver->ctx()->_conf->rgw_bucket_quota_ttl;
qs.async_refresh_time += driver->ctx()->_conf->rgw_bucket_quota_ttl / 2;
map_add(user, bucket, qs);
}
template<class T>
int RGWQuotaCache<T>::get_stats(const rgw_user& user, const rgw_bucket& bucket, RGWStorageStats& stats, optional_yield y, const DoutPrefixProvider* dpp) {
RGWQuotaCacheStats qs;
utime_t now = ceph_clock_now();
if (map_find(user, bucket, qs)) {
if (qs.async_refresh_time.sec() > 0 && now >= qs.async_refresh_time) {
int r = async_refresh(user, bucket, qs);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: quota async refresh returned ret=" << r << dendl;
/* continue processing, might be a transient error, async refresh is just optimization */
}
}
if (qs.expiration > ceph_clock_now()) {
stats = qs.stats;
return 0;
}
}
int ret = fetch_stats_from_storage(user, bucket, stats, y, dpp);
if (ret < 0 && ret != -ENOENT)
return ret;
set_stats(user, bucket, qs, stats);
return 0;
}
template<class T>
class RGWQuotaStatsUpdate : public lru_map<T, RGWQuotaCacheStats>::UpdateContext {
const int objs_delta;
const uint64_t added_bytes;
const uint64_t removed_bytes;
public:
RGWQuotaStatsUpdate(const int objs_delta,
const uint64_t added_bytes,
const uint64_t removed_bytes)
: objs_delta(objs_delta),
added_bytes(added_bytes),
removed_bytes(removed_bytes) {
}
bool update(RGWQuotaCacheStats * const entry) override {
const uint64_t rounded_added = rgw_rounded_objsize(added_bytes);
const uint64_t rounded_removed = rgw_rounded_objsize(removed_bytes);
if (((int64_t)(entry->stats.size + added_bytes - removed_bytes)) >= 0) {
entry->stats.size += added_bytes - removed_bytes;
} else {
entry->stats.size = 0;
}
if (((int64_t)(entry->stats.size_rounded + rounded_added - rounded_removed)) >= 0) {
entry->stats.size_rounded += rounded_added - rounded_removed;
} else {
entry->stats.size_rounded = 0;
}
if (((int64_t)(entry->stats.num_objects + objs_delta)) >= 0) {
entry->stats.num_objects += objs_delta;
} else {
entry->stats.num_objects = 0;
}
return true;
}
};
template<class T>
void RGWQuotaCache<T>::adjust_stats(const rgw_user& user, rgw_bucket& bucket, int objs_delta,
uint64_t added_bytes, uint64_t removed_bytes)
{
RGWQuotaStatsUpdate<T> update(objs_delta, added_bytes, removed_bytes);
map_find_and_update(user, bucket, &update);
data_modified(user, bucket);
}
class BucketAsyncRefreshHandler : public RGWQuotaCache<rgw_bucket>::AsyncRefreshHandler,
public RGWGetBucketStats_CB {
rgw_user user;
public:
BucketAsyncRefreshHandler(rgw::sal::Driver* _driver, RGWQuotaCache<rgw_bucket> *_cache,
const rgw_user& _user, const rgw_bucket& _bucket) :
RGWQuotaCache<rgw_bucket>::AsyncRefreshHandler(_driver, _cache),
RGWGetBucketStats_CB(_bucket), user(_user) {}
void drop_reference() override { put(); }
void handle_response(int r) override;
int init_fetch() override;
};
int BucketAsyncRefreshHandler::init_fetch()
{
std::unique_ptr<rgw::sal::Bucket> rbucket;
const DoutPrefix dp(driver->ctx(), dout_subsys, "rgw bucket async refresh handler: ");
int r = driver->get_bucket(&dp, nullptr, bucket, &rbucket, null_yield);
if (r < 0) {
ldpp_dout(&dp, 0) << "could not get bucket info for bucket=" << bucket << " r=" << r << dendl;
return r;
}
ldpp_dout(&dp, 20) << "initiating async quota refresh for bucket=" << bucket << dendl;
const auto& index = rbucket->get_info().get_current_index();
if (is_layout_indexless(index)) {
return 0;
}
r = rbucket->read_stats_async(&dp, index, RGW_NO_SHARD, this);
if (r < 0) {
ldpp_dout(&dp, 0) << "could not get bucket info for bucket=" << bucket.name << dendl;
/* read_stats_async() dropped our reference already */
return r;
}
return 0;
}
void BucketAsyncRefreshHandler::handle_response(const int r)
{
if (r < 0) {
ldout(driver->ctx(), 20) << "AsyncRefreshHandler::handle_response() r=" << r << dendl;
cache->async_refresh_fail(user, bucket);
return;
}
RGWStorageStats bs;
for (const auto& pair : *stats) {
const RGWStorageStats& s = pair.second;
bs.size += s.size;
bs.size_rounded += s.size_rounded;
bs.num_objects += s.num_objects;
}
cache->async_refresh_response(user, bucket, bs);
}
class RGWBucketStatsCache : public RGWQuotaCache<rgw_bucket> {
protected:
bool map_find(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs) override {
return stats_map.find(bucket, qs);
}
bool map_find_and_update(const rgw_user& user, const rgw_bucket& bucket, lru_map<rgw_bucket, RGWQuotaCacheStats>::UpdateContext *ctx) override {
return stats_map.find_and_update(bucket, NULL, ctx);
}
void map_add(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs) override {
stats_map.add(bucket, qs);
}
int fetch_stats_from_storage(const rgw_user& user, const rgw_bucket& bucket, RGWStorageStats& stats, optional_yield y, const DoutPrefixProvider *dpp) override;
public:
explicit RGWBucketStatsCache(rgw::sal::Driver* _driver) : RGWQuotaCache<rgw_bucket>(_driver, _driver->ctx()->_conf->rgw_bucket_quota_cache_size) {
}
AsyncRefreshHandler *allocate_refresh_handler(const rgw_user& user, const rgw_bucket& bucket) override {
return new BucketAsyncRefreshHandler(driver, this, user, bucket);
}
};
int RGWBucketStatsCache::fetch_stats_from_storage(const rgw_user& _u, const rgw_bucket& _b, RGWStorageStats& stats, optional_yield y, const DoutPrefixProvider *dpp)
{
std::unique_ptr<rgw::sal::User> user = driver->get_user(_u);
std::unique_ptr<rgw::sal::Bucket> bucket;
int r = driver->get_bucket(dpp, user.get(), _b, &bucket, y);
if (r < 0) {
ldpp_dout(dpp, 0) << "could not get bucket info for bucket=" << _b << " r=" << r << dendl;
return r;
}
stats = RGWStorageStats();
const auto& index = bucket->get_info().get_current_index();
if (is_layout_indexless(index)) {
return 0;
}
string bucket_ver;
string master_ver;
map<RGWObjCategory, RGWStorageStats> bucket_stats;
r = bucket->read_stats(dpp, index, RGW_NO_SHARD, &bucket_ver,
&master_ver, bucket_stats, nullptr);
if (r < 0) {
ldpp_dout(dpp, 0) << "could not get bucket stats for bucket="
<< _b.name << dendl;
return r;
}
for (const auto& pair : bucket_stats) {
const RGWStorageStats& s = pair.second;
stats.size += s.size;
stats.size_rounded += s.size_rounded;
stats.num_objects += s.num_objects;
}
return 0;
}
class UserAsyncRefreshHandler : public RGWQuotaCache<rgw_user>::AsyncRefreshHandler,
public RGWGetUserStats_CB {
const DoutPrefixProvider *dpp;
rgw_bucket bucket;
public:
UserAsyncRefreshHandler(const DoutPrefixProvider *_dpp, rgw::sal::Driver* _driver, RGWQuotaCache<rgw_user> *_cache,
const rgw_user& _user, const rgw_bucket& _bucket) :
RGWQuotaCache<rgw_user>::AsyncRefreshHandler(_driver, _cache),
RGWGetUserStats_CB(_user),
dpp(_dpp),
bucket(_bucket) {}
void drop_reference() override { put(); }
int init_fetch() override;
void handle_response(int r) override;
};
int UserAsyncRefreshHandler::init_fetch()
{
std::unique_ptr<rgw::sal::User> ruser = driver->get_user(user);
ldpp_dout(dpp, 20) << "initiating async quota refresh for user=" << user << dendl;
int r = ruser->read_stats_async(dpp, this);
if (r < 0) {
ldpp_dout(dpp, 0) << "could not get bucket info for user=" << user << dendl;
/* get_bucket_stats_async() dropped our reference already */
return r;
}
return 0;
}
void UserAsyncRefreshHandler::handle_response(int r)
{
if (r < 0) {
ldout(driver->ctx(), 20) << "AsyncRefreshHandler::handle_response() r=" << r << dendl;
cache->async_refresh_fail(user, bucket);
return;
}
cache->async_refresh_response(user, bucket, stats);
}
class RGWUserStatsCache : public RGWQuotaCache<rgw_user> {
const DoutPrefixProvider *dpp;
std::atomic<bool> down_flag = { false };
ceph::shared_mutex mutex = ceph::make_shared_mutex("RGWUserStatsCache");
map<rgw_bucket, rgw_user> modified_buckets;
/* thread, sync recent modified buckets info */
class BucketsSyncThread : public Thread {
CephContext *cct;
RGWUserStatsCache *stats;
ceph::mutex lock = ceph::make_mutex("RGWUserStatsCache::BucketsSyncThread");
ceph::condition_variable cond;
public:
BucketsSyncThread(CephContext *_cct, RGWUserStatsCache *_s) : cct(_cct), stats(_s) {}
void *entry() override {
ldout(cct, 20) << "BucketsSyncThread: start" << dendl;
do {
map<rgw_bucket, rgw_user> buckets;
stats->swap_modified_buckets(buckets);
for (map<rgw_bucket, rgw_user>::iterator iter = buckets.begin(); iter != buckets.end(); ++iter) {
rgw_bucket bucket = iter->first;
rgw_user& user = iter->second;
ldout(cct, 20) << "BucketsSyncThread: sync user=" << user << " bucket=" << bucket << dendl;
const DoutPrefix dp(cct, dout_subsys, "rgw bucket sync thread: ");
int r = stats->sync_bucket(user, bucket, null_yield, &dp);
if (r < 0) {
ldout(cct, 0) << "WARNING: sync_bucket() returned r=" << r << dendl;
}
}
if (stats->going_down())
break;
std::unique_lock locker{lock};
cond.wait_for(
locker,
std::chrono::seconds(cct->_conf->rgw_user_quota_bucket_sync_interval));
} while (!stats->going_down());
ldout(cct, 20) << "BucketsSyncThread: done" << dendl;
return NULL;
}
void stop() {
std::lock_guard l{lock};
cond.notify_all();
}
};
/*
* thread, full sync all users stats periodically
*
* only sync non idle users or ones that never got synced before, this is needed so that
* users that didn't have quota turned on before (or existed before the user objclass
* tracked stats) need to get their backend stats up to date.
*/
class UserSyncThread : public Thread {
CephContext *cct;
RGWUserStatsCache *stats;
ceph::mutex lock = ceph::make_mutex("RGWUserStatsCache::UserSyncThread");
ceph::condition_variable cond;
public:
UserSyncThread(CephContext *_cct, RGWUserStatsCache *_s) : cct(_cct), stats(_s) {}
void *entry() override {
ldout(cct, 20) << "UserSyncThread: start" << dendl;
do {
const DoutPrefix dp(cct, dout_subsys, "rgw user sync thread: ");
int ret = stats->sync_all_users(&dp, null_yield);
if (ret < 0) {
ldout(cct, 5) << "ERROR: sync_all_users() returned ret=" << ret << dendl;
}
if (stats->going_down())
break;
std::unique_lock l{lock};
cond.wait_for(l, std::chrono::seconds(cct->_conf->rgw_user_quota_sync_interval));
} while (!stats->going_down());
ldout(cct, 20) << "UserSyncThread: done" << dendl;
return NULL;
}
void stop() {
std::lock_guard l{lock};
cond.notify_all();
}
};
BucketsSyncThread *buckets_sync_thread;
UserSyncThread *user_sync_thread;
protected:
bool map_find(const rgw_user& user,const rgw_bucket& bucket, RGWQuotaCacheStats& qs) override {
return stats_map.find(user, qs);
}
bool map_find_and_update(const rgw_user& user, const rgw_bucket& bucket, lru_map<rgw_user, RGWQuotaCacheStats>::UpdateContext *ctx) override {
return stats_map.find_and_update(user, NULL, ctx);
}
void map_add(const rgw_user& user, const rgw_bucket& bucket, RGWQuotaCacheStats& qs) override {
stats_map.add(user, qs);
}
int fetch_stats_from_storage(const rgw_user& user, const rgw_bucket& bucket, RGWStorageStats& stats, optional_yield y, const DoutPrefixProvider *dpp) override;
int sync_bucket(const rgw_user& rgw_user, rgw_bucket& bucket, optional_yield y, const DoutPrefixProvider *dpp);
int sync_user(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y);
int sync_all_users(const DoutPrefixProvider *dpp, optional_yield y);
void data_modified(const rgw_user& user, rgw_bucket& bucket) override;
void swap_modified_buckets(map<rgw_bucket, rgw_user>& out) {
std::unique_lock lock{mutex};
modified_buckets.swap(out);
}
template<class T> /* easier doing it as a template, Thread doesn't have ->stop() */
void stop_thread(T **pthr) {
T *thread = *pthr;
if (!thread)
return;
thread->stop();
thread->join();
delete thread;
*pthr = NULL;
}
public:
RGWUserStatsCache(const DoutPrefixProvider *dpp, rgw::sal::Driver* _driver, bool quota_threads)
: RGWQuotaCache<rgw_user>(_driver, _driver->ctx()->_conf->rgw_bucket_quota_cache_size), dpp(dpp)
{
if (quota_threads) {
buckets_sync_thread = new BucketsSyncThread(driver->ctx(), this);
buckets_sync_thread->create("rgw_buck_st_syn");
user_sync_thread = new UserSyncThread(driver->ctx(), this);
user_sync_thread->create("rgw_user_st_syn");
} else {
buckets_sync_thread = NULL;
user_sync_thread = NULL;
}
}
~RGWUserStatsCache() override {
stop();
}
AsyncRefreshHandler *allocate_refresh_handler(const rgw_user& user, const rgw_bucket& bucket) override {
return new UserAsyncRefreshHandler(dpp, driver, this, user, bucket);
}
bool going_down() {
return down_flag;
}
void stop() {
down_flag = true;
{
std::unique_lock lock{mutex};
stop_thread(&buckets_sync_thread);
}
stop_thread(&user_sync_thread);
}
};
int RGWUserStatsCache::fetch_stats_from_storage(const rgw_user& _u,
const rgw_bucket& _b,
RGWStorageStats& stats,
optional_yield y,
const DoutPrefixProvider *dpp)
{
std::unique_ptr<rgw::sal::User> user = driver->get_user(_u);
int r = user->read_stats(dpp, y, &stats);
if (r < 0) {
ldpp_dout(dpp, 0) << "could not get user stats for user=" << user << dendl;
return r;
}
return 0;
}
int RGWUserStatsCache::sync_bucket(const rgw_user& _u, rgw_bucket& _b, optional_yield y, const DoutPrefixProvider *dpp)
{
std::unique_ptr<rgw::sal::User> user = driver->get_user(_u);
std::unique_ptr<rgw::sal::Bucket> bucket;
int r = driver->get_bucket(dpp, user.get(), _b, &bucket, y);
if (r < 0) {
ldpp_dout(dpp, 0) << "could not get bucket info for bucket=" << _b << " r=" << r << dendl;
return r;
}
r = bucket->sync_user_stats(dpp, y);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: sync_user_stats() for user=" << _u << ", bucket=" << bucket << " returned " << r << dendl;
return r;
}
return bucket->check_bucket_shards(dpp, y);
}
int RGWUserStatsCache::sync_user(const DoutPrefixProvider *dpp, const rgw_user& _u, optional_yield y)
{
RGWStorageStats stats;
ceph::real_time last_stats_sync;
ceph::real_time last_stats_update;
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(_u.to_str()));
int ret = user->read_stats(dpp, y, &stats, &last_stats_sync, &last_stats_update);
if (ret < 0) {
ldpp_dout(dpp, 5) << "ERROR: can't read user header: ret=" << ret << dendl;
return ret;
}
if (!driver->ctx()->_conf->rgw_user_quota_sync_idle_users &&
last_stats_update < last_stats_sync) {
ldpp_dout(dpp, 20) << "user is idle, not doing a full sync (user=" << user << ")" << dendl;
return 0;
}
real_time when_need_full_sync = last_stats_sync;
when_need_full_sync += make_timespan(driver->ctx()->_conf->rgw_user_quota_sync_wait_time);
// check if enough time passed since last full sync
/* FIXME: missing check? */
ret = rgw_user_sync_all_stats(dpp, driver, user.get(), y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed user stats sync, ret=" << ret << dendl;
return ret;
}
return 0;
}
int RGWUserStatsCache::sync_all_users(const DoutPrefixProvider *dpp, optional_yield y)
{
string key = "user";
void *handle;
int ret = driver->meta_list_keys_init(dpp, key, string(), &handle);
if (ret < 0) {
ldpp_dout(dpp, 10) << "ERROR: can't get key: ret=" << ret << dendl;
return ret;
}
bool truncated;
int max = 1000;
do {
list<string> keys;
ret = driver->meta_list_keys_next(dpp, handle, max, keys, &truncated);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: lists_keys_next(): ret=" << ret << dendl;
goto done;
}
for (list<string>::iterator iter = keys.begin();
iter != keys.end() && !going_down();
++iter) {
rgw_user user(*iter);
ldpp_dout(dpp, 20) << "RGWUserStatsCache: sync user=" << user << dendl;
int ret = sync_user(dpp, user, y);
if (ret < 0) {
ldpp_dout(dpp, 5) << "ERROR: sync_user() failed, user=" << user << " ret=" << ret << dendl;
/* continuing to next user */
continue;
}
}
} while (truncated);
ret = 0;
done:
driver->meta_list_keys_complete(handle);
return ret;
}
void RGWUserStatsCache::data_modified(const rgw_user& user, rgw_bucket& bucket)
{
/* racy, but it's ok */
mutex.lock_shared();
bool need_update = modified_buckets.find(bucket) == modified_buckets.end();
mutex.unlock_shared();
if (need_update) {
std::unique_lock lock{mutex};
modified_buckets[bucket] = user;
}
}
class RGWQuotaInfoApplier {
/* NOTE: no non-static field allowed as instances are supposed to live in
* the static memory only. */
protected:
RGWQuotaInfoApplier() = default;
public:
virtual ~RGWQuotaInfoApplier() {}
virtual bool is_size_exceeded(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t size) const = 0;
virtual bool is_num_objs_exceeded(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t num_objs) const = 0;
static const RGWQuotaInfoApplier& get_instance(const RGWQuotaInfo& qinfo);
};
class RGWQuotaInfoDefApplier : public RGWQuotaInfoApplier {
public:
bool is_size_exceeded(const DoutPrefixProvider *dpp, const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t size) const override;
bool is_num_objs_exceeded(const DoutPrefixProvider *dpp, const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t num_objs) const override;
};
class RGWQuotaInfoRawApplier : public RGWQuotaInfoApplier {
public:
bool is_size_exceeded(const DoutPrefixProvider *dpp, const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t size) const override;
bool is_num_objs_exceeded(const DoutPrefixProvider *dpp, const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t num_objs) const override;
};
bool RGWQuotaInfoDefApplier::is_size_exceeded(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t size) const
{
if (qinfo.max_size < 0) {
/* The limit is not enabled. */
return false;
}
const uint64_t cur_size = stats.size_rounded;
const uint64_t new_size = rgw_rounded_objsize(size);
if (std::cmp_greater(cur_size + new_size, qinfo.max_size)) {
ldpp_dout(dpp, 10) << "quota exceeded: stats.size_rounded=" << stats.size_rounded
<< " size=" << new_size << " "
<< entity << "_quota.max_size=" << qinfo.max_size << dendl;
return true;
}
return false;
}
bool RGWQuotaInfoDefApplier::is_num_objs_exceeded(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t num_objs) const
{
if (qinfo.max_objects < 0) {
/* The limit is not enabled. */
return false;
}
if (std::cmp_greater(stats.num_objects + num_objs, qinfo.max_objects)) {
ldpp_dout(dpp, 10) << "quota exceeded: stats.num_objects=" << stats.num_objects
<< " " << entity << "_quota.max_objects=" << qinfo.max_objects
<< dendl;
return true;
}
return false;
}
bool RGWQuotaInfoRawApplier::is_size_exceeded(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t size) const
{
if (qinfo.max_size < 0) {
/* The limit is not enabled. */
return false;
}
const uint64_t cur_size = stats.size;
if (std::cmp_greater(cur_size + size, qinfo.max_size)) {
ldpp_dout(dpp, 10) << "quota exceeded: stats.size=" << stats.size
<< " size=" << size << " "
<< entity << "_quota.max_size=" << qinfo.max_size << dendl;
return true;
}
return false;
}
bool RGWQuotaInfoRawApplier::is_num_objs_exceeded(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& qinfo,
const RGWStorageStats& stats,
const uint64_t num_objs) const
{
if (qinfo.max_objects < 0) {
/* The limit is not enabled. */
return false;
}
if (std::cmp_greater(stats.num_objects + num_objs, qinfo.max_objects)) {
ldpp_dout(dpp, 10) << "quota exceeded: stats.num_objects=" << stats.num_objects
<< " " << entity << "_quota.max_objects=" << qinfo.max_objects
<< dendl;
return true;
}
return false;
}
const RGWQuotaInfoApplier& RGWQuotaInfoApplier::get_instance(
const RGWQuotaInfo& qinfo)
{
static RGWQuotaInfoDefApplier default_qapplier;
static RGWQuotaInfoRawApplier raw_qapplier;
if (qinfo.check_on_raw) {
return raw_qapplier;
} else {
return default_qapplier;
}
}
class RGWQuotaHandlerImpl : public RGWQuotaHandler {
rgw::sal::Driver* driver;
RGWBucketStatsCache bucket_stats_cache;
RGWUserStatsCache user_stats_cache;
int check_quota(const DoutPrefixProvider *dpp,
const char * const entity,
const RGWQuotaInfo& quota,
const RGWStorageStats& stats,
const uint64_t num_objs,
const uint64_t size) {
if (!quota.enabled) {
return 0;
}
const auto& quota_applier = RGWQuotaInfoApplier::get_instance(quota);
ldpp_dout(dpp, 20) << entity
<< " quota: max_objects=" << quota.max_objects
<< " max_size=" << quota.max_size << dendl;
if (quota_applier.is_num_objs_exceeded(dpp, entity, quota, stats, num_objs)) {
return -ERR_QUOTA_EXCEEDED;
}
if (quota_applier.is_size_exceeded(dpp, entity, quota, stats, size)) {
return -ERR_QUOTA_EXCEEDED;
}
ldpp_dout(dpp, 20) << entity << " quota OK:"
<< " stats.num_objects=" << stats.num_objects
<< " stats.size=" << stats.size << dendl;
return 0;
}
public:
RGWQuotaHandlerImpl(const DoutPrefixProvider *dpp, rgw::sal::Driver* _driver, bool quota_threads) : driver(_driver),
bucket_stats_cache(_driver),
user_stats_cache(dpp, _driver, quota_threads) {}
int check_quota(const DoutPrefixProvider *dpp,
const rgw_user& user,
rgw_bucket& bucket,
RGWQuota& quota,
uint64_t num_objs,
uint64_t size, optional_yield y) override {
if (!quota.bucket_quota.enabled && !quota.user_quota.enabled) {
return 0;
}
/*
* we need to fetch bucket stats if the user quota is enabled, because
* the whole system relies on us periodically updating the user's bucket
* stats in the user's header, this happens in get_stats() if we actually
* fetch that info and not rely on cached data
*/
const DoutPrefix dp(driver->ctx(), dout_subsys, "rgw quota handler: ");
if (quota.bucket_quota.enabled) {
RGWStorageStats bucket_stats;
int ret = bucket_stats_cache.get_stats(user, bucket, bucket_stats, y, &dp);
if (ret < 0) {
return ret;
}
ret = check_quota(dpp, "bucket", quota.bucket_quota, bucket_stats, num_objs, size);
if (ret < 0) {
return ret;
}
}
if (quota.user_quota.enabled) {
RGWStorageStats user_stats;
int ret = user_stats_cache.get_stats(user, bucket, user_stats, y, &dp);
if (ret < 0) {
return ret;
}
ret = check_quota(dpp, "user", quota.user_quota, user_stats, num_objs, size);
if (ret < 0) {
return ret;
}
}
return 0;
}
void update_stats(const rgw_user& user, rgw_bucket& bucket, int obj_delta, uint64_t added_bytes, uint64_t removed_bytes) override {
bucket_stats_cache.adjust_stats(user, bucket, obj_delta, added_bytes, removed_bytes);
user_stats_cache.adjust_stats(user, bucket, obj_delta, added_bytes, removed_bytes);
}
void check_bucket_shards(const DoutPrefixProvider *dpp, uint64_t max_objs_per_shard,
uint64_t num_shards, uint64_t num_objs, bool is_multisite,
bool& need_resharding, uint32_t *suggested_num_shards) override
{
if (num_objs > num_shards * max_objs_per_shard) {
ldpp_dout(dpp, 0) << __func__ << ": resharding needed: stats.num_objects=" << num_objs
<< " shard max_objects=" << max_objs_per_shard * num_shards << dendl;
need_resharding = true;
if (suggested_num_shards) {
uint32_t obj_multiplier = 2;
if (is_multisite) {
// if we're maintaining bilogs for multisite, reshards are significantly
// more expensive. scale up the shard count much faster to minimize the
// number of reshard events during a write workload
obj_multiplier = 8;
}
*suggested_num_shards = num_objs * obj_multiplier / max_objs_per_shard;
}
} else {
need_resharding = false;
}
}
};
RGWQuotaHandler *RGWQuotaHandler::generate_handler(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, bool quota_threads)
{
return new RGWQuotaHandlerImpl(dpp, driver, quota_threads);
}
void RGWQuotaHandler::free_handler(RGWQuotaHandler *handler)
{
delete handler;
}
void rgw_apply_default_bucket_quota(RGWQuotaInfo& quota, const ConfigProxy& conf)
{
if (conf->rgw_bucket_default_quota_max_objects >= 0) {
quota.max_objects = conf->rgw_bucket_default_quota_max_objects;
quota.enabled = true;
}
if (conf->rgw_bucket_default_quota_max_size >= 0) {
quota.max_size = conf->rgw_bucket_default_quota_max_size;
quota.enabled = true;
}
}
void rgw_apply_default_user_quota(RGWQuotaInfo& quota, const ConfigProxy& conf)
{
if (conf->rgw_user_default_quota_max_objects >= 0) {
quota.max_objects = conf->rgw_user_default_quota_max_objects;
quota.enabled = true;
}
if (conf->rgw_user_default_quota_max_size >= 0) {
quota.max_size = conf->rgw_user_default_quota_max_size;
quota.enabled = true;
}
}
void RGWQuotaInfo::dump(Formatter *f) const
{
f->dump_bool("enabled", enabled);
f->dump_bool("check_on_raw", check_on_raw);
f->dump_int("max_size", max_size);
f->dump_int("max_size_kb", rgw_rounded_kb(max_size));
f->dump_int("max_objects", max_objects);
}
void RGWQuotaInfo::decode_json(JSONObj *obj)
{
if (false == JSONDecoder::decode_json("max_size", max_size, obj)) {
/* We're parsing an older version of the struct. */
int64_t max_size_kb = 0;
JSONDecoder::decode_json("max_size_kb", max_size_kb, obj);
max_size = max_size_kb * 1024;
}
JSONDecoder::decode_json("max_objects", max_objects, obj);
JSONDecoder::decode_json("check_on_raw", check_on_raw, obj);
JSONDecoder::decode_json("enabled", enabled, obj);
}
| 34,487 | 31.845714 | 164 |
cc
|
null |
ceph-main/src/rgw/rgw_quota.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 Inktank, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "include/utime.h"
#include "common/config_fwd.h"
#include "common/lru_map.h"
#include "rgw/rgw_quota_types.h"
#include "common/async/yield_context.h"
#include "rgw_sal_fwd.h"
struct rgw_bucket;
class RGWQuotaHandler {
public:
RGWQuotaHandler() {}
virtual ~RGWQuotaHandler() {
}
virtual int check_quota(const DoutPrefixProvider *dpp, const rgw_user& bucket_owner, rgw_bucket& bucket,
RGWQuota& quota,
uint64_t num_objs, uint64_t size, optional_yield y) = 0;
virtual void check_bucket_shards(const DoutPrefixProvider *dpp, uint64_t max_objs_per_shard,
uint64_t num_shards, uint64_t num_objs, bool is_multisite,
bool& need_resharding, uint32_t *suggested_num_shards) = 0;
virtual void update_stats(const rgw_user& bucket_owner, rgw_bucket& bucket, int obj_delta, uint64_t added_bytes, uint64_t removed_bytes) = 0;
static RGWQuotaHandler *generate_handler(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, bool quota_threads);
static void free_handler(RGWQuotaHandler *handler);
};
// apply default quotas from configuration
void rgw_apply_default_bucket_quota(RGWQuotaInfo& quota, const ConfigProxy& conf);
void rgw_apply_default_user_quota(RGWQuotaInfo& quota, const ConfigProxy& conf);
| 1,751 | 34.04 | 143 |
h
|
null |
ceph-main/src/rgw/rgw_quota_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) 2013 Inktank, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* introduce changes or include files which can only be compiled in
* radosgw or OSD contexts (e.g., rgw_sal.h, rgw_common.h)
*/
#pragma once
static inline int64_t rgw_rounded_kb(int64_t bytes)
{
return (bytes + 1023) / 1024;
}
class JSONObj;
struct RGWQuotaInfo {
template<class T> friend class RGWQuotaCache;
public:
int64_t max_size;
int64_t max_objects;
bool enabled;
/* Do we want to compare with raw, not rounded RGWStorageStats::size (true)
* or maybe rounded-to-4KiB RGWStorageStats::size_rounded (false)? */
bool check_on_raw;
RGWQuotaInfo()
: max_size(-1),
max_objects(-1),
enabled(false),
check_on_raw(false) {
}
void encode(bufferlist& bl) const {
ENCODE_START(3, 1, bl);
if (max_size < 0) {
encode(-rgw_rounded_kb(abs(max_size)), bl);
} else {
encode(rgw_rounded_kb(max_size), bl);
}
encode(max_objects, bl);
encode(enabled, bl);
encode(max_size, bl);
encode(check_on_raw, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(3, 1, 1, bl);
int64_t max_size_kb;
decode(max_size_kb, bl);
decode(max_objects, bl);
decode(enabled, bl);
if (struct_v < 2) {
max_size = max_size_kb * 1024;
} else {
decode(max_size, bl);
}
if (struct_v >= 3) {
decode(check_on_raw, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(RGWQuotaInfo)
struct RGWQuota {
RGWQuotaInfo user_quota;
RGWQuotaInfo bucket_quota;
};
| 2,086 | 22.715909 | 77 |
h
|
null |
ceph-main/src/rgw/rgw_ratelimit.h
|
#pragma once
#include <chrono>
#include <thread>
#include <condition_variable>
#include "rgw_common.h"
class RateLimiterEntry {
/*
fixed_point_rgw_ratelimit is important to preserve the precision of the token calculation
for example: a user have a limit of single op per minute, the user will consume its single token and then will send another request, 1s after it.
in that case, without this method, the user will get 0 tokens although it should get 0.016 tokens.
using this method it will add 16 tokens to the user, and the user will have 16 tokens, each time rgw will do comparison rgw will divide by fixed_point_rgw_ratelimit, so the user will be blocked anyway until it has enough tokens.
*/
static constexpr int64_t fixed_point_rgw_ratelimit = 1000;
// counters are tracked in multiples of fixed_point_rgw_ratelimit
struct counters {
int64_t ops = 0;
int64_t bytes = 0;
};
counters read;
counters write;
ceph::timespan ts;
bool first_run = true;
std::mutex ts_lock;
// Those functions are returning the integer value of the tokens
int64_t read_ops () const
{
return read.ops / fixed_point_rgw_ratelimit;
}
int64_t write_ops() const
{
return write.ops / fixed_point_rgw_ratelimit;
}
int64_t read_bytes() const
{
return read.bytes / fixed_point_rgw_ratelimit;
}
int64_t write_bytes() const
{
return write.bytes / fixed_point_rgw_ratelimit;
}
bool should_rate_limit_read(int64_t ops_limit, int64_t bw_limit) {
//check if tenants did not reach their bw or ops limits and that the limits are not 0 (which is unlimited)
if(((read_ops() - 1 < 0) && (ops_limit > 0)) ||
(read_bytes() < 0 && bw_limit > 0))
{
return true;
}
// we don't want to reduce ops' tokens if we've rejected it.
read.ops -= fixed_point_rgw_ratelimit;
return false;
}
bool should_rate_limit_write(int64_t ops_limit, int64_t bw_limit)
{
//check if tenants did not reach their bw or ops limits and that the limits are not 0 (which is unlimited)
if(((write_ops() - 1 < 0) && (ops_limit > 0)) ||
(write_bytes() < 0 && bw_limit > 0))
{
return true;
}
// we don't want to reduce ops' tokens if we've rejected it.
write.ops -= fixed_point_rgw_ratelimit;
return false;
}
/* The purpose of this function is to minimum time before overriding the stored timestamp
This function is necessary to force the increase tokens add at least 1 token when it updates the last stored timestamp.
That way the user/bucket will not lose tokens because of rounding
*/
bool minimum_time_reached(ceph::timespan curr_timestamp) const
{
using namespace std::chrono;
constexpr auto min_duration = duration_cast<ceph::timespan>(seconds(60)) / fixed_point_rgw_ratelimit;
const auto delta = curr_timestamp - ts;
if (delta < min_duration)
{
return false;
}
return true;
}
void increase_tokens(ceph::timespan curr_timestamp,
const RGWRateLimitInfo* info)
{
constexpr int fixed_point = fixed_point_rgw_ratelimit;
if (first_run)
{
write.ops = info->max_write_ops * fixed_point;
write.bytes = info->max_write_bytes * fixed_point;
read.ops = info->max_read_ops * fixed_point;
read.bytes = info->max_read_bytes * fixed_point;
ts = curr_timestamp;
first_run = false;
return;
}
else if(curr_timestamp > ts && minimum_time_reached(curr_timestamp))
{
const int64_t time_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>(curr_timestamp - ts).count() / 60.0 / std::milli::den * fixed_point; // / 60 to make it work with 1 min token bucket
ts = curr_timestamp;
const int64_t write_ops = info->max_write_ops * time_in_ms;
const int64_t write_bw = info->max_write_bytes * time_in_ms;
const int64_t read_ops = info->max_read_ops * time_in_ms;
const int64_t read_bw = info->max_read_bytes * time_in_ms;
read.ops = std::min(info->max_read_ops * fixed_point, read_ops + read.ops);
read.bytes = std::min(info->max_read_bytes * fixed_point, read_bw + read.bytes);
write.ops = std::min(info->max_write_ops * fixed_point, write_ops + write.ops);
write.bytes = std::min(info->max_write_bytes * fixed_point, write_bw + write.bytes);
}
}
public:
bool should_rate_limit(bool is_read, const RGWRateLimitInfo* ratelimit_info, ceph::timespan curr_timestamp)
{
std::unique_lock lock(ts_lock);
increase_tokens(curr_timestamp, ratelimit_info);
if (is_read)
{
return should_rate_limit_read(ratelimit_info->max_read_ops, ratelimit_info->max_read_bytes);
}
return should_rate_limit_write(ratelimit_info->max_write_ops, ratelimit_info->max_write_bytes);
}
void decrease_bytes(bool is_read, int64_t amount, const RGWRateLimitInfo* info) {
std::unique_lock lock(ts_lock);
// we don't want the tenant to be with higher debt than 120 seconds(2 min) of its limit
if (is_read)
{
read.bytes = std::max(read.bytes - amount * fixed_point_rgw_ratelimit,info->max_read_bytes * fixed_point_rgw_ratelimit * -2);
} else {
write.bytes = std::max(write.bytes - amount * fixed_point_rgw_ratelimit,info->max_write_bytes * fixed_point_rgw_ratelimit * -2);
}
}
void giveback_tokens(bool is_read)
{
std::unique_lock lock(ts_lock);
if (is_read)
{
read.ops += fixed_point_rgw_ratelimit;
} else {
write.ops += fixed_point_rgw_ratelimit;
}
}
};
class RateLimiter {
static constexpr size_t map_size = 2000000; // will create it with the closest upper prime number
std::shared_mutex insert_lock;
std::atomic_bool& replacing;
std::condition_variable& cv;
typedef std::unordered_map<std::string, RateLimiterEntry> hash_map;
hash_map ratelimit_entries{map_size};
static bool is_read_op(const std::string_view method) {
if (method == "GET" || method == "HEAD")
{
return true;
}
return false;
}
// find or create an entry, and return its iterator
auto& find_or_create(const std::string& key) {
std::shared_lock rlock(insert_lock);
if (ratelimit_entries.size() > 0.9 * map_size && replacing == false)
{
replacing = true;
cv.notify_all();
}
auto ret = ratelimit_entries.find(key);
rlock.unlock();
if (ret == ratelimit_entries.end())
{
std::unique_lock wlock(insert_lock);
ret = ratelimit_entries.emplace(std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple()).first;
}
return ret->second;
}
public:
RateLimiter(const RateLimiter&) = delete;
RateLimiter& operator =(const RateLimiter&) = delete;
RateLimiter(RateLimiter&&) = delete;
RateLimiter& operator =(RateLimiter&&) = delete;
RateLimiter() = delete;
RateLimiter(std::atomic_bool& replacing, std::condition_variable& cv)
: replacing(replacing), cv(cv)
{
// prevents rehash, so no iterators invalidation
ratelimit_entries.max_load_factor(1000);
};
bool should_rate_limit(const char *method, const std::string& key, ceph::coarse_real_time curr_timestamp, const RGWRateLimitInfo* ratelimit_info) {
if (key.empty() || key.length() == 1 || !ratelimit_info->enabled)
{
return false;
}
bool is_read = is_read_op(method);
auto& it = find_or_create(key);
auto curr_ts = curr_timestamp.time_since_epoch();
return it.should_rate_limit(is_read ,ratelimit_info, curr_ts);
}
void giveback_tokens(const char *method, const std::string& key)
{
bool is_read = is_read_op(method);
auto& it = find_or_create(key);
it.giveback_tokens(is_read);
}
void decrease_bytes(const char *method, const std::string& key, const int64_t amount, const RGWRateLimitInfo* info) {
if (key.empty() || key.length() == 1 || !info->enabled)
{
return;
}
bool is_read = is_read_op(method);
if ((is_read && !info->max_read_bytes) || (!is_read && !info->max_write_bytes))
{
return;
}
auto& it = find_or_create(key);
it.decrease_bytes(is_read, amount, info);
}
void clear() {
ratelimit_entries.clear();
}
};
// This class purpose is to hold 2 RateLimiter instances, one active and one passive.
// once the active has reached the watermark for clearing it will call the replace_active() thread using cv
// The replace_active will clear the previous RateLimiter after all requests to it has been done (use_count() > 1)
// In the meanwhile new requests will come into the newer active
class ActiveRateLimiter : public DoutPrefix {
std::atomic_uint8_t stopped = {false};
std::condition_variable cv;
std::mutex cv_m;
std::thread runner;
std::atomic_bool replacing = false;
std::atomic_uint8_t current_active = 0;
std::shared_ptr<RateLimiter> ratelimit[2];
void replace_active() {
using namespace std::chrono_literals;
std::unique_lock<std::mutex> lk(cv_m);
while (!stopped) {
cv.wait(lk);
current_active = current_active ^ 1;
ldpp_dout(this, 20) << "replacing active ratelimit data structure" << dendl;
while (!stopped && ratelimit[(current_active ^ 1)].use_count() > 1 ) {
if (cv.wait_for(lk, 1min) != std::cv_status::timeout && stopped)
{
return;
}
}
if (stopped)
{
return;
}
ldpp_dout(this, 20) << "clearing passive ratelimit data structure" << dendl;
ratelimit[(current_active ^ 1)]->clear();
replacing = false;
}
}
public:
ActiveRateLimiter(const ActiveRateLimiter&) = delete;
ActiveRateLimiter& operator =(const ActiveRateLimiter&) = delete;
ActiveRateLimiter(ActiveRateLimiter&&) = delete;
ActiveRateLimiter& operator =(ActiveRateLimiter&&) = delete;
ActiveRateLimiter() = delete;
ActiveRateLimiter(CephContext* cct) :
DoutPrefix(cct, ceph_subsys_rgw, "rate limiter: ")
{
ratelimit[0] = std::make_shared<RateLimiter>(replacing, cv);
ratelimit[1] = std::make_shared<RateLimiter>(replacing, cv);
}
~ActiveRateLimiter() {
ldpp_dout(this, 20) << "stopping ratelimit_gc thread" << dendl;
cv_m.lock();
stopped = true;
cv_m.unlock();
cv.notify_all();
runner.join();
}
std::shared_ptr<RateLimiter> get_active() {
return ratelimit[current_active];
}
void start() {
ldpp_dout(this, 20) << "starting ratelimit_gc thread" << dendl;
runner = std::thread(&ActiveRateLimiter::replace_active, this);
const auto rc = ceph_pthread_setname(runner.native_handle(), "ratelimit_gc");
ceph_assert(rc==0);
}
};
| 10,868 | 36.095563 | 232 |
h
|
null |
ceph-main/src/rgw/rgw_realm.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <optional>
#include "common/errno.h"
#include "rgw_zone.h"
#include "rgw_realm_watcher.h"
#include "rgw_meta_sync_status.h"
#include "rgw_sal_config.h"
#include "rgw_string.h"
#include "rgw_sync.h"
#include "services/svc_zone.h"
#include "services/svc_sys_obj.h"
#include "common/ceph_json.h"
#include "common/Formatter.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
namespace rgw_zone_defaults {
std::string realm_info_oid_prefix = "realms.";
std::string realm_names_oid_prefix = "realms_names.";
std::string default_realm_info_oid = "default.realm";
std::string RGW_DEFAULT_REALM_ROOT_POOL = "rgw.root";
}
using namespace std;
using namespace rgw_zone_defaults;
RGWRealm::~RGWRealm() {}
RGWRemoteMetaLog::~RGWRemoteMetaLog()
{
delete error_logger;
}
string RGWRealm::get_predefined_id(CephContext *cct) const {
return cct->_conf.get_val<string>("rgw_realm_id");
}
const string& RGWRealm::get_predefined_name(CephContext *cct) const {
return cct->_conf->rgw_realm;
}
int RGWRealm::create(const DoutPrefixProvider *dpp, optional_yield y, bool exclusive)
{
int ret = RGWSystemMetaObj::create(dpp, y, exclusive);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR creating new realm object " << name << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
// create the control object for watch/notify
ret = create_control(dpp, exclusive, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR creating control for new realm " << name << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
RGWPeriod period;
if (current_period.empty()) {
/* create new period for the realm */
ret = period.init(dpp, cct, sysobj_svc, id, y, name, false);
if (ret < 0 ) {
return ret;
}
ret = period.create(dpp, y, true);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: creating new period for realm " << name << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
} else {
period = RGWPeriod(current_period, 0);
int ret = period.init(dpp, cct, sysobj_svc, id, y, name);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to init period " << current_period << dendl;
return ret;
}
}
ret = set_current_period(dpp, period, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed set current period " << current_period << dendl;
return ret;
}
// try to set as default. may race with another create, so pass exclusive=true
// so we don't override an existing default
ret = set_as_default(dpp, y, true);
if (ret < 0 && ret != -EEXIST) {
ldpp_dout(dpp, 0) << "WARNING: failed to set realm as default realm, ret=" << ret << dendl;
}
return 0;
}
int RGWRealm::delete_obj(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = RGWSystemMetaObj::delete_obj(dpp, y);
if (ret < 0) {
return ret;
}
return delete_control(dpp, y);
}
int RGWRealm::create_control(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y)
{
auto pool = rgw_pool{get_pool(cct)};
auto oid = get_control_oid();
bufferlist bl;
auto sysobj = sysobj_svc->get_obj(rgw_raw_obj{pool, oid});
return sysobj.wop()
.set_exclusive(exclusive)
.write(dpp, bl, y);
}
int RGWRealm::delete_control(const DoutPrefixProvider *dpp, optional_yield y)
{
auto pool = rgw_pool{get_pool(cct)};
auto obj = rgw_raw_obj{pool, get_control_oid()};
auto sysobj = sysobj_svc->get_obj(obj);
return sysobj.wop().remove(dpp, y);
}
rgw_pool RGWRealm::get_pool(CephContext *cct) const
{
if (cct->_conf->rgw_realm_root_pool.empty()) {
return rgw_pool(RGW_DEFAULT_REALM_ROOT_POOL);
}
return rgw_pool(cct->_conf->rgw_realm_root_pool);
}
const string RGWRealm::get_default_oid(bool old_format) const
{
if (cct->_conf->rgw_default_realm_info_oid.empty()) {
return default_realm_info_oid;
}
return cct->_conf->rgw_default_realm_info_oid;
}
const string& RGWRealm::get_names_oid_prefix() const
{
return realm_names_oid_prefix;
}
const string& RGWRealm::get_info_oid_prefix(bool old_format) const
{
return realm_info_oid_prefix;
}
int RGWRealm::set_current_period(const DoutPrefixProvider *dpp, RGWPeriod& period, optional_yield y)
{
// update realm epoch to match the period's
if (epoch > period.get_realm_epoch()) {
ldpp_dout(dpp, 0) << "ERROR: set_current_period with old realm epoch "
<< period.get_realm_epoch() << ", current epoch=" << epoch << dendl;
return -EINVAL;
}
if (epoch == period.get_realm_epoch() && current_period != period.get_id()) {
ldpp_dout(dpp, 0) << "ERROR: set_current_period with same realm epoch "
<< period.get_realm_epoch() << ", but different period id "
<< period.get_id() << " != " << current_period << dendl;
return -EINVAL;
}
epoch = period.get_realm_epoch();
current_period = period.get_id();
int ret = update(dpp, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: period update: " << cpp_strerror(-ret) << dendl;
return ret;
}
ret = period.reflect(dpp, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: period.reflect(): " << cpp_strerror(-ret) << dendl;
return ret;
}
return 0;
}
string RGWRealm::get_control_oid() const
{
return get_info_oid_prefix() + id + ".control";
}
int RGWRealm::notify_zone(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y)
{
rgw_pool pool{get_pool(cct)};
auto sysobj = sysobj_svc->get_obj(rgw_raw_obj{pool, get_control_oid()});
int ret = sysobj.wn().notify(dpp, bl, 0, nullptr, y);
if (ret < 0) {
return ret;
}
return 0;
}
int RGWRealm::notify_new_period(const DoutPrefixProvider *dpp, const RGWPeriod& period, optional_yield y)
{
bufferlist bl;
using ceph::encode;
// push the period to dependent zonegroups/zones
encode(RGWRealmNotify::ZonesNeedPeriod, bl);
encode(period, bl);
// reload the gateway with the new period
encode(RGWRealmNotify::Reload, bl);
return notify_zone(dpp, bl, y);
}
int RGWRealm::find_zone(const DoutPrefixProvider *dpp,
const rgw_zone_id& zid,
RGWPeriod *pperiod,
RGWZoneGroup *pzonegroup,
bool *pfound,
optional_yield y) const
{
auto& found = *pfound;
found = false;
string period_id;
epoch_t epoch = 0;
RGWPeriod period(period_id, epoch);
int r = period.init(dpp, cct, sysobj_svc, get_id(), y, get_name());
if (r < 0) {
ldpp_dout(dpp, 0) << "WARNING: period init failed: " << cpp_strerror(-r) << " ... skipping" << dendl;
return r;
}
found = period.find_zone(dpp, zid, pzonegroup, y);
if (found) {
*pperiod = period;
}
return 0;
}
void RGWRealm::generate_test_instances(list<RGWRealm*> &o)
{
RGWRealm *z = new RGWRealm;
o.push_back(z);
o.push_back(new RGWRealm);
}
void RGWRealm::dump(Formatter *f) const
{
RGWSystemMetaObj::dump(f);
encode_json("current_period", current_period, f);
encode_json("epoch", epoch, f);
}
void RGWRealm::decode_json(JSONObj *obj)
{
RGWSystemMetaObj::decode_json(obj);
JSONDecoder::decode_json("current_period", current_period, obj);
JSONDecoder::decode_json("epoch", epoch, obj);
}
| 7,309 | 26.481203 | 114 |
cc
|
null |
ceph-main/src/rgw/rgw_realm_reloader.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_realm_reloader.h"
#include "rgw_auth_registry.h"
#include "rgw_bucket.h"
#include "rgw_log.h"
#include "rgw_rest.h"
#include "rgw_user.h"
#include "rgw_process_env.h"
#include "rgw_sal.h"
#include "rgw_sal_rados.h"
#include "services/svc_zone.h"
#include "common/errno.h"
#define dout_subsys ceph_subsys_rgw
#undef dout_prefix
#define dout_prefix (*_dout << "rgw realm reloader: ")
// safe callbacks from SafeTimer are unneccessary. reload() can take a long
// time, so we don't want to hold the mutex and block handle_notify() for the
// duration
static constexpr bool USE_SAFE_TIMER_CALLBACKS = false;
RGWRealmReloader::RGWRealmReloader(RGWProcessEnv& env,
const rgw::auth::ImplicitTenants& implicit_tenants,
std::map<std::string, std::string>& service_map_meta,
Pauser* frontends)
: env(env),
implicit_tenants(implicit_tenants),
service_map_meta(service_map_meta),
frontends(frontends),
timer(env.driver->ctx(), mutex, USE_SAFE_TIMER_CALLBACKS),
mutex(ceph::make_mutex("RGWRealmReloader")),
reload_scheduled(nullptr)
{
timer.init();
}
RGWRealmReloader::~RGWRealmReloader()
{
std::lock_guard lock{mutex};
timer.shutdown();
}
class RGWRealmReloader::C_Reload : public Context {
RGWRealmReloader* reloader;
public:
explicit C_Reload(RGWRealmReloader* reloader) : reloader(reloader) {}
void finish(int r) override { reloader->reload(); }
};
void RGWRealmReloader::handle_notify(RGWRealmNotify type,
bufferlist::const_iterator& p)
{
if (!env.driver) {
/* we're in the middle of reload */
return;
}
CephContext *const cct = env.driver->ctx();
std::lock_guard lock{mutex};
if (reload_scheduled) {
ldout(cct, 4) << "Notification on realm, reconfiguration "
"already scheduled" << dendl;
return;
}
reload_scheduled = new C_Reload(this);
cond.notify_one(); // wake reload() if it blocked on a bad configuration
// schedule reload() without delay
timer.add_event_after(0, reload_scheduled);
ldout(cct, 4) << "Notification on realm, reconfiguration scheduled" << dendl;
}
void RGWRealmReloader::reload()
{
CephContext *const cct = env.driver->ctx();
const DoutPrefix dp(cct, dout_subsys, "rgw realm reloader: ");
ldpp_dout(&dp, 1) << "Pausing frontends for realm update..." << dendl;
frontends->pause();
ldpp_dout(&dp, 1) << "Frontends paused" << dendl;
// TODO: make RGWRados responsible for rgw_log_usage lifetime
rgw_log_usage_finalize();
// destroy the existing driver
DriverManager::close_storage(env.driver);
env.driver = nullptr;
ldpp_dout(&dp, 1) << "driver closed" << dendl;
{
// allow a new notify to reschedule us. it's important that we do this
// before we start loading the new realm, or we could miss some updates
std::lock_guard lock{mutex};
reload_scheduled = nullptr;
}
while (!env.driver) {
// reload the new configuration from ConfigStore
int r = env.site->load(&dp, null_yield, env.cfgstore);
if (r == 0) {
ldpp_dout(&dp, 1) << "Creating new driver" << dendl;
// recreate and initialize a new driver
DriverManager::Config cfg;
cfg.store_name = "rados";
cfg.filter_name = "none";
env.driver = DriverManager::get_storage(&dp, cct, cfg,
cct->_conf->rgw_enable_gc_threads,
cct->_conf->rgw_enable_lc_threads,
cct->_conf->rgw_enable_quota_threads,
cct->_conf->rgw_run_sync_thread,
cct->_conf.get_val<bool>("rgw_dynamic_resharding"),
true, null_yield, // run notification thread
cct->_conf->rgw_cache_enabled);
}
rgw::sal::Driver* store_cleanup = nullptr;
{
std::unique_lock lock{mutex};
// failure to recreate RGWRados is not a recoverable error, but we
// don't want to assert or abort the entire cluster. instead, just
// sleep until we get another notification, and retry until we get
// a working configuration
if (env.driver == nullptr) {
ldpp_dout(&dp, -1) << "Failed to reload realm after a period "
"configuration update. Waiting for a new update." << dendl;
// sleep until another event is scheduled
cond.wait(lock, [this] { return reload_scheduled; });
ldpp_dout(&dp, 1) << "Woke up with a new configuration, retrying "
"realm reload." << dendl;
}
if (reload_scheduled) {
// cancel the event; we'll handle it now
timer.cancel_event(reload_scheduled);
reload_scheduled = nullptr;
// if we successfully created a driver, clean it up outside of the lock,
// then continue to loop and recreate another
std::swap(env.driver, store_cleanup);
}
}
if (store_cleanup) {
ldpp_dout(&dp, 4) << "Got another notification, restarting realm "
"reload." << dendl;
DriverManager::close_storage(store_cleanup);
}
}
int r = env.driver->register_to_service_map(&dp, "rgw", service_map_meta);
if (r < 0) {
ldpp_dout(&dp, -1) << "ERROR: failed to register to service map: " << cpp_strerror(-r) << dendl;
/* ignore error */
}
ldpp_dout(&dp, 1) << "Finishing initialization of new driver" << dendl;
// finish initializing the new driver
ldpp_dout(&dp, 1) << " - REST subsystem init" << dendl;
rgw_rest_init(cct, env.driver->get_zone()->get_zonegroup());
ldpp_dout(&dp, 1) << " - usage subsystem init" << dendl;
rgw_log_usage_init(cct, env.driver);
/* Initialize the registry of auth strategies which will coordinate
* the dynamic reconfiguration. */
env.auth_registry = rgw::auth::StrategyRegistry::create(
cct, implicit_tenants, env.driver);
env.lua.manager = env.driver->get_lua_manager();
ldpp_dout(&dp, 1) << "Resuming frontends with new realm configuration." << dendl;
frontends->resume(env.driver);
}
| 6,092 | 30.734375 | 100 |
cc
|
null |
ceph-main/src/rgw/rgw_realm_reloader.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_realm_watcher.h"
#include "common/Cond.h"
#include "rgw_sal_fwd.h"
struct RGWProcessEnv;
namespace rgw::auth { class ImplicitTenants; }
/**
* RGWRealmReloader responds to new period notifications by recreating RGWRados
* with the updated realm configuration.
*/
class RGWRealmReloader : public RGWRealmWatcher::Watcher {
public:
/**
* Pauser is an interface to pause/resume frontends. Frontend cooperation
* is required to ensure that they stop issuing requests on the old
* RGWRados instance, and restart with the updated configuration.
*
* This abstraction avoids a dependency on class RGWFrontend.
*/
class Pauser {
public:
virtual ~Pauser() = default;
/// pause all frontends while realm reconfiguration is in progress
virtual void pause() = 0;
/// resume all frontends with the given RGWRados instance
virtual void resume(rgw::sal::Driver* driver) = 0;
};
RGWRealmReloader(RGWProcessEnv& env,
const rgw::auth::ImplicitTenants& implicit_tenants,
std::map<std::string, std::string>& service_map_meta,
Pauser* frontends);
~RGWRealmReloader() override;
/// respond to realm notifications by scheduling a reload()
void handle_notify(RGWRealmNotify type, bufferlist::const_iterator& p) override;
private:
/// pause frontends and replace the RGWRados instance
void reload();
class C_Reload; //< Context that calls reload()
RGWProcessEnv& env;
const rgw::auth::ImplicitTenants& implicit_tenants;
std::map<std::string, std::string>& service_map_meta;
Pauser *const frontends;
/// reload() takes a significant amount of time, so we don't want to run
/// it in the handle_notify() thread. we choose a timer thread instead of a
/// Finisher because it allows us to cancel events that were scheduled while
/// reload() is still running
SafeTimer timer;
ceph::mutex mutex; //< protects access to timer and reload_scheduled
ceph::condition_variable cond; //< to signal reload() after an invalid realm config
C_Reload* reload_scheduled; //< reload() context if scheduled
};
| 2,253 | 33.676923 | 85 |
h
|
null |
ceph-main/src/rgw/rgw_realm_watcher.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 "rgw_realm_watcher.h"
#include "rgw_tools.h"
#include "rgw_zone.h"
#define dout_subsys ceph_subsys_rgw
#undef dout_prefix
#define dout_prefix (*_dout << "rgw realm watcher: ")
RGWRealmWatcher::RGWRealmWatcher(const DoutPrefixProvider *dpp, CephContext* cct, const RGWRealm& realm)
: cct(cct)
{
// no default realm, nothing to watch
if (realm.get_id().empty()) {
ldpp_dout(dpp, 4) << "No realm, disabling dynamic reconfiguration." << dendl;
return;
}
// establish the watch on RGWRealm
int r = watch_start(dpp, realm);
if (r < 0) {
ldpp_dout(dpp, -1) << "Failed to establish a watch on RGWRealm, "
"disabling dynamic reconfiguration." << dendl;
return;
}
}
RGWRealmWatcher::~RGWRealmWatcher()
{
watch_stop();
}
void RGWRealmWatcher::add_watcher(RGWRealmNotify type, Watcher& watcher)
{
watchers.emplace(type, watcher);
}
void RGWRealmWatcher::handle_notify(uint64_t notify_id, uint64_t cookie,
uint64_t notifier_id, bufferlist& bl)
{
if (cookie != watch_handle)
return;
// send an empty notify ack
bufferlist reply;
pool_ctx.notify_ack(watch_oid, notify_id, cookie, reply);
try {
auto p = bl.cbegin();
while (!p.end()) {
RGWRealmNotify notify;
decode(notify, p);
auto watcher = watchers.find(notify);
if (watcher == watchers.end()) {
lderr(cct) << "Failed to find a watcher for notify type "
<< static_cast<int>(notify) << dendl;
break;
}
watcher->second.handle_notify(notify, p);
}
} catch (const buffer::error &e) {
lderr(cct) << "Failed to decode realm notifications." << dendl;
}
}
void RGWRealmWatcher::handle_error(uint64_t cookie, int err)
{
lderr(cct) << "RGWRealmWatcher::handle_error oid=" << watch_oid << " err=" << err << dendl;
if (cookie != watch_handle)
return;
watch_restart();
}
int RGWRealmWatcher::watch_start(const DoutPrefixProvider *dpp, const RGWRealm& realm)
{
// initialize a Rados client
int r = rados.init_with_context(cct);
if (r < 0) {
ldpp_dout(dpp, -1) << "Rados client initialization failed with "
<< cpp_strerror(-r) << dendl;
return r;
}
r = rados.connect();
if (r < 0) {
ldpp_dout(dpp, -1) << "Rados client connection failed with "
<< cpp_strerror(-r) << dendl;
return r;
}
// open an IoCtx for the realm's pool
rgw_pool pool(realm.get_pool(cct));
r = rgw_init_ioctx(dpp, &rados, pool, pool_ctx);
if (r < 0) {
ldpp_dout(dpp, -1) << "Failed to open pool " << pool
<< " with " << cpp_strerror(-r) << dendl;
rados.shutdown();
return r;
}
// register a watch on the realm's control object
auto oid = realm.get_control_oid();
r = pool_ctx.watch2(oid, &watch_handle, this);
if (r < 0) {
ldpp_dout(dpp, -1) << "Failed to watch " << oid
<< " with " << cpp_strerror(-r) << dendl;
pool_ctx.close();
rados.shutdown();
return r;
}
ldpp_dout(dpp, 10) << "Watching " << oid << dendl;
std::swap(watch_oid, oid);
return 0;
}
int RGWRealmWatcher::watch_restart()
{
ceph_assert(!watch_oid.empty());
int r = pool_ctx.unwatch2(watch_handle);
if (r < 0) {
lderr(cct) << "Failed to unwatch on " << watch_oid
<< " with " << cpp_strerror(-r) << dendl;
}
r = pool_ctx.watch2(watch_oid, &watch_handle, this);
if (r < 0) {
lderr(cct) << "Failed to restart watch on " << watch_oid
<< " with " << cpp_strerror(-r) << dendl;
pool_ctx.close();
watch_oid.clear();
}
return r;
}
void RGWRealmWatcher::watch_stop()
{
if (!watch_oid.empty()) {
pool_ctx.unwatch2(watch_handle);
pool_ctx.close();
watch_oid.clear();
}
}
| 3,845 | 24.812081 | 104 |
cc
|
null |
ceph-main/src/rgw/rgw_realm_watcher.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 "include/ceph_assert.h"
#include "common/Timer.h"
#include "common/Cond.h"
class RGWRados;
class RGWRealm;
enum class RGWRealmNotify {
Reload,
ZonesNeedPeriod,
};
WRITE_RAW_ENCODER(RGWRealmNotify);
/**
* RGWRealmWatcher establishes a watch on the current RGWRealm's control object,
* and forwards notifications to registered observers.
*/
class RGWRealmWatcher : public librados::WatchCtx2 {
public:
/**
* Watcher is an interface that allows the RGWRealmWatcher to pass
* notifications on to other interested objects.
*/
class Watcher {
public:
virtual ~Watcher() = default;
virtual void handle_notify(RGWRealmNotify type,
bufferlist::const_iterator& p) = 0;
};
RGWRealmWatcher(const DoutPrefixProvider *dpp, CephContext* cct, const RGWRealm& realm);
~RGWRealmWatcher() override;
/// register a watcher for the given notification type
void add_watcher(RGWRealmNotify type, Watcher& watcher);
/// respond to realm notifications by calling the appropriate watcher
void handle_notify(uint64_t notify_id, uint64_t cookie,
uint64_t notifier_id, bufferlist& bl) override;
/// reestablish the watch if it gets disconnected
void handle_error(uint64_t cookie, int err) override;
private:
CephContext *const cct;
/// keep a separate Rados client whose lifetime is independent of RGWRados
/// so that we don't miss notifications during realm reconfiguration
librados::Rados rados;
librados::IoCtx pool_ctx;
uint64_t watch_handle = 0;
std::string watch_oid;
int watch_start(const DoutPrefixProvider *dpp, const RGWRealm& realm);
int watch_restart();
void watch_stop();
std::map<RGWRealmNotify, Watcher&> watchers;
};
| 1,909 | 27.507463 | 90 |
h
|
null |
ceph-main/src/rgw/rgw_request.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"
#include "rgw_acl.h"
#include "rgw_user.h"
#include "rgw_op.h"
#include "common/QueueRing.h"
#include <atomic>
struct RGWRequest
{
uint64_t id;
req_state *s;
RGWOp *op;
explicit RGWRequest(uint64_t id) : id(id), s(NULL), op(NULL) {}
virtual ~RGWRequest() {}
void init_state(req_state *_s) {
s = _s;
}
}; /* RGWRequest */
struct RGWLoadGenRequest : public RGWRequest {
std::string method;
std::string resource;
int content_length;
std::atomic<bool>* fail_flag = nullptr;
RGWLoadGenRequest(uint64_t req_id, const std::string& _m, const std::string& _r, int _cl,
std::atomic<bool> *ff)
: RGWRequest(req_id), method(_m), resource(_r), content_length(_cl),
fail_flag(ff) {}
};
| 851 | 19.780488 | 89 |
h
|
null |
ceph-main/src/rgw/rgw_resolve.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include "acconfig.h"
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
#include <arpa/nameser_compat.h>
#endif
#include "rgw_common.h"
#include "rgw_resolve.h"
#include "common/dns_resolve.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
RGWResolver::~RGWResolver() {
}
RGWResolver::RGWResolver() {
resolver = DNSResolver::get_instance();
}
int RGWResolver::resolve_cname(const string& hostname, string& cname, bool *found) {
return resolver->resolve_cname(g_ceph_context, hostname, &cname, found);
}
RGWResolver *rgw_resolver;
void rgw_init_resolver()
{
rgw_resolver = new RGWResolver();
}
void rgw_shutdown_resolver()
{
delete rgw_resolver;
}
| 860 | 17.717391 | 84 |
cc
|
null |
ceph-main/src/rgw/rgw_resolve.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"
namespace ceph {
class DNSResolver;
}
class RGWResolver {
DNSResolver *resolver;
public:
~RGWResolver();
RGWResolver();
int resolve_cname(const std::string& hostname, std::string& cname, bool *found);
};
extern void rgw_init_resolver(void);
extern void rgw_shutdown_resolver(void);
extern RGWResolver *rgw_resolver;
| 475 | 18.04 | 82 |
h
|
null |
ceph-main/src/rgw/rgw_rest.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 <limits.h>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include "ceph_ver.h"
#include "common/Formatter.h"
#include "common/HTMLFormatter.h"
#include "common/utf8.h"
#include "include/str_list.h"
#include "rgw_common.h"
#include "rgw_rados.h"
#include "rgw_zone.h"
#include "rgw_auth_s3.h"
#include "rgw_formats.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_rest_swift.h"
#include "rgw_rest_s3.h"
#include "rgw_swift_auth.h"
#include "rgw_cors_s3.h"
#include "rgw_perf_counters.h"
#include "rgw_client_io.h"
#include "rgw_resolve.h"
#include "rgw_sal_rados.h"
#include "rgw_ratelimit.h"
#include <numeric>
#define dout_subsys ceph_subsys_rgw
using namespace std;
struct rgw_http_status_code {
int code;
const char *name;
};
const static struct rgw_http_status_code http_codes[] = {
{ 100, "Continue" },
{ 200, "OK" },
{ 201, "Created" },
{ 202, "Accepted" },
{ 204, "No Content" },
{ 205, "Reset Content" },
{ 206, "Partial Content" },
{ 207, "Multi Status" },
{ 208, "Already Reported" },
{ 300, "Multiple Choices" },
{ 301, "Moved Permanently" },
{ 302, "Found" },
{ 303, "See Other" },
{ 304, "Not Modified" },
{ 305, "User Proxy" },
{ 306, "Switch Proxy" },
{ 307, "Temporary Redirect" },
{ 308, "Permanent Redirect" },
{ 400, "Bad Request" },
{ 401, "Unauthorized" },
{ 402, "Payment Required" },
{ 403, "Forbidden" },
{ 404, "Not Found" },
{ 405, "Method Not Allowed" },
{ 406, "Not Acceptable" },
{ 407, "Proxy Authentication Required" },
{ 408, "Request Timeout" },
{ 409, "Conflict" },
{ 410, "Gone" },
{ 411, "Length Required" },
{ 412, "Precondition Failed" },
{ 413, "Request Entity Too Large" },
{ 414, "Request-URI Too Long" },
{ 415, "Unsupported Media Type" },
{ 416, "Requested Range Not Satisfiable" },
{ 417, "Expectation Failed" },
{ 422, "Unprocessable Entity" },
{ 498, "Rate Limited"},
{ 500, "Internal Server Error" },
{ 501, "Not Implemented" },
{ 503, "Slow Down"},
{ 0, NULL },
};
struct rgw_http_attr {
const char *rgw_attr;
const char *http_attr;
};
/*
* mapping between rgw object attrs and output http fields
*/
static const struct rgw_http_attr base_rgw_to_http_attrs[] = {
{ RGW_ATTR_CONTENT_LANG, "Content-Language" },
{ RGW_ATTR_EXPIRES, "Expires" },
{ RGW_ATTR_CACHE_CONTROL, "Cache-Control" },
{ RGW_ATTR_CONTENT_DISP, "Content-Disposition" },
{ RGW_ATTR_CONTENT_ENC, "Content-Encoding" },
{ RGW_ATTR_USER_MANIFEST, "X-Object-Manifest" },
{ RGW_ATTR_X_ROBOTS_TAG , "X-Robots-Tag" },
{ RGW_ATTR_STORAGE_CLASS , "X-Amz-Storage-Class" },
/* RGW_ATTR_AMZ_WEBSITE_REDIRECT_LOCATION header depends on access mode:
* S3 endpoint: x-amz-website-redirect-location
* S3Website endpoint: Location
*/
{ RGW_ATTR_AMZ_WEBSITE_REDIRECT_LOCATION, "x-amz-website-redirect-location" },
};
struct generic_attr {
const char *http_header;
const char *rgw_attr;
};
/*
* mapping between http env fields and rgw object attrs
*/
static const struct generic_attr generic_attrs[] = {
{ "CONTENT_TYPE", RGW_ATTR_CONTENT_TYPE },
{ "HTTP_CONTENT_LANGUAGE", RGW_ATTR_CONTENT_LANG },
{ "HTTP_EXPIRES", RGW_ATTR_EXPIRES },
{ "HTTP_CACHE_CONTROL", RGW_ATTR_CACHE_CONTROL },
{ "HTTP_CONTENT_DISPOSITION", RGW_ATTR_CONTENT_DISP },
{ "HTTP_CONTENT_ENCODING", RGW_ATTR_CONTENT_ENC },
{ "HTTP_X_ROBOTS_TAG", RGW_ATTR_X_ROBOTS_TAG },
};
map<string, string> rgw_to_http_attrs;
static map<string, string> generic_attrs_map;
map<int, const char *> http_status_names;
/*
* make attrs look_like_this
* converts dashes to underscores
*/
string lowercase_underscore_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) {
switch (*s) {
case '-':
buf[i] = '_';
break;
default:
buf[i] = tolower(*s);
}
}
return string(buf);
}
/*
* make attrs LOOK_LIKE_THIS
* converts dashes to underscores
*/
string uppercase_underscore_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) {
switch (*s) {
case '-':
buf[i] = '_';
break;
default:
buf[i] = toupper(*s);
}
}
return string(buf);
}
/* avoid duplicate hostnames in hostnames lists */
static set<string> hostnames_set;
static set<string> hostnames_s3website_set;
void rgw_rest_init(CephContext *cct, const rgw::sal::ZoneGroup& zone_group)
{
for (const auto& rgw2http : base_rgw_to_http_attrs) {
rgw_to_http_attrs[rgw2http.rgw_attr] = rgw2http.http_attr;
}
for (const auto& http2rgw : generic_attrs) {
generic_attrs_map[http2rgw.http_header] = http2rgw.rgw_attr;
}
list<string> extended_http_attrs;
get_str_list(cct->_conf->rgw_extended_http_attrs, extended_http_attrs);
list<string>::iterator iter;
for (iter = extended_http_attrs.begin(); iter != extended_http_attrs.end(); ++iter) {
string rgw_attr = RGW_ATTR_PREFIX;
rgw_attr.append(lowercase_underscore_http_attr(*iter));
rgw_to_http_attrs[rgw_attr] = camelcase_dash_http_attr(*iter);
string http_header = "HTTP_";
http_header.append(uppercase_underscore_http_attr(*iter));
generic_attrs_map[http_header] = rgw_attr;
}
for (const struct rgw_http_status_code *h = http_codes; h->code; h++) {
http_status_names[h->code] = h->name;
}
std::list<std::string> rgw_dns_names;
std::string rgw_dns_names_str = cct->_conf->rgw_dns_name;
get_str_list(rgw_dns_names_str, ", ", rgw_dns_names);
hostnames_set.insert(rgw_dns_names.begin(), rgw_dns_names.end());
std::list<std::string> names;
zone_group.get_hostnames(names);
hostnames_set.insert(names.begin(), names.end());
hostnames_set.erase(""); // filter out empty hostnames
ldout(cct, 20) << "RGW hostnames: " << hostnames_set << dendl;
/* TODO: We should have a sanity check that no hostname matches the end of
* any other hostname, otherwise we will get ambigious results from
* rgw_find_host_in_domains.
* Eg:
* Hostnames: [A, B.A]
* Inputs: [Z.A, X.B.A]
* Z.A clearly splits to subdomain=Z, domain=Z
* X.B.A ambigously splits to both {X, B.A} and {X.B, A}
*/
zone_group.get_s3website_hostnames(names);
hostnames_s3website_set.insert(cct->_conf->rgw_dns_s3website_name);
hostnames_s3website_set.insert(names.begin(), names.end());
hostnames_s3website_set.erase(""); // filter out empty hostnames
ldout(cct, 20) << "RGW S3website hostnames: " << hostnames_s3website_set << dendl;
/* TODO: we should repeat the hostnames_set sanity check here
* and ALSO decide about overlap, if any
*/
}
static bool str_ends_with_nocase(const string& s, const string& suffix, size_t *pos)
{
size_t len = suffix.size();
if (len > (size_t)s.size()) {
return false;
}
ssize_t p = s.size() - len;
if (pos) {
*pos = p;
}
return boost::algorithm::iends_with(s, suffix);
}
static bool rgw_find_host_in_domains(const string& host, string *domain, string *subdomain,
const set<string>& valid_hostnames_set)
{
set<string>::iterator iter;
/** TODO, Future optimization
* store hostnames_set elements _reversed_, and look for a prefix match,
* which is much faster than a suffix match.
*/
for (iter = valid_hostnames_set.begin(); iter != valid_hostnames_set.end(); ++iter) {
size_t pos;
if (!str_ends_with_nocase(host, *iter, &pos))
continue;
if (pos == 0) {
*domain = host;
subdomain->clear();
} else {
if (host[pos - 1] != '.') {
continue;
}
*domain = host.substr(pos);
*subdomain = host.substr(0, pos - 1);
}
return true;
}
return false;
}
static void dump_status(req_state *s, int status,
const char *status_name)
{
if (s->formatter) {
s->formatter->set_status(status, status_name);
}
try {
RESTFUL_IO(s)->send_status(status, status_name);
} catch (rgw::io::Exception& e) {
ldpp_dout(s, 0) << "ERROR: s->cio->send_status() returned err="
<< e.what() << dendl;
}
}
void rgw_flush_formatter_and_reset(req_state *s, Formatter *formatter)
{
std::ostringstream oss;
formatter->output_footer();
formatter->flush(oss);
std::string outs(oss.str());
if (!outs.empty() && s->op != OP_HEAD) {
dump_body(s, outs);
}
s->formatter->reset();
}
void rgw_flush_formatter(req_state *s, Formatter *formatter)
{
std::ostringstream oss;
formatter->flush(oss);
std::string outs(oss.str());
if (!outs.empty() && s->op != OP_HEAD) {
dump_body(s, outs);
}
}
void dump_errno(int http_ret, string& out) {
stringstream ss;
ss << http_ret << " " << http_status_names[http_ret];
out = ss.str();
}
void dump_errno(const struct rgw_err &err, string& out) {
dump_errno(err.http_ret, out);
}
void dump_errno(req_state *s)
{
dump_status(s, s->err.http_ret, http_status_names[s->err.http_ret]);
}
void dump_errno(req_state *s, int http_ret)
{
dump_status(s, http_ret, http_status_names[http_ret]);
}
void dump_header(req_state* const s,
const std::string_view& name,
const std::string_view& val)
{
try {
RESTFUL_IO(s)->send_header(name, val);
} catch (rgw::io::Exception& e) {
ldpp_dout(s, 0) << "ERROR: s->cio->send_header() returned err="
<< e.what() << dendl;
}
}
void dump_header(req_state* const s,
const std::string_view& name,
ceph::buffer::list& bl)
{
return dump_header(s, name, rgw_sanitized_hdrval(bl));
}
void dump_header(req_state* const s,
const std::string_view& name,
const long long val)
{
char buf[32];
const auto len = snprintf(buf, sizeof(buf), "%lld", val);
return dump_header(s, name, std::string_view(buf, len));
}
void dump_header(req_state* const s,
const std::string_view& name,
const utime_t& ut)
{
char buf[32];
const auto len = snprintf(buf, sizeof(buf), "%lld.%05d",
static_cast<long long>(ut.sec()),
static_cast<int>(ut.usec() / 10));
return dump_header(s, name, std::string_view(buf, len));
}
void dump_content_length(req_state* const s, const uint64_t len)
{
try {
RESTFUL_IO(s)->send_content_length(len);
} catch (rgw::io::Exception& e) {
ldpp_dout(s, 0) << "ERROR: s->cio->send_content_length() returned err="
<< e.what() << dendl;
}
dump_header(s, "Accept-Ranges", "bytes");
}
static void dump_chunked_encoding(req_state* const s)
{
try {
RESTFUL_IO(s)->send_chunked_transfer_encoding();
} catch (rgw::io::Exception& e) {
ldpp_dout(s, 0) << "ERROR: RESTFUL_IO(s)->send_chunked_transfer_encoding()"
<< " returned err=" << e.what() << dendl;
}
}
void dump_etag(req_state* const s,
const std::string_view& etag,
const bool quoted)
{
if (etag.empty()) {
return;
}
if (s->prot_flags & RGW_REST_SWIFT && ! quoted) {
return dump_header(s, "etag", etag);
} else {
return dump_header_quoted(s, "ETag", etag);
}
}
void dump_bucket_from_state(req_state *s)
{
if (g_conf()->rgw_expose_bucket && ! s->bucket_name.empty()) {
if (! s->bucket_tenant.empty()) {
dump_header(s, "Bucket",
url_encode(s->bucket_tenant + "/" + s->bucket_name));
} else {
dump_header(s, "Bucket", url_encode(s->bucket_name));
}
}
}
void dump_redirect(req_state * const s, const std::string& redirect)
{
return dump_header_if_nonempty(s, "Location", redirect);
}
static size_t dump_time_header_impl(char (×tr)[TIME_BUF_SIZE],
const real_time t)
{
const utime_t ut(t);
time_t secs = static_cast<time_t>(ut.sec());
struct tm result;
const struct tm * const tmp = gmtime_r(&secs, &result);
if (tmp == nullptr) {
return 0;
}
return strftime(timestr, sizeof(timestr),
"%a, %d %b %Y %H:%M:%S %Z", tmp);
}
void dump_time_header(req_state *s, const char *name, real_time t)
{
char timestr[TIME_BUF_SIZE];
const size_t len = dump_time_header_impl(timestr, t);
if (len == 0) {
return;
}
return dump_header(s, name, std::string_view(timestr, len));
}
std::string dump_time_to_str(const real_time& t)
{
char timestr[TIME_BUF_SIZE];
dump_time_header_impl(timestr, t);
return timestr;
}
void dump_last_modified(req_state *s, real_time t)
{
dump_time_header(s, "Last-Modified", t);
}
void dump_epoch_header(req_state *s, const char *name, real_time t)
{
utime_t ut(t);
char buf[65];
const auto len = snprintf(buf, sizeof(buf), "%lld.%09lld",
(long long)ut.sec(),
(long long)ut.nsec());
return dump_header(s, name, std::string_view(buf, len));
}
void dump_time(req_state *s, const char *name, real_time t)
{
char buf[TIME_BUF_SIZE];
rgw_to_iso8601(t, buf, sizeof(buf));
s->formatter->dump_string(name, buf);
}
void dump_owner(req_state *s, const rgw_user& id, const string& name,
const char *section)
{
if (!section)
section = "Owner";
s->formatter->open_object_section(section);
s->formatter->dump_string("ID", id.to_str());
s->formatter->dump_string("DisplayName", name);
s->formatter->close_section();
}
void dump_access_control(req_state *s, const char *origin,
const char *meth,
const char *hdr, const char *exp_hdr,
uint32_t max_age) {
if (origin && (origin[0] != '\0')) {
dump_header(s, "Access-Control-Allow-Origin", origin);
/* If the server specifies an origin host rather than "*",
* then it must also include Origin in the Vary response header
* to indicate to clients that server responses will differ
* based on the value of the Origin request header.
*/
if (strcmp(origin, "*") != 0) {
dump_header(s, "Vary", "Origin");
}
if (meth && (meth[0] != '\0')) {
dump_header(s, "Access-Control-Allow-Methods", meth);
}
if (hdr && (hdr[0] != '\0')) {
dump_header(s, "Access-Control-Allow-Headers", hdr);
}
if (exp_hdr && (exp_hdr[0] != '\0')) {
dump_header(s, "Access-Control-Expose-Headers", exp_hdr);
}
if (max_age != CORS_MAX_AGE_INVALID) {
dump_header(s, "Access-Control-Max-Age", max_age);
}
}
}
void dump_access_control(req_state *s, RGWOp *op)
{
string origin;
string method;
string header;
string exp_header;
unsigned max_age = CORS_MAX_AGE_INVALID;
if (!op->generate_cors_headers(origin, method, header, exp_header, &max_age))
return;
dump_access_control(s, origin.c_str(), method.c_str(), header.c_str(),
exp_header.c_str(), max_age);
}
void dump_start(req_state *s)
{
if (!s->content_started) {
s->formatter->output_header();
s->content_started = true;
}
}
void dump_trans_id(req_state *s)
{
if (s->prot_flags & RGW_REST_SWIFT) {
dump_header(s, "X-Trans-Id", s->trans_id);
dump_header(s, "X-Openstack-Request-Id", s->trans_id);
} else if (s->trans_id.length()) {
dump_header(s, "x-amz-request-id", s->trans_id);
}
}
void end_header(req_state* s, RGWOp* op, const char *content_type,
const int64_t proposed_content_length, bool force_content_type,
bool force_no_error)
{
string ctype;
dump_trans_id(s);
if ((!s->is_err()) && s->bucket &&
(s->bucket->get_info().owner != s->user->get_id()) &&
(s->bucket->get_info().requester_pays)) {
dump_header(s, "x-amz-request-charged", "requester");
}
if (op) {
dump_access_control(s, op);
}
if (s->prot_flags & RGW_REST_SWIFT && !content_type) {
force_content_type = true;
}
/* do not send content type if content length is zero
and the content type was not set by the user */
if (force_content_type || s->is_err() ||
(!content_type && s->formatter && s->formatter->get_len() != 0)) {
ctype = to_mime_type(s->format);
if (s->prot_flags & RGW_REST_SWIFT)
ctype.append("; charset=utf-8");
content_type = ctype.c_str();
}
if (!force_no_error && s->is_err()) {
dump_start(s);
dump(s);
dump_content_length(s, s->formatter ? s->formatter->get_len() : 0);
} else {
if (proposed_content_length == CHUNKED_TRANSFER_ENCODING) {
dump_chunked_encoding(s);
} else if (proposed_content_length != NO_CONTENT_LENGTH) {
dump_content_length(s, proposed_content_length);
}
}
if (content_type) {
dump_header(s, "Content-Type", content_type);
}
std::string srv = g_conf().get_val<std::string>("rgw_service_provider_name");
if (!srv.empty()) {
dump_header(s, "Server", srv);
} else {
dump_header(s, "Server", "Ceph Object Gateway (" CEPH_RELEASE_NAME ")");
}
try {
RESTFUL_IO(s)->complete_header();
} catch (rgw::io::Exception& e) {
ldpp_dout(s, 0) << "ERROR: RESTFUL_IO(s)->complete_header() returned err="
<< e.what() << dendl;
}
ACCOUNTING_IO(s)->set_account(true);
if (s->formatter) {
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
static void build_redirect_url(req_state *s, const string& redirect_base, string *redirect_url)
{
string& dest_uri = *redirect_url;
dest_uri = redirect_base;
/*
* reqest_uri is always start with slash, so we need to remove
* the unnecessary slash at the end of dest_uri.
*/
if (dest_uri[dest_uri.size() - 1] == '/') {
dest_uri = dest_uri.substr(0, dest_uri.size() - 1);
}
dest_uri += s->info.request_uri;
dest_uri += "?";
dest_uri += s->info.request_params;
}
void abort_early(req_state *s, RGWOp* op, int err_no,
RGWHandler* handler, optional_yield y)
{
string error_content("");
if (!s->formatter) {
s->formatter = new JSONFormatter;
s->format = RGWFormat::JSON;
}
// op->error_handler is responsible for calling it's handler error_handler
if (op != NULL) {
int new_err_no;
new_err_no = op->error_handler(err_no, &error_content, y);
ldpp_dout(s, 1) << "op->ERRORHANDLER: err_no=" << err_no
<< " new_err_no=" << new_err_no << dendl;
err_no = new_err_no;
} else if (handler != NULL) {
int new_err_no;
new_err_no = handler->error_handler(err_no, &error_content, y);
ldpp_dout(s, 1) << "handler->ERRORHANDLER: err_no=" << err_no
<< " new_err_no=" << new_err_no << dendl;
err_no = new_err_no;
}
// If the error handler(s) above dealt with it completely, they should have
// returned 0. If non-zero, we need to continue here.
if (err_no) {
// Watch out, we might have a custom error state already set!
if (!s->err.http_ret || s->err.http_ret == 200) {
set_req_state_err(s, err_no);
}
if (s->err.http_ret == 404 && !s->redirect_zone_endpoint.empty()) {
s->err.http_ret = 301;
err_no = -ERR_PERMANENT_REDIRECT;
build_redirect_url(s, s->redirect_zone_endpoint, &s->redirect);
}
dump_errno(s);
dump_bucket_from_state(s);
if (err_no == -ERR_PERMANENT_REDIRECT || err_no == -ERR_WEBSITE_REDIRECT) {
string dest_uri;
if (!s->redirect.empty()) {
dest_uri = s->redirect;
} else if (!s->zonegroup_endpoint.empty()) {
build_redirect_url(s, s->zonegroup_endpoint, &dest_uri);
}
if (!dest_uri.empty()) {
dump_redirect(s, dest_uri);
}
}
if (!error_content.empty()) {
/*
* TODO we must add all error entries as headers here:
* when having a working errordoc, then the s3 error fields are
* rendered as HTTP headers, e.g.:
* x-amz-error-code: NoSuchKey
* x-amz-error-message: The specified key does not exist.
* x-amz-error-detail-Key: foo
*/
end_header(s, op, NULL, error_content.size(), false, true);
RESTFUL_IO(s)->send_body(error_content.c_str(), error_content.size());
} else {
end_header(s, op);
}
}
perfcounter->inc(l_rgw_failed_req);
}
void dump_continue(req_state * const s)
{
try {
RESTFUL_IO(s)->send_100_continue();
} catch (rgw::io::Exception& e) {
ldpp_dout(s, 0) << "ERROR: RESTFUL_IO(s)->send_100_continue() returned err="
<< e.what() << dendl;
}
}
void dump_range(req_state* const s,
const uint64_t ofs,
const uint64_t end,
const uint64_t total)
{
/* dumping range into temp buffer first, as libfcgi will fail to digest
* %lld */
char range_buf[128];
size_t len;
if (! total) {
len = snprintf(range_buf, sizeof(range_buf), "bytes */%lld",
static_cast<long long>(total));
} else {
len = snprintf(range_buf, sizeof(range_buf), "bytes %lld-%lld/%lld",
static_cast<long long>(ofs),
static_cast<long long>(end),
static_cast<long long>(total));
}
return dump_header(s, "Content-Range", std::string_view(range_buf, len));
}
int dump_body(req_state* const s,
const char* const buf,
const size_t len)
{
bool healthchk = false;
// we dont want to limit health checks
if(s->op_type == RGW_OP_GET_HEALTH_CHECK)
healthchk = true;
if(len > 0 && !healthchk) {
const char *method = s->info.method;
s->ratelimit_data->decrease_bytes(method, s->ratelimit_user_name, len, &s->user_ratelimit);
if(!rgw::sal::Bucket::empty(s->bucket.get()))
s->ratelimit_data->decrease_bytes(method, s->ratelimit_bucket_marker, len, &s->bucket_ratelimit);
}
try {
return RESTFUL_IO(s)->send_body(buf, len);
} catch (rgw::io::Exception& e) {
return -e.code().value();
}
}
int dump_body(req_state* const s, /* const */ ceph::buffer::list& bl)
{
return dump_body(s, bl.c_str(), bl.length());
}
int dump_body(req_state* const s, const std::string& str)
{
return dump_body(s, str.c_str(), str.length());
}
int recv_body(req_state* const s,
char* const buf,
const size_t max)
{
int len;
try {
len = RESTFUL_IO(s)->recv_body(buf, max);
} catch (rgw::io::Exception& e) {
return -e.code().value();
}
bool healthchk = false;
// we dont want to limit health checks
if(s->op_type == RGW_OP_GET_HEALTH_CHECK)
healthchk = true;
if(len > 0 && !healthchk) {
const char *method = s->info.method;
s->ratelimit_data->decrease_bytes(method, s->ratelimit_user_name, len, &s->user_ratelimit);
if(!rgw::sal::Bucket::empty(s->bucket.get()))
s->ratelimit_data->decrease_bytes(method, s->ratelimit_bucket_marker, len, &s->bucket_ratelimit);
}
return len;
}
int RGWGetObj_ObjStore::get_params(optional_yield y)
{
range_str = s->info.env->get("HTTP_RANGE");
if_mod = s->info.env->get("HTTP_IF_MODIFIED_SINCE");
if_unmod = s->info.env->get("HTTP_IF_UNMODIFIED_SINCE");
if_match = s->info.env->get("HTTP_IF_MATCH");
if_nomatch = s->info.env->get("HTTP_IF_NONE_MATCH");
if (s->system_request) {
mod_zone_id = s->info.env->get_int("HTTP_DEST_ZONE_SHORT_ID", 0);
mod_pg_ver = s->info.env->get_int("HTTP_DEST_PG_VER", 0);
rgwx_stat = s->info.args.exists(RGW_SYS_PARAM_PREFIX "stat");
get_data &= (!rgwx_stat);
}
return 0;
}
int RESTArgs::get_string(req_state *s, const string& name,
const string& def_val, string *val, bool *existed)
{
bool exists;
*val = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
return 0;
}
int RESTArgs::get_uint64(req_state *s, const string& name,
uint64_t def_val, uint64_t *val, bool *existed)
{
bool exists;
string sval = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
int r = stringtoull(sval, val);
if (r < 0)
return r;
return 0;
}
int RESTArgs::get_int64(req_state *s, const string& name,
int64_t def_val, int64_t *val, bool *existed)
{
bool exists;
string sval = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
int r = stringtoll(sval, val);
if (r < 0)
return r;
return 0;
}
int RESTArgs::get_uint32(req_state *s, const string& name,
uint32_t def_val, uint32_t *val, bool *existed)
{
bool exists;
string sval = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
int r = stringtoul(sval, val);
if (r < 0)
return r;
return 0;
}
int RESTArgs::get_int32(req_state *s, const string& name,
int32_t def_val, int32_t *val, bool *existed)
{
bool exists;
string sval = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
int r = stringtol(sval, val);
if (r < 0)
return r;
return 0;
}
int RESTArgs::get_time(req_state *s, const string& name,
const utime_t& def_val, utime_t *val, bool *existed)
{
bool exists;
string sval = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
uint64_t epoch, nsec;
int r = utime_t::parse_date(sval, &epoch, &nsec);
if (r < 0)
return r;
*val = utime_t(epoch, nsec);
return 0;
}
int RESTArgs::get_epoch(req_state *s, const string& name, uint64_t def_val, uint64_t *epoch, bool *existed)
{
bool exists;
string date = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*epoch = def_val;
return 0;
}
int r = utime_t::parse_date(date, epoch, NULL);
if (r < 0)
return r;
return 0;
}
int RESTArgs::get_bool(req_state *s, const string& name, bool def_val, bool *val, bool *existed)
{
bool exists;
string sval = s->info.args.get(name, &exists);
if (existed)
*existed = exists;
if (!exists) {
*val = def_val;
return 0;
}
const char *str = sval.c_str();
if (sval.empty() ||
strcasecmp(str, "true") == 0 ||
sval.compare("1") == 0) {
*val = true;
return 0;
}
if (strcasecmp(str, "false") != 0 &&
sval.compare("0") != 0) {
*val = def_val;
return -EINVAL;
}
*val = false;
return 0;
}
void RGWRESTFlusher::do_start(int ret)
{
set_req_state_err(s, ret); /* no going back from here */
dump_errno(s);
dump_start(s);
end_header(s, op);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWRESTFlusher::do_flush()
{
rgw_flush_formatter(s, s->formatter);
}
int RGWPutObj_ObjStore::verify_params()
{
if (s->length) {
off_t len = atoll(s->length);
if (len > (off_t)(s->cct->_conf->rgw_max_put_size)) {
return -ERR_TOO_LARGE;
}
}
return 0;
}
int RGWPutObj_ObjStore::get_params(optional_yield y)
{
supplied_md5_b64 = s->info.env->get("HTTP_CONTENT_MD5");
return 0;
}
int RGWPutObj_ObjStore::get_data(bufferlist& bl)
{
size_t cl;
uint64_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
if (s->length) {
cl = atoll(s->length) - ofs;
if (cl > chunk_size)
cl = chunk_size;
} else {
cl = chunk_size;
}
int len = 0;
{
ACCOUNTING_IO(s)->set_account(true);
bufferptr bp(cl);
const auto read_len = recv_body(s, bp.c_str(), cl);
if (read_len < 0) {
return read_len;
}
len = read_len;
bl.append(bp, 0, len);
ACCOUNTING_IO(s)->set_account(false);
}
if ((uint64_t)ofs + len > s->cct->_conf->rgw_max_put_size) {
return -ERR_TOO_LARGE;
}
return len;
}
/*
* parses params in the format: 'first; param1=foo; param2=bar'
*/
void RGWPostObj_ObjStore::parse_boundary_params(const std::string& params_str,
std::string& first,
std::map<std::string,
std::string>& params)
{
size_t pos = params_str.find(';');
if (std::string::npos == pos) {
first = rgw_trim_whitespace(params_str);
return;
}
first = rgw_trim_whitespace(params_str.substr(0, pos));
pos++;
while (pos < params_str.size()) {
size_t end = params_str.find(';', pos);
if (std::string::npos == end) {
end = params_str.size();
}
std::string param = params_str.substr(pos, end - pos);
size_t eqpos = param.find('=');
if (std::string::npos != eqpos) {
std::string param_name = rgw_trim_whitespace(param.substr(0, eqpos));
std::string val = rgw_trim_quotes(param.substr(eqpos + 1));
params[std::move(param_name)] = std::move(val);
} else {
params[rgw_trim_whitespace(param)] = "";
}
pos = end + 1;
}
}
int RGWPostObj_ObjStore::parse_part_field(const std::string& line,
std::string& field_name, /* out */
post_part_field& field) /* out */
{
size_t pos = line.find(':');
if (pos == string::npos)
return -EINVAL;
field_name = line.substr(0, pos);
if (pos >= line.size() - 1)
return 0;
parse_boundary_params(line.substr(pos + 1), field.val, field.params);
return 0;
}
static bool is_crlf(const char *s)
{
return (*s == '\r' && *(s + 1) == '\n');
}
/*
* find the index of the boundary, if exists, or optionally the next end of line
* also returns how many bytes to skip
*/
static int index_of(ceph::bufferlist& bl,
uint64_t max_len,
const std::string& str,
const bool check_crlf,
bool& reached_boundary,
int& skip)
{
reached_boundary = false;
skip = 0;
if (str.size() < 2) // we assume boundary is at least 2 chars (makes it easier with crlf checks)
return -EINVAL;
if (bl.length() < str.size())
return -1;
const char *buf = bl.c_str();
const char *s = str.c_str();
if (max_len > bl.length())
max_len = bl.length();
for (uint64_t i = 0; i < max_len; i++, buf++) {
if (check_crlf &&
i >= 1 &&
is_crlf(buf - 1)) {
return i + 1; // skip the crlf
}
if ((i < max_len - str.size() + 1) &&
(buf[0] == s[0] && buf[1] == s[1]) &&
(strncmp(buf, s, str.size()) == 0)) {
reached_boundary = true;
skip = str.size();
/* oh, great, now we need to swallow the preceding crlf
* if exists
*/
if ((i >= 2) &&
is_crlf(buf - 2)) {
i -= 2;
skip += 2;
}
return i;
}
}
return -1;
}
int RGWPostObj_ObjStore::read_with_boundary(ceph::bufferlist& bl,
uint64_t max,
const bool check_crlf,
bool& reached_boundary,
bool& done)
{
uint64_t cl = max + 2 + boundary.size();
if (max > in_data.length()) {
uint64_t need_to_read = cl - in_data.length();
bufferptr bp(need_to_read);
const auto read_len = recv_body(s, bp.c_str(), need_to_read);
if (read_len < 0) {
return read_len;
}
in_data.append(bp, 0, read_len);
}
done = false;
int skip;
const int index = index_of(in_data, cl, boundary, check_crlf,
reached_boundary, skip);
if (index >= 0) {
max = index;
}
if (max > in_data.length()) {
max = in_data.length();
}
bl.substr_of(in_data, 0, max);
ceph::bufferlist new_read_data;
/*
* now we need to skip boundary for next time, also skip any crlf, or
* check to see if it's the last final boundary (marked with "--" at the end
*/
if (reached_boundary) {
int left = in_data.length() - max;
if (left < skip + 2) {
int need = skip + 2 - left;
bufferptr boundary_bp(need);
const int r = recv_body(s, boundary_bp.c_str(), need);
if (r < 0) {
return r;
}
in_data.append(boundary_bp);
}
max += skip; // skip boundary for next time
if (in_data.length() >= max + 2) {
const char *data = in_data.c_str();
if (is_crlf(data + max)) {
max += 2;
} else {
if (*(data + max) == '-' &&
*(data + max + 1) == '-') {
done = true;
max += 2;
}
}
}
}
new_read_data.substr_of(in_data, max, in_data.length() - max);
in_data = new_read_data;
return 0;
}
int RGWPostObj_ObjStore::read_line(ceph::bufferlist& bl,
const uint64_t max,
bool& reached_boundary,
bool& done)
{
return read_with_boundary(bl, max, true, reached_boundary, done);
}
int RGWPostObj_ObjStore::read_data(ceph::bufferlist& bl,
const uint64_t max,
bool& reached_boundary,
bool& done)
{
return read_with_boundary(bl, max, false, reached_boundary, done);
}
int RGWPostObj_ObjStore::read_form_part_header(struct post_form_part* const part,
bool& done)
{
bufferlist bl;
bool reached_boundary;
uint64_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
int r = read_line(bl, chunk_size, reached_boundary, done);
if (r < 0) {
return r;
}
if (done) {
return 0;
}
if (reached_boundary) { // skip the first boundary
r = read_line(bl, chunk_size, reached_boundary, done);
if (r < 0) {
return r;
} else if (done) {
return 0;
}
}
while (true) {
/*
* iterate through fields
*/
std::string line = rgw_trim_whitespace(string(bl.c_str(), bl.length()));
if (line.empty()) {
break;
}
struct post_part_field field;
string field_name;
r = parse_part_field(line, field_name, field);
if (r < 0) {
return r;
}
part->fields[field_name] = field;
if (stringcasecmp(field_name, "Content-Disposition") == 0) {
part->name = field.params["name"];
}
if (reached_boundary) {
break;
}
r = read_line(bl, chunk_size, reached_boundary, done);
if (r < 0) {
return r;
}
}
return 0;
}
bool RGWPostObj_ObjStore::part_str(parts_collection_t& parts,
const std::string& name,
std::string* val)
{
const auto iter = parts.find(name);
if (std::end(parts) == iter) {
return false;
}
ceph::bufferlist& data = iter->second.data;
std::string str = string(data.c_str(), data.length());
*val = rgw_trim_whitespace(str);
return true;
}
std::string RGWPostObj_ObjStore::get_part_str(parts_collection_t& parts,
const std::string& name,
const std::string& def_val)
{
std::string val;
if (part_str(parts, name, &val)) {
return val;
} else {
return rgw_trim_whitespace(def_val);
}
}
bool RGWPostObj_ObjStore::part_bl(parts_collection_t& parts,
const std::string& name,
ceph::bufferlist* pbl)
{
const auto iter = parts.find(name);
if (std::end(parts) == iter) {
return false;
}
*pbl = iter->second.data;
return true;
}
int RGWPostObj_ObjStore::verify_params()
{
/* check that we have enough memory to store the object
note that this test isn't exact and may fail unintentionally
for large requests is */
if (!s->length) {
return -ERR_LENGTH_REQUIRED;
}
off_t len = atoll(s->length);
if (len > (off_t)(s->cct->_conf->rgw_max_put_size)) {
return -ERR_TOO_LARGE;
}
supplied_md5_b64 = s->info.env->get("HTTP_CONTENT_MD5");
return 0;
}
int RGWPostObj_ObjStore::get_params(optional_yield y)
{
if (s->expect_cont) {
/* OK, here it really gets ugly. With POST, the params are embedded in the
* request body, so we need to continue before being able to actually look
* at them. This diverts from the usual request flow. */
dump_continue(s);
s->expect_cont = false;
}
std::string req_content_type_str = s->info.env->get("CONTENT_TYPE", "");
std::string req_content_type;
std::map<std::string, std::string> params;
parse_boundary_params(req_content_type_str, req_content_type, params);
if (req_content_type.compare("multipart/form-data") != 0) {
err_msg = "Request Content-Type is not multipart/form-data";
return -EINVAL;
}
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
ldpp_dout(s, 20) << "request content_type_str="
<< req_content_type_str << dendl;
ldpp_dout(s, 20) << "request content_type params:" << dendl;
for (const auto& pair : params) {
ldpp_dout(s, 20) << " " << pair.first << " -> " << pair.second
<< dendl;
}
}
const auto iter = params.find("boundary");
if (std::end(params) == iter) {
err_msg = "Missing multipart boundary specification";
return -EINVAL;
}
/* Create the boundary. */
boundary = "--";
boundary.append(iter->second);
return 0;
}
int RGWPutACLs_ObjStore::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
ldpp_dout(s, 0) << "RGWPutACLs_ObjStore::get_params read data is: " << data.c_str() << dendl;
return op_ret;
}
int RGWPutLC_ObjStore::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
return op_ret;
}
int RGWPutBucketObjectLock_ObjStore::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
return op_ret;
}
int RGWPutObjLegalHold_ObjStore::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
return op_ret;
}
static std::tuple<int, bufferlist> read_all_chunked_input(req_state *s, const uint64_t max_read)
{
#define READ_CHUNK 4096
#define MAX_READ_CHUNK (128 * 1024)
int need_to_read = READ_CHUNK;
int total = need_to_read;
bufferlist bl;
int read_len = 0;
do {
bufferptr bp(need_to_read + 1);
read_len = recv_body(s, bp.c_str(), need_to_read);
if (read_len < 0) {
return std::make_tuple(read_len, std::move(bl));
}
bp.c_str()[read_len] = '\0';
bp.set_length(read_len);
bl.append(bp);
if (read_len == need_to_read) {
if (need_to_read < MAX_READ_CHUNK)
need_to_read *= 2;
if ((unsigned)total > max_read) {
return std::make_tuple(-ERANGE, std::move(bl));
}
total += need_to_read;
} else {
break;
}
} while (true);
return std::make_tuple(0, std::move(bl));
}
std::tuple<int, bufferlist > rgw_rest_read_all_input(req_state *s,
const uint64_t max_len,
const bool allow_chunked)
{
size_t cl = 0;
int len = 0;
bufferlist bl;
if (s->length)
cl = atoll(s->length);
else if (!allow_chunked)
return std::make_tuple(-ERR_LENGTH_REQUIRED, std::move(bl));
if (cl) {
if (cl > (size_t)max_len) {
return std::make_tuple(-ERANGE, std::move(bl));
}
bufferptr bp(cl + 1);
len = recv_body(s, bp.c_str(), cl);
if (len < 0) {
return std::make_tuple(len, std::move(bl));
}
bp.c_str()[len] = '\0';
bp.set_length(len);
bl.append(bp);
} else if (allow_chunked && !s->length) {
const char *encoding = s->info.env->get("HTTP_TRANSFER_ENCODING");
if (!encoding || strcmp(encoding, "chunked") != 0)
return std::make_tuple(-ERR_LENGTH_REQUIRED, std::move(bl));
int ret = 0;
std::tie(ret, bl) = read_all_chunked_input(s, max_len);
if (ret < 0)
return std::make_tuple(ret, std::move(bl));
}
return std::make_tuple(0, std::move(bl));
}
int RGWCompleteMultipart_ObjStore::get_params(optional_yield y)
{
upload_id = s->info.args.get("uploadId");
if (upload_id.empty()) {
op_ret = -ENOTSUP;
return op_ret;
}
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size);
if (op_ret < 0)
return op_ret;
return 0;
}
int RGWListMultipart_ObjStore::get_params(optional_yield y)
{
upload_id = s->info.args.get("uploadId");
if (upload_id.empty()) {
op_ret = -ENOTSUP;
}
string marker_str = s->info.args.get("part-number-marker");
if (!marker_str.empty()) {
string err;
marker = strict_strtol(marker_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(s, 20) << "bad marker: " << marker << dendl;
op_ret = -EINVAL;
return op_ret;
}
}
string str = s->info.args.get("max-parts");
op_ret = parse_value_and_bound(str, max_parts, 0,
g_conf().get_val<uint64_t>("rgw_max_listing_results"),
max_parts);
return op_ret;
}
int RGWListBucketMultiparts_ObjStore::get_params(optional_yield y)
{
delimiter = s->info.args.get("delimiter");
prefix = s->info.args.get("prefix");
string str = s->info.args.get("max-uploads");
op_ret = parse_value_and_bound(str, max_uploads, 0,
g_conf().get_val<uint64_t>("rgw_max_listing_results"),
default_max);
if (op_ret < 0) {
return op_ret;
}
if (auto encoding_type = s->info.args.get_optional("encoding-type");
encoding_type != boost::none) {
if (strcasecmp(encoding_type->c_str(), "url") != 0) {
op_ret = -EINVAL;
s->err.message="Invalid Encoding Method specified in Request";
return op_ret;
}
encode_url = true;
}
string key_marker = s->info.args.get("key-marker");
string upload_id_marker = s->info.args.get("upload-id-marker");
if (!key_marker.empty()) {
std::unique_ptr<rgw::sal::MultipartUpload> upload;
upload = s->bucket->get_multipart_upload(key_marker,
upload_id_marker);
marker_meta = upload->get_meta();
marker_key = upload->get_key();
marker_upload_id = upload->get_upload_id();
}
return 0;
}
int RGWDeleteMultiObj_ObjStore::get_params(optional_yield y)
{
if (s->bucket_name.empty()) {
op_ret = -EINVAL;
return op_ret;
}
// everything is probably fine, set the bucket
bucket = s->bucket.get();
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
return op_ret;
}
void RGWRESTOp::send_response()
{
if (!flusher.did_start()) {
set_req_state_err(s, get_ret());
dump_errno(s);
end_header(s, this);
}
flusher.flush();
}
int RGWRESTOp::verify_permission(optional_yield)
{
return check_caps(s->user->get_info().caps);
}
RGWOp* RGWHandler_REST::get_op(void)
{
RGWOp *op;
switch (s->op) {
case OP_GET:
op = op_get();
break;
case OP_PUT:
op = op_put();
break;
case OP_DELETE:
op = op_delete();
break;
case OP_HEAD:
op = op_head();
break;
case OP_POST:
op = op_post();
break;
case OP_COPY:
op = op_copy();
break;
case OP_OPTIONS:
op = op_options();
break;
default:
return NULL;
}
if (op) {
op->init(driver, s, this);
}
return op;
} /* get_op */
void RGWHandler_REST::put_op(RGWOp* op)
{
delete op;
} /* put_op */
int RGWHandler_REST::allocate_formatter(req_state *s,
RGWFormat default_type,
bool configurable)
{
s->format = RGWFormat::BAD_FORMAT; // set to invalid value to allocation happens anyway
auto type = default_type;
if (configurable) {
string format_str = s->info.args.get("format");
if (format_str.compare("xml") == 0) {
type = RGWFormat::XML;
} else if (format_str.compare("json") == 0) {
type = RGWFormat::JSON;
} else if (format_str.compare("html") == 0) {
type = RGWFormat::HTML;
} else {
const char *accept = s->info.env->get("HTTP_ACCEPT");
if (accept) {
// trim at first ;
std::string_view format = accept;
format = format.substr(0, format.find(';'));
if (format == "text/xml" || format == "application/xml") {
type = RGWFormat::XML;
} else if (format == "application/json") {
type = RGWFormat::JSON;
} else if (format == "text/html") {
type = RGWFormat::HTML;
}
}
}
}
return RGWHandler_REST::reallocate_formatter(s, type);
}
int RGWHandler_REST::reallocate_formatter(req_state *s, const RGWFormat type)
{
if (s->format == type) {
// do nothing, just reset
ceph_assert(s->formatter);
s->formatter->reset();
return 0;
}
delete s->formatter;
s->formatter = nullptr;
s->format = type;
const string& mm = s->info.args.get("multipart-manifest");
const bool multipart_delete = (mm.compare("delete") == 0);
const bool swift_bulkupload = s->prot_flags & RGW_REST_SWIFT &&
s->info.args.exists("extract-archive");
switch (s->format) {
case RGWFormat::PLAIN:
{
const bool use_kv_syntax = s->info.args.exists("bulk-delete") ||
multipart_delete || swift_bulkupload;
s->formatter = new RGWFormatter_Plain(use_kv_syntax);
break;
}
case RGWFormat::XML:
{
const bool lowercase_underscore = s->info.args.exists("bulk-delete") ||
multipart_delete || swift_bulkupload;
s->formatter = new XMLFormatter(false, lowercase_underscore);
break;
}
case RGWFormat::JSON:
s->formatter = new JSONFormatter(false);
break;
case RGWFormat::HTML:
s->formatter = new HTMLFormatter(s->prot_flags & RGW_REST_WEBSITE);
break;
default:
return -EINVAL;
};
//s->formatter->reset(); // All formatters should reset on create already
return 0;
}
// This function enforces Amazon's spec for bucket names.
// (The requirements, not the recommendations.)
int RGWHandler_REST::validate_bucket_name(const string& bucket)
{
int len = bucket.size();
if (len < 3) {
if (len == 0) {
// This request doesn't specify a bucket at all
return 0;
}
// Name too short
return -ERR_INVALID_BUCKET_NAME;
}
else if (len > MAX_BUCKET_NAME_LEN) {
// Name too long
return -ERR_INVALID_BUCKET_NAME;
}
const char *s = bucket.c_str();
for (int i = 0; i < len; ++i, ++s) {
if (*(unsigned char *)s == 0xff)
return -ERR_INVALID_BUCKET_NAME;
if (*(unsigned char *)s == '/')
return -ERR_INVALID_BUCKET_NAME;
}
return 0;
}
// "The name for a key is a sequence of Unicode characters whose UTF-8 encoding
// is at most 1024 bytes long."
// However, we can still have control characters and other nasties in there.
// Just as long as they're utf-8 nasties.
int RGWHandler_REST::validate_object_name(const string& object)
{
int len = object.size();
if (len > MAX_OBJ_NAME_LEN) {
// Name too long
return -ERR_INVALID_OBJECT_NAME;
}
if (check_utf8(object.c_str(), len)) {
// Object names must be valid UTF-8.
return -ERR_INVALID_OBJECT_NAME;
}
return 0;
}
static http_op op_from_method(const char *method)
{
if (!method)
return OP_UNKNOWN;
if (strcmp(method, "GET") == 0)
return OP_GET;
if (strcmp(method, "PUT") == 0)
return OP_PUT;
if (strcmp(method, "DELETE") == 0)
return OP_DELETE;
if (strcmp(method, "HEAD") == 0)
return OP_HEAD;
if (strcmp(method, "POST") == 0)
return OP_POST;
if (strcmp(method, "COPY") == 0)
return OP_COPY;
if (strcmp(method, "OPTIONS") == 0)
return OP_OPTIONS;
return OP_UNKNOWN;
}
int RGWHandler_REST::init_permissions(RGWOp* op, optional_yield y)
{
if (op->get_type() == RGW_OP_CREATE_BUCKET) {
// We don't need user policies in case of STS token returned by AssumeRole, hence the check for user type
if (! s->user->get_id().empty() && s->auth.identity->get_identity_type() != TYPE_ROLE) {
try {
if (auto ret = s->user->read_attrs(s, y); ! ret) {
auto user_policies = get_iam_user_policy_from_attr(s->cct, s->user->get_attrs(), s->user->get_tenant());
s->iam_user_policies.insert(s->iam_user_policies.end(),
std::make_move_iterator(user_policies.begin()),
std::make_move_iterator(user_policies.end()));
}
} catch (const std::exception& e) {
ldpp_dout(op, -1) << "Error reading IAM User Policy: " << e.what() << dendl;
}
}
rgw_build_iam_environment(driver, s);
return 0;
}
return do_init_permissions(op, y);
}
int RGWHandler_REST::read_permissions(RGWOp* op_obj, optional_yield y)
{
bool only_bucket = false;
switch (s->op) {
case OP_HEAD:
case OP_GET:
only_bucket = false;
break;
case OP_PUT:
case OP_POST:
case OP_COPY:
/* is it a 'multi-object delete' request? */
if (s->info.args.exists("delete")) {
only_bucket = true;
break;
}
if (is_obj_update_op()) {
only_bucket = false;
break;
}
/* is it a 'create bucket' request? */
if (op_obj->get_type() == RGW_OP_CREATE_BUCKET)
return 0;
only_bucket = true;
break;
case OP_DELETE:
if (!s->info.args.exists("tagging")){
only_bucket = true;
}
break;
case OP_OPTIONS:
only_bucket = true;
break;
default:
return -EINVAL;
}
return do_read_permissions(op_obj, only_bucket, y);
}
void RGWRESTMgr::register_resource(string resource, RGWRESTMgr *mgr)
{
string r = "/";
r.append(resource);
/* do we have a resource manager registered for this entry point? */
map<string, RGWRESTMgr *>::iterator iter = resource_mgrs.find(r);
if (iter != resource_mgrs.end()) {
delete iter->second;
}
resource_mgrs[r] = mgr;
resources_by_size.insert(pair<size_t, string>(r.size(), r));
/* now build default resource managers for the path (instead of nested entry points)
* e.g., if the entry point is /auth/v1.0/ then we'd want to create a default
* manager for /auth/
*/
size_t pos = r.find('/', 1);
while (pos != r.size() - 1 && pos != string::npos) {
string s = r.substr(0, pos);
iter = resource_mgrs.find(s);
if (iter == resource_mgrs.end()) { /* only register it if one does not exist */
resource_mgrs[s] = new RGWRESTMgr; /* a default do-nothing manager */
resources_by_size.insert(pair<size_t, string>(s.size(), s));
}
pos = r.find('/', pos + 1);
}
}
void RGWRESTMgr::register_default_mgr(RGWRESTMgr *mgr)
{
delete default_mgr;
default_mgr = mgr;
}
RGWRESTMgr* RGWRESTMgr::get_resource_mgr(req_state* const s,
const std::string& uri,
std::string* const out_uri)
{
*out_uri = uri;
multimap<size_t, string>::reverse_iterator iter;
for (iter = resources_by_size.rbegin(); iter != resources_by_size.rend(); ++iter) {
string& resource = iter->second;
if (uri.compare(0, iter->first, resource) == 0 &&
(uri.size() == iter->first ||
uri[iter->first] == '/')) {
std::string suffix = uri.substr(iter->first);
return resource_mgrs[resource]->get_resource_mgr(s, suffix, out_uri);
}
}
if (default_mgr) {
return default_mgr->get_resource_mgr_as_default(s, uri, out_uri);
}
return this;
}
void RGWREST::register_x_headers(const string& s_headers)
{
std::vector<std::string> hdrs = get_str_vec(s_headers);
for (auto& hdr : hdrs) {
boost::algorithm::to_upper(hdr); // XXX
(void) x_headers.insert(hdr);
}
}
RGWRESTMgr::~RGWRESTMgr()
{
map<string, RGWRESTMgr *>::iterator iter;
for (iter = resource_mgrs.begin(); iter != resource_mgrs.end(); ++iter) {
delete iter->second;
}
delete default_mgr;
}
int64_t parse_content_length(const char *content_length)
{
int64_t len = -1;
if (*content_length == '\0') {
len = 0;
} else {
string err;
len = strict_strtoll(content_length, 10, &err);
if (!err.empty()) {
len = -1;
}
}
return len;
}
int RGWREST::preprocess(req_state *s, rgw::io::BasicClient* cio)
{
req_info& info = s->info;
/* save the request uri used to hash on the client side. request_uri may suffer
modifications as part of the bucket encoding in the subdomain calling format.
request_uri_aws4 will be used under aws4 auth */
s->info.request_uri_aws4 = s->info.request_uri;
s->cio = cio;
// We need to know if this RGW instance is running the s3website API with a
// higher priority than regular S3 API, or possibly in place of the regular
// S3 API.
// Map the listing of rgw_enable_apis in REVERSE order, so that items near
// the front of the list have a higher number assigned (and -1 for items not in the list).
list<string> apis;
get_str_list(g_conf()->rgw_enable_apis, apis);
int api_priority_s3 = -1;
int api_priority_s3website = -1;
auto api_s3website_priority_rawpos = std::find(apis.begin(), apis.end(), "s3website");
auto api_s3_priority_rawpos = std::find(apis.begin(), apis.end(), "s3");
if (api_s3_priority_rawpos != apis.end()) {
api_priority_s3 = apis.size() - std::distance(apis.begin(), api_s3_priority_rawpos);
}
if (api_s3website_priority_rawpos != apis.end()) {
api_priority_s3website = apis.size() - std::distance(apis.begin(), api_s3website_priority_rawpos);
}
ldpp_dout(s, 10) << "rgw api priority: s3=" << api_priority_s3 << " s3website=" << api_priority_s3website << dendl;
bool s3website_enabled = api_priority_s3website >= 0;
if (info.host.size()) {
ssize_t pos;
if (info.host.find('[') == 0) {
pos = info.host.find(']');
if (pos >=1) {
info.host = info.host.substr(1, pos-1);
}
} else {
pos = info.host.find(':');
if (pos >= 0) {
info.host = info.host.substr(0, pos);
}
}
ldpp_dout(s, 10) << "host=" << info.host << dendl;
string domain;
string subdomain;
bool in_hosted_domain_s3website = false;
bool in_hosted_domain = rgw_find_host_in_domains(info.host, &domain, &subdomain, hostnames_set);
string s3website_domain;
string s3website_subdomain;
if (s3website_enabled) {
in_hosted_domain_s3website = rgw_find_host_in_domains(info.host, &s3website_domain, &s3website_subdomain, hostnames_s3website_set);
if (in_hosted_domain_s3website) {
in_hosted_domain = true; // TODO: should hostnames be a strict superset of hostnames_s3website?
domain = s3website_domain;
subdomain = s3website_subdomain;
}
}
ldpp_dout(s, 20)
<< "subdomain=" << subdomain
<< " domain=" << domain
<< " in_hosted_domain=" << in_hosted_domain
<< " in_hosted_domain_s3website=" << in_hosted_domain_s3website
<< dendl;
if (g_conf()->rgw_resolve_cname
&& !in_hosted_domain
&& !in_hosted_domain_s3website) {
string cname;
bool found;
int r = rgw_resolver->resolve_cname(info.host, cname, &found);
if (r < 0) {
ldpp_dout(s, 0)
<< "WARNING: rgw_resolver->resolve_cname() returned r=" << r
<< dendl;
}
if (found) {
ldpp_dout(s, 5) << "resolved host cname " << info.host << " -> "
<< cname << dendl;
in_hosted_domain =
rgw_find_host_in_domains(cname, &domain, &subdomain, hostnames_set);
if (s3website_enabled
&& !in_hosted_domain_s3website) {
in_hosted_domain_s3website =
rgw_find_host_in_domains(cname, &s3website_domain,
&s3website_subdomain,
hostnames_s3website_set);
if (in_hosted_domain_s3website) {
in_hosted_domain = true; // TODO: should hostnames be a
// strict superset of hostnames_s3website?
domain = s3website_domain;
subdomain = s3website_subdomain;
}
}
ldpp_dout(s, 20)
<< "subdomain=" << subdomain
<< " domain=" << domain
<< " in_hosted_domain=" << in_hosted_domain
<< " in_hosted_domain_s3website=" << in_hosted_domain_s3website
<< dendl;
}
}
// Handle A/CNAME records that point to the RGW storage, but do match the
// CNAME test above, per issue http://tracker.ceph.com/issues/15975
// If BOTH domain & subdomain variables are empty, then none of the above
// cases matched anything, and we should fall back to using the Host header
// directly as the bucket name.
// As additional checks:
// - if the Host header is an IP, we're using path-style access without DNS
// - Also check that the Host header is a valid bucket name before using it.
// - Don't enable virtual hosting if no hostnames are configured
if (subdomain.empty()
&& (domain.empty() || domain != info.host)
&& !looks_like_ip_address(info.host.c_str())
&& RGWHandler_REST::validate_bucket_name(info.host) == 0
&& !(hostnames_set.empty() && hostnames_s3website_set.empty())) {
subdomain.append(info.host);
in_hosted_domain = 1;
}
if (s3website_enabled && api_priority_s3website > api_priority_s3) {
in_hosted_domain_s3website = 1;
}
if (in_hosted_domain_s3website) {
s->prot_flags |= RGW_REST_WEBSITE;
}
if (in_hosted_domain && !subdomain.empty()) {
string encoded_bucket = "/";
encoded_bucket.append(subdomain);
if (s->info.request_uri[0] != '/')
encoded_bucket.append("/");
encoded_bucket.append(s->info.request_uri);
s->info.request_uri = encoded_bucket;
}
if (!domain.empty()) {
s->info.domain = domain;
}
ldpp_dout(s, 20)
<< "final domain/bucket"
<< " subdomain=" << subdomain
<< " domain=" << domain
<< " in_hosted_domain=" << in_hosted_domain
<< " in_hosted_domain_s3website=" << in_hosted_domain_s3website
<< " s->info.domain=" << s->info.domain
<< " s->info.request_uri=" << s->info.request_uri
<< dendl;
}
if (s->info.domain.empty()) {
s->info.domain = s->cct->_conf->rgw_dns_name;
}
s->decoded_uri = url_decode(s->info.request_uri);
/* Validate for being free of the '\0' buried in the middle of the string. */
if (std::strlen(s->decoded_uri.c_str()) != s->decoded_uri.length()) {
return -ERR_ZERO_IN_URL;
}
/* FastCGI specification, section 6.3
* http://www.fastcgi.com/devkit/doc/fcgi-spec.html#S6.3
* ===
* The Authorizer application receives HTTP request information from the Web
* server on the FCGI_PARAMS stream, in the same format as a Responder. The
* Web server does not send CONTENT_LENGTH, PATH_INFO, PATH_TRANSLATED, and
* SCRIPT_NAME headers.
* ===
* Ergo if we are in Authorizer role, we MUST look at HTTP_CONTENT_LENGTH
* instead of CONTENT_LENGTH for the Content-Length.
*
* There is one slight wrinkle in this, and that's older versions of
* nginx/lighttpd/apache setting BOTH headers. As a result, we have to check
* both headers and can't always simply pick A or B.
*/
const char* content_length = info.env->get("CONTENT_LENGTH");
const char* http_content_length = info.env->get("HTTP_CONTENT_LENGTH");
if (!http_content_length != !content_length) {
/* Easy case: one or the other is missing */
s->length = (content_length ? content_length : http_content_length);
} else if (s->cct->_conf->rgw_content_length_compat &&
content_length && http_content_length) {
/* Hard case: Both are set, we have to disambiguate */
int64_t content_length_i, http_content_length_i;
content_length_i = parse_content_length(content_length);
http_content_length_i = parse_content_length(http_content_length);
// Now check them:
if (http_content_length_i < 0) {
// HTTP_CONTENT_LENGTH is invalid, ignore it
} else if (content_length_i < 0) {
// CONTENT_LENGTH is invalid, and HTTP_CONTENT_LENGTH is valid
// Swap entries
content_length = http_content_length;
} else {
// both CONTENT_LENGTH and HTTP_CONTENT_LENGTH are valid
// Let's pick the larger size
if (content_length_i < http_content_length_i) {
// prefer the larger value
content_length = http_content_length;
}
}
s->length = content_length;
// End of: else if (s->cct->_conf->rgw_content_length_compat &&
// content_length &&
// http_content_length)
} else {
/* no content length was defined */
s->length = NULL;
}
if (s->length) {
if (*s->length == '\0') {
s->content_length = 0;
} else {
string err;
s->content_length = strict_strtoll(s->length, 10, &err);
if (!err.empty()) {
ldpp_dout(s, 10) << "bad content length, aborting" << dendl;
return -EINVAL;
}
}
}
if (s->content_length < 0) {
ldpp_dout(s, 10) << "negative content length, aborting" << dendl;
return -EINVAL;
}
map<string, string>::iterator giter;
for (giter = generic_attrs_map.begin(); giter != generic_attrs_map.end();
++giter) {
const char *env = info.env->get(giter->first.c_str());
if (env) {
s->generic_attrs[giter->second] = env;
}
}
if (g_conf()->rgw_print_continue) {
const char *expect = info.env->get("HTTP_EXPECT");
s->expect_cont = (expect && !strcasecmp(expect, "100-continue"));
}
s->op = op_from_method(info.method);
info.init_meta_info(s, &s->has_bad_meta);
return 0;
}
RGWHandler_REST* RGWREST::get_handler(
rgw::sal::Driver* const driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix,
RGWRestfulIO* const rio,
RGWRESTMgr** const pmgr,
int* const init_error
) {
*init_error = preprocess(s, rio);
if (*init_error < 0) {
return nullptr;
}
RGWRESTMgr *m = mgr.get_manager(s, frontend_prefix, s->decoded_uri,
&s->relative_uri);
if (! m) {
*init_error = -ERR_METHOD_NOT_ALLOWED;
return nullptr;
}
if (pmgr) {
*pmgr = m;
}
RGWHandler_REST* handler = m->get_handler(driver, s, auth_registry, frontend_prefix);
if (! handler) {
*init_error = -ERR_METHOD_NOT_ALLOWED;
return NULL;
}
ldpp_dout(s, 20) << __func__ << " handler=" << typeid(*handler).name() << dendl;
*init_error = handler->init(driver, s, rio);
if (*init_error < 0) {
m->put_handler(handler);
return nullptr;
}
return handler;
} /* get stream handler */
| 62,640 | 25.873016 | 137 |
cc
|
null |
ceph-main/src/rgw/rgw_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
#define TIME_BUF_SIZE 128
#include <string_view>
#include <boost/container/flat_set.hpp>
#include "common/sstring.hh"
#include "common/ceph_json.h"
#include "include/ceph_assert.h" /* needed because of common/ceph_json.h */
#include "rgw_op.h"
#include "rgw_formats.h"
#include "rgw_client_io.h"
#include "rgw_lua_background.h"
extern std::map<std::string, std::string> rgw_to_http_attrs;
extern void rgw_rest_init(CephContext *cct, const rgw::sal::ZoneGroup& zone_group);
extern void rgw_flush_formatter_and_reset(req_state *s,
ceph::Formatter *formatter);
extern void rgw_flush_formatter(req_state *s,
ceph::Formatter *formatter);
inline std::string_view rgw_sanitized_hdrval(ceph::buffer::list& raw)
{
/* std::string and thus std::string_view ARE OBLIGED to carry multiple
* 0x00 and count them to the length of a string. We need to take that
* into consideration and sanitize the size of a ceph::buffer::list used
* to store metadata values (x-amz-meta-*, X-Container-Meta-*, etags).
* Otherwise we might send 0x00 to clients. */
const char* const data = raw.c_str();
size_t len = raw.length();
if (len && data[len - 1] == '\0') {
/* That's the case - the null byte has been included at the last position
* of the bufferlist. We need to restore the proper string length we'll
* pass to string_ref. */
len--;
}
return std::string_view(data, len);
}
template <class T>
std::tuple<int, bufferlist > rgw_rest_get_json_input_keep_data(CephContext *cct, req_state *s, T& out, uint64_t max_len)
{
int rv = 0;
bufferlist data;
std::tie(rv, data) = rgw_rest_read_all_input(s, max_len);
if (rv < 0) {
return std::make_tuple(rv, std::move(data));
}
if (!data.length()) {
return std::make_tuple(-EINVAL, std::move(data));
}
JSONParser parser;
if (!parser.parse(data.c_str(), data.length())) {
return std::make_tuple(-EINVAL, std::move(data));
}
try {
decode_json_obj(out, &parser);
} catch (JSONDecoder::err& e) {
return std::make_tuple(-EINVAL, std::move(data));
}
return std::make_tuple(0, std::move(data));
}
class RESTArgs {
public:
static int get_string(req_state *s, const std::string& name,
const std::string& def_val, std::string *val,
bool *existed = NULL);
static int get_uint64(req_state *s, const std::string& name,
uint64_t def_val, uint64_t *val, bool *existed = NULL);
static int get_int64(req_state *s, const std::string& name,
int64_t def_val, int64_t *val, bool *existed = NULL);
static int get_uint32(req_state *s, const std::string& name,
uint32_t def_val, uint32_t *val, bool *existed = NULL);
static int get_int32(req_state *s, const std::string& name,
int32_t def_val, int32_t *val, bool *existed = NULL);
static int get_time(req_state *s, const std::string& name,
const utime_t& def_val, utime_t *val,
bool *existed = NULL);
static int get_epoch(req_state *s, const std::string& name,
uint64_t def_val, uint64_t *epoch,
bool *existed = NULL);
static int get_bool(req_state *s, const std::string& name, bool def_val,
bool *val, bool *existed = NULL);
};
class RGWRESTFlusher : public RGWFormatterFlusher {
req_state *s;
RGWOp *op;
protected:
void do_flush() override;
void do_start(int ret) override;
public:
RGWRESTFlusher(req_state *_s, RGWOp *_op) :
RGWFormatterFlusher(_s->formatter), s(_s), op(_op) {}
RGWRESTFlusher() : RGWFormatterFlusher(NULL), s(NULL), op(NULL) {}
void init(req_state *_s, RGWOp *_op) {
s = _s;
op = _op;
set_formatter(s->formatter);
}
};
class RGWGetObj_ObjStore : public RGWGetObj
{
protected:
bool sent_header;
public:
RGWGetObj_ObjStore() : sent_header(false) {}
void init(rgw::sal::Driver* driver, req_state *s, RGWHandler *h) override {
RGWGetObj::init(driver, s, h);
sent_header = false;
}
int get_params(optional_yield y) override;
};
class RGWGetObjTags_ObjStore : public RGWGetObjTags {
public:
RGWGetObjTags_ObjStore() {};
~RGWGetObjTags_ObjStore() {};
};
class RGWPutObjTags_ObjStore: public RGWPutObjTags {
public:
RGWPutObjTags_ObjStore() {};
~RGWPutObjTags_ObjStore() {};
};
class RGWGetBucketTags_ObjStore : public RGWGetBucketTags {
public:
RGWGetBucketTags_ObjStore() = default;
virtual ~RGWGetBucketTags_ObjStore() = default;
};
class RGWPutBucketTags_ObjStore: public RGWPutBucketTags {
public:
RGWPutBucketTags_ObjStore() = default;
virtual ~RGWPutBucketTags_ObjStore() = default;
};
class RGWGetBucketReplication_ObjStore : public RGWGetBucketReplication {
public:
RGWGetBucketReplication_ObjStore() {};
~RGWGetBucketReplication_ObjStore() {};
};
class RGWPutBucketReplication_ObjStore: public RGWPutBucketReplication {
public:
RGWPutBucketReplication_ObjStore() = default;
virtual ~RGWPutBucketReplication_ObjStore() = default;
};
class RGWDeleteBucketReplication_ObjStore: public RGWDeleteBucketReplication {
public:
RGWDeleteBucketReplication_ObjStore() = default;
virtual ~RGWDeleteBucketReplication_ObjStore() = default;
};
class RGWListBuckets_ObjStore : public RGWListBuckets {
public:
RGWListBuckets_ObjStore() {}
~RGWListBuckets_ObjStore() override {}
};
class RGWGetUsage_ObjStore : public RGWGetUsage {
public:
RGWGetUsage_ObjStore() {}
~RGWGetUsage_ObjStore() override {}
};
class RGWListBucket_ObjStore : public RGWListBucket {
public:
RGWListBucket_ObjStore() {}
~RGWListBucket_ObjStore() override {}
};
class RGWStatAccount_ObjStore : public RGWStatAccount {
public:
RGWStatAccount_ObjStore() {}
~RGWStatAccount_ObjStore() override {}
};
class RGWStatBucket_ObjStore : public RGWStatBucket {
public:
RGWStatBucket_ObjStore() {}
~RGWStatBucket_ObjStore() override {}
};
class RGWCreateBucket_ObjStore : public RGWCreateBucket {
public:
RGWCreateBucket_ObjStore() {}
~RGWCreateBucket_ObjStore() override {}
};
class RGWDeleteBucket_ObjStore : public RGWDeleteBucket {
public:
RGWDeleteBucket_ObjStore() {}
~RGWDeleteBucket_ObjStore() override {}
};
class RGWPutObj_ObjStore : public RGWPutObj
{
public:
RGWPutObj_ObjStore() {}
~RGWPutObj_ObjStore() override {}
int verify_params() override;
int get_params(optional_yield y) override;
int get_data(bufferlist& bl) override;
};
class RGWPostObj_ObjStore : public RGWPostObj
{
std::string boundary;
public:
struct post_part_field {
std::string val;
std::map<std::string, std::string> params;
};
struct post_form_part {
std::string name;
std::map<std::string, post_part_field, ltstr_nocase> fields;
ceph::bufferlist data;
};
protected:
using parts_collection_t = \
std::map<std::string, post_form_part, const ltstr_nocase>;
std::string err_msg;
ceph::bufferlist in_data;
int read_with_boundary(ceph::bufferlist& bl,
uint64_t max,
bool check_eol,
bool& reached_boundary,
bool& done);
int read_line(ceph::bufferlist& bl,
uint64_t max,
bool& reached_boundary,
bool& done);
int read_data(ceph::bufferlist& bl,
uint64_t max,
bool& reached_boundary,
bool& done);
int read_form_part_header(struct post_form_part *part, bool& done);
int get_params(optional_yield y) override;
static int parse_part_field(const std::string& line,
std::string& field_name, /* out */
post_part_field& field); /* out */
static void parse_boundary_params(const std::string& params_str,
std::string& first,
std::map<std::string, std::string>& params);
static bool part_str(parts_collection_t& parts,
const std::string& name,
std::string *val);
static std::string get_part_str(parts_collection_t& parts,
const std::string& name,
const std::string& def_val = std::string());
static bool part_bl(parts_collection_t& parts,
const std::string& name,
ceph::bufferlist *pbl);
public:
RGWPostObj_ObjStore() {}
~RGWPostObj_ObjStore() override {}
int verify_params() override;
};
class RGWPutMetadataAccount_ObjStore : public RGWPutMetadataAccount
{
public:
RGWPutMetadataAccount_ObjStore() {}
~RGWPutMetadataAccount_ObjStore() override {}
};
class RGWPutMetadataBucket_ObjStore : public RGWPutMetadataBucket
{
public:
RGWPutMetadataBucket_ObjStore() {}
~RGWPutMetadataBucket_ObjStore() override {}
};
class RGWPutMetadataObject_ObjStore : public RGWPutMetadataObject
{
public:
RGWPutMetadataObject_ObjStore() {}
~RGWPutMetadataObject_ObjStore() override {}
};
class RGWDeleteObj_ObjStore : public RGWDeleteObj {
public:
RGWDeleteObj_ObjStore() {}
~RGWDeleteObj_ObjStore() override {}
};
class RGWGetCrossDomainPolicy_ObjStore : public RGWGetCrossDomainPolicy {
public:
RGWGetCrossDomainPolicy_ObjStore() = default;
~RGWGetCrossDomainPolicy_ObjStore() override = default;
};
class RGWGetHealthCheck_ObjStore : public RGWGetHealthCheck {
public:
RGWGetHealthCheck_ObjStore() = default;
~RGWGetHealthCheck_ObjStore() override = default;
};
class RGWCopyObj_ObjStore : public RGWCopyObj {
public:
RGWCopyObj_ObjStore() {}
~RGWCopyObj_ObjStore() override {}
};
class RGWGetACLs_ObjStore : public RGWGetACLs {
public:
RGWGetACLs_ObjStore() {}
~RGWGetACLs_ObjStore() override {}
};
class RGWPutACLs_ObjStore : public RGWPutACLs {
public:
RGWPutACLs_ObjStore() {}
~RGWPutACLs_ObjStore() override {}
int get_params(optional_yield y) override;
};
class RGWGetLC_ObjStore : public RGWGetLC {
public:
RGWGetLC_ObjStore() {}
~RGWGetLC_ObjStore() override {}
};
class RGWPutLC_ObjStore : public RGWPutLC {
public:
RGWPutLC_ObjStore() {}
~RGWPutLC_ObjStore() override {}
int get_params(optional_yield y) override;
};
class RGWDeleteLC_ObjStore : public RGWDeleteLC {
public:
RGWDeleteLC_ObjStore() {}
~RGWDeleteLC_ObjStore() override {}
};
class RGWGetCORS_ObjStore : public RGWGetCORS {
public:
RGWGetCORS_ObjStore() {}
~RGWGetCORS_ObjStore() override {}
};
class RGWPutCORS_ObjStore : public RGWPutCORS {
public:
RGWPutCORS_ObjStore() {}
~RGWPutCORS_ObjStore() override {}
};
class RGWDeleteCORS_ObjStore : public RGWDeleteCORS {
public:
RGWDeleteCORS_ObjStore() {}
~RGWDeleteCORS_ObjStore() override {}
};
class RGWOptionsCORS_ObjStore : public RGWOptionsCORS {
public:
RGWOptionsCORS_ObjStore() {}
~RGWOptionsCORS_ObjStore() override {}
};
class RGWGetBucketEncryption_ObjStore : public RGWGetBucketEncryption {
public:
RGWGetBucketEncryption_ObjStore() {}
~RGWGetBucketEncryption_ObjStore() override {}
};
class RGWPutBucketEncryption_ObjStore : public RGWPutBucketEncryption {
public:
RGWPutBucketEncryption_ObjStore() {}
~RGWPutBucketEncryption_ObjStore() override {}
};
class RGWDeleteBucketEncryption_ObjStore : public RGWDeleteBucketEncryption {
public:
RGWDeleteBucketEncryption_ObjStore() {}
~RGWDeleteBucketEncryption_ObjStore() override {}
};
class RGWInitMultipart_ObjStore : public RGWInitMultipart {
public:
RGWInitMultipart_ObjStore() {}
~RGWInitMultipart_ObjStore() override {}
};
class RGWCompleteMultipart_ObjStore : public RGWCompleteMultipart {
public:
RGWCompleteMultipart_ObjStore() {}
~RGWCompleteMultipart_ObjStore() override {}
int get_params(optional_yield y) override;
};
class RGWAbortMultipart_ObjStore : public RGWAbortMultipart {
public:
RGWAbortMultipart_ObjStore() {}
~RGWAbortMultipart_ObjStore() override {}
};
class RGWListMultipart_ObjStore : public RGWListMultipart {
public:
RGWListMultipart_ObjStore() {}
~RGWListMultipart_ObjStore() override {}
int get_params(optional_yield y) override;
};
class RGWListBucketMultiparts_ObjStore : public RGWListBucketMultiparts {
public:
RGWListBucketMultiparts_ObjStore() {}
~RGWListBucketMultiparts_ObjStore() override {}
int get_params(optional_yield y) override;
};
class RGWBulkDelete_ObjStore : public RGWBulkDelete {
public:
RGWBulkDelete_ObjStore() {}
~RGWBulkDelete_ObjStore() override {}
};
class RGWBulkUploadOp_ObjStore : public RGWBulkUploadOp {
public:
RGWBulkUploadOp_ObjStore() = default;
~RGWBulkUploadOp_ObjStore() = default;
};
class RGWDeleteMultiObj_ObjStore : public RGWDeleteMultiObj {
public:
RGWDeleteMultiObj_ObjStore() {}
~RGWDeleteMultiObj_ObjStore() override {}
int get_params(optional_yield y) override;
};
class RGWInfo_ObjStore : public RGWInfo {
public:
RGWInfo_ObjStore() = default;
~RGWInfo_ObjStore() override = default;
};
class RGWPutBucketObjectLock_ObjStore : public RGWPutBucketObjectLock {
public:
RGWPutBucketObjectLock_ObjStore() = default;
~RGWPutBucketObjectLock_ObjStore() = default;
int get_params(optional_yield y) override;
};
class RGWGetBucketObjectLock_ObjStore : public RGWGetBucketObjectLock {
public:
RGWGetBucketObjectLock_ObjStore() = default;
~RGWGetBucketObjectLock_ObjStore() override = default;
};
class RGWPutObjRetention_ObjStore : public RGWPutObjRetention {
public:
RGWPutObjRetention_ObjStore() = default;
~RGWPutObjRetention_ObjStore() override = default;
};
class RGWGetObjRetention_ObjStore : public RGWGetObjRetention {
public:
RGWGetObjRetention_ObjStore() = default;
~RGWGetObjRetention_ObjStore() = default;
};
class RGWPutObjLegalHold_ObjStore : public RGWPutObjLegalHold {
public:
RGWPutObjLegalHold_ObjStore() = default;
~RGWPutObjLegalHold_ObjStore() override = default;
int get_params(optional_yield y) override;
};
class RGWGetObjLegalHold_ObjStore : public RGWGetObjLegalHold {
public:
RGWGetObjLegalHold_ObjStore() = default;
~RGWGetObjLegalHold_ObjStore() = default;
};
class RGWRESTOp : public RGWOp {
protected:
RGWRESTFlusher flusher;
public:
void init(rgw::sal::Driver* driver, req_state *s,
RGWHandler *dialect_handler) override {
RGWOp::init(driver, s, dialect_handler);
flusher.init(s, this);
}
void send_response() override;
virtual int check_caps(const RGWUserCaps& caps)
{ return -EPERM; } /* should to be implemented! */
int verify_permission(optional_yield y) override;
dmc::client_id dmclock_client() override { return dmc::client_id::admin; }
};
class RGWHandler_REST : public RGWHandler {
protected:
virtual bool is_obj_update_op() const { return false; }
virtual RGWOp *op_get() { return NULL; }
virtual RGWOp *op_put() { return NULL; }
virtual RGWOp *op_delete() { return NULL; }
virtual RGWOp *op_head() { return NULL; }
virtual RGWOp *op_post() { return NULL; }
virtual RGWOp *op_copy() { return NULL; }
virtual RGWOp *op_options() { return NULL; }
public:
static int allocate_formatter(req_state *s, RGWFormat default_formatter,
bool configurable);
static constexpr int MAX_BUCKET_NAME_LEN = 255;
static constexpr int MAX_OBJ_NAME_LEN = 1024;
RGWHandler_REST() {}
~RGWHandler_REST() override {}
static int validate_bucket_name(const std::string& bucket);
static int validate_object_name(const std::string& object);
static int reallocate_formatter(req_state *s, RGWFormat type);
int init_permissions(RGWOp* op, optional_yield y) override;
int read_permissions(RGWOp* op, optional_yield y) override;
virtual RGWOp* get_op(void);
virtual void put_op(RGWOp* op);
};
class RGWHandler_REST_SWIFT;
class RGWHandler_SWIFT_Auth;
class RGWHandler_REST_S3;
namespace rgw::auth {
class StrategyRegistry;
}
class RGWRESTMgr {
bool should_log;
protected:
std::map<std::string, RGWRESTMgr*> resource_mgrs;
std::multimap<size_t, std::string> resources_by_size;
RGWRESTMgr* default_mgr;
virtual RGWRESTMgr* get_resource_mgr(req_state* s,
const std::string& uri,
std::string* out_uri);
virtual RGWRESTMgr* get_resource_mgr_as_default(req_state* const s,
const std::string& uri,
std::string* our_uri) {
return this;
}
public:
RGWRESTMgr()
: should_log(false),
default_mgr(nullptr) {
}
virtual ~RGWRESTMgr();
void register_resource(std::string resource, RGWRESTMgr* mgr);
void register_default_mgr(RGWRESTMgr* mgr);
virtual RGWRESTMgr* get_manager(req_state* const s,
/* Prefix to be concatenated with @uri
* during the lookup. */
const std::string& frontend_prefix,
const std::string& uri,
std::string* out_uri) final {
return get_resource_mgr(s, frontend_prefix + uri, out_uri);
}
virtual RGWHandler_REST* get_handler(
rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix
) {
return nullptr;
}
virtual void put_handler(RGWHandler_REST* const handler) {
delete handler;
}
void set_logging(bool _should_log) {
should_log = _should_log;
}
bool get_logging() const {
return should_log;
}
};
class RGWLibIO;
class RGWRestfulIO;
class RGWREST {
using x_header = basic_sstring<char, uint16_t, 32>;
boost::container::flat_set<x_header> x_headers;
RGWRESTMgr mgr;
static int preprocess(req_state *s, rgw::io::BasicClient* rio);
public:
RGWREST() {}
RGWHandler_REST *get_handler(rgw::sal::Driver* driver,
req_state *s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix,
RGWRestfulIO *rio,
RGWRESTMgr **pmgr,
int *init_error);
#if 0
RGWHandler *get_handler(RGWRados *driver, req_state *s,
RGWLibIO *io, RGWRESTMgr **pmgr,
int *init_error);
#endif
void put_handler(RGWHandler_REST *handler) {
mgr.put_handler(handler);
}
void register_resource(std::string resource, RGWRESTMgr *m,
bool register_empty = false) {
if (!register_empty && resource.empty())
return;
mgr.register_resource(resource, m);
}
void register_default_mgr(RGWRESTMgr *m) {
mgr.register_default_mgr(m);
}
void register_x_headers(const std::string& headers);
bool log_x_headers(void) {
return (x_headers.size() > 0);
}
bool log_x_header(const std::string& header) {
return (x_headers.find(header) != x_headers.end());
}
};
static constexpr int64_t NO_CONTENT_LENGTH = -1;
static constexpr int64_t CHUNKED_TRANSFER_ENCODING = -2;
extern void dump_errno(int http_ret, std::string& out);
extern void dump_errno(const struct rgw_err &err, std::string& out);
extern void dump_errno(req_state *s);
extern void dump_errno(req_state *s, int http_ret);
extern void end_header(req_state *s,
RGWOp* op = nullptr,
const char *content_type = nullptr,
const int64_t proposed_content_length =
NO_CONTENT_LENGTH,
bool force_content_type = false,
bool force_no_error = false);
extern void dump_start(req_state *s);
extern void list_all_buckets_start(req_state *s);
extern void dump_owner(req_state *s, const rgw_user& id,
const std::string& name, const char *section = NULL);
extern void dump_header(req_state* s,
const std::string_view& name,
const std::string_view& val);
extern void dump_header(req_state* s,
const std::string_view& name,
ceph::buffer::list& bl);
extern void dump_header(req_state* s,
const std::string_view& name,
long long val);
extern void dump_header(req_state* s,
const std::string_view& name,
const utime_t& val);
template <class... Args>
inline void dump_header_prefixed(req_state* s,
const std::string_view& name_prefix,
const std::string_view& name,
Args&&... args) {
char full_name_buf[name_prefix.size() + name.size() + 1];
const auto len = snprintf(full_name_buf, sizeof(full_name_buf), "%.*s%.*s",
static_cast<int>(name_prefix.length()),
name_prefix.data(),
static_cast<int>(name.length()),
name.data());
std::string_view full_name(full_name_buf, len);
return dump_header(s, std::move(full_name), std::forward<Args>(args)...);
}
template <class... Args>
inline void dump_header_infixed(req_state* s,
const std::string_view& prefix,
const std::string_view& infix,
const std::string_view& sufix,
Args&&... args) {
char full_name_buf[prefix.size() + infix.size() + sufix.size() + 1];
const auto len = snprintf(full_name_buf, sizeof(full_name_buf), "%.*s%.*s%.*s",
static_cast<int>(prefix.length()),
prefix.data(),
static_cast<int>(infix.length()),
infix.data(),
static_cast<int>(sufix.length()),
sufix.data());
std::string_view full_name(full_name_buf, len);
return dump_header(s, std::move(full_name), std::forward<Args>(args)...);
}
template <class... Args>
inline void dump_header_quoted(req_state* s,
const std::string_view& name,
const std::string_view& val) {
/* We need two extra bytes for quotes. */
char qvalbuf[val.size() + 2 + 1];
const auto len = snprintf(qvalbuf, sizeof(qvalbuf), "\"%.*s\"",
static_cast<int>(val.length()), val.data());
return dump_header(s, name, std::string_view(qvalbuf, len));
}
template <class ValueT>
inline void dump_header_if_nonempty(req_state* s,
const std::string_view& name,
const ValueT& value) {
if (name.length() > 0 && value.length() > 0) {
return dump_header(s, name, value);
}
}
inline std::string compute_domain_uri(const req_state *s) {
std::string uri = (!s->info.domain.empty()) ? s->info.domain :
[&s]() -> std::string {
RGWEnv const &env(*(s->info.env));
std::string uri =
env.get("SERVER_PORT_SECURE") ? "https://" : "http://";
if (env.exists("SERVER_NAME")) {
uri.append(env.get("SERVER_NAME", "<SERVER_NAME>"));
} else {
uri.append(env.get("HTTP_HOST", "<HTTP_HOST>"));
}
return uri;
}();
return uri;
}
extern void dump_content_length(req_state *s, uint64_t len);
extern int64_t parse_content_length(const char *content_length);
extern void dump_etag(req_state *s,
const std::string_view& etag,
bool quoted = false);
extern void dump_epoch_header(req_state *s, const char *name, real_time t);
extern void dump_time_header(req_state *s, const char *name, real_time t);
extern void dump_last_modified(req_state *s, real_time t);
extern void abort_early(req_state* s, RGWOp* op, int err,
RGWHandler* handler, optional_yield y);
extern void dump_range(req_state* s, uint64_t ofs, uint64_t end,
uint64_t total_size);
extern void dump_continue(req_state *s);
extern void list_all_buckets_end(req_state *s);
extern void dump_time(req_state *s, const char *name, real_time t);
extern std::string dump_time_to_str(const real_time& t);
extern void dump_bucket_from_state(req_state *s);
extern void dump_redirect(req_state *s, const std::string& redirect);
extern bool is_valid_url(const char *url);
extern void dump_access_control(req_state *s, const char *origin,
const char *meth,
const char *hdr, const char *exp_hdr,
uint32_t max_age);
extern void dump_access_control(req_state *s, RGWOp *op);
extern int dump_body(req_state* s, const char* buf, size_t len);
extern int dump_body(req_state* s, /* const */ ceph::buffer::list& bl);
extern int dump_body(req_state* s, const std::string& str);
extern int recv_body(req_state* s, char* buf, size_t max);
| 24,416 | 28.776829 | 120 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.