Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
ceph-main/src/rgw/rgw_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
|
null |
ceph-main/src/rgw/rgw_rest_admin.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/rgw_rest.h"
class RGWRESTMgr_Admin : public RGWRESTMgr {
public:
RGWRESTMgr_Admin() {}
~RGWRESTMgr_Admin() override {}
};
| 261 | 19.153846 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_rest_client.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_common.h"
#include "rgw_rest_client.h"
#include "rgw_auth_s3.h"
#include "rgw_http_errors.h"
#include "common/armor.h"
#include "common/strtol.h"
#include "include/str_list.h"
#include "rgw_crypt_sanitize.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
int RGWHTTPSimpleRequest::get_status()
{
int retcode = get_req_retcode();
if (retcode < 0) {
return retcode;
}
return status;
}
int RGWHTTPSimpleRequest::handle_header(const string& name, const string& val)
{
if (name == "CONTENT_LENGTH") {
string err;
long len = strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(this, 0) << "ERROR: failed converting content length (" << val << ") to int " << dendl;
return -EINVAL;
}
max_response = len;
}
return 0;
}
int RGWHTTPSimpleRequest::receive_header(void *ptr, size_t len)
{
unique_lock guard(out_headers_lock);
char line[len + 1];
char *s = (char *)ptr, *end = (char *)ptr + len;
char *p = line;
ldpp_dout(this, 30) << "receive_http_header" << dendl;
while (s != end) {
if (*s == '\r') {
s++;
continue;
}
if (*s == '\n') {
*p = '\0';
ldpp_dout(this, 30) << "received header:" << line << dendl;
// TODO: fill whatever data required here
char *l = line;
char *tok = strsep(&l, " \t:");
if (tok && l) {
while (*l == ' ')
l++;
if (strcmp(tok, "HTTP") == 0 || strncmp(tok, "HTTP/", 5) == 0) {
http_status = atoi(l);
if (http_status == 100) /* 100-continue response */
continue;
status = rgw_http_error_to_errno(http_status);
} else {
/* convert header field name to upper case */
char *src = tok;
char buf[len + 1];
size_t i;
for (i = 0; i < len && *src; ++i, ++src) {
switch (*src) {
case '-':
buf[i] = '_';
break;
default:
buf[i] = toupper(*src);
}
}
buf[i] = '\0';
out_headers[buf] = l;
int r = handle_header(buf, l);
if (r < 0)
return r;
}
}
}
if (s != end)
*p++ = *s++;
}
return 0;
}
static void get_new_date_str(string& date_str)
{
date_str = rgw_to_asctime(ceph_clock_now());
}
static void get_gmt_date_str(string& date_str)
{
auto now_time = ceph::real_clock::now();
time_t rawtime = ceph::real_clock::to_time_t(now_time);
char buffer[80];
struct tm timeInfo;
gmtime_r(&rawtime, &timeInfo);
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %z", &timeInfo);
date_str = buffer;
}
int RGWHTTPSimpleRequest::send_data(void *ptr, size_t len, bool* pause)
{
if (!send_iter)
return 0;
if (len > send_iter->get_remaining())
len = send_iter->get_remaining();
send_iter->copy(len, (char *)ptr);
return len;
}
int RGWHTTPSimpleRequest::receive_data(void *ptr, size_t len, bool *pause)
{
size_t cp_len, left_len;
left_len = max_response > response.length() ? (max_response - response.length()) : 0;
if (left_len == 0)
return 0; /* don't read extra data */
cp_len = (len > left_len) ? left_len : len;
bufferptr p((char *)ptr, cp_len);
response.append(p);
return 0;
}
static void append_param(string& dest, const string& name, const string& val)
{
if (dest.empty()) {
dest.append("?");
} else {
dest.append("&");
}
string url_name;
url_encode(name, url_name);
dest.append(url_name);
if (!val.empty()) {
string url_val;
url_encode(val, url_val);
dest.append("=");
dest.append(url_val);
}
}
static void do_get_params_str(const param_vec_t& params, map<string, string>& extra_args, string& dest)
{
map<string, string>::iterator miter;
for (miter = extra_args.begin(); miter != extra_args.end(); ++miter) {
append_param(dest, miter->first, miter->second);
}
for (auto iter = params.begin(); iter != params.end(); ++iter) {
append_param(dest, iter->first, iter->second);
}
}
void RGWHTTPSimpleRequest::get_params_str(map<string, string>& extra_args, string& dest)
{
do_get_params_str(params, extra_args, dest);
}
void RGWHTTPSimpleRequest::get_out_headers(map<string, string> *pheaders)
{
unique_lock guard(out_headers_lock);
pheaders->swap(out_headers);
out_headers.clear();
}
static int sign_request_v2(const DoutPrefixProvider *dpp, const RGWAccessKey& key,
const string& region, const string& service,
RGWEnv& env, req_info& info,
const bufferlist *opt_content)
{
/* don't sign if no key is provided */
if (key.key.empty()) {
return 0;
}
auto cct = dpp->get_cct();
if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
for (const auto& i: env.get_map()) {
ldpp_dout(dpp, 20) << __func__ << "():> " << i.first << " -> " << rgw::crypt_sanitize::x_meta_map{i.first, i.second} << dendl;
}
}
string canonical_header;
if (!rgw_create_s3_canonical_header(dpp, info, NULL, canonical_header, false)) {
ldpp_dout(dpp, 0) << "failed to create canonical s3 header" << dendl;
return -EINVAL;
}
ldpp_dout(dpp, 10) << "generated canonical header: " << canonical_header << dendl;
string digest;
try {
digest = rgw::auth::s3::get_v2_signature(cct, key.key, canonical_header);
} catch (int ret) {
return ret;
}
string auth_hdr = "AWS " + key.id + ":" + digest;
ldpp_dout(dpp, 15) << "generated auth header: " << auth_hdr << dendl;
env.set("AUTHORIZATION", auth_hdr);
return 0;
}
static int sign_request_v4(const DoutPrefixProvider *dpp, const RGWAccessKey& key,
const string& region, const string& service,
RGWEnv& env, req_info& info,
const bufferlist *opt_content)
{
/* don't sign if no key is provided */
if (key.key.empty()) {
return 0;
}
auto cct = dpp->get_cct();
if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
for (const auto& i: env.get_map()) {
ldpp_dout(dpp, 20) << __func__ << "():> " << i.first << " -> " << rgw::crypt_sanitize::x_meta_map{i.first, i.second} << dendl;
}
}
rgw::auth::s3::AWSSignerV4::prepare_result_t sigv4_data;
if (service == "s3") {
sigv4_data = rgw::auth::s3::AWSSignerV4::prepare(dpp, key.id, region, service, info, opt_content, true);
} else {
sigv4_data = rgw::auth::s3::AWSSignerV4::prepare(dpp, key.id, region, service, info, opt_content, false);
}
auto sigv4_headers = sigv4_data.signature_factory(dpp, key.key, sigv4_data);
for (auto& entry : sigv4_headers) {
ldpp_dout(dpp, 20) << __func__ << "(): sigv4 header: " << entry.first << ": " << entry.second << dendl;
env.set(entry.first, entry.second);
}
return 0;
}
static int sign_request(const DoutPrefixProvider *dpp, const RGWAccessKey& key,
const string& region, const string& service,
RGWEnv& env, req_info& info,
const bufferlist *opt_content)
{
auto authv = dpp->get_cct()->_conf.get_val<int64_t>("rgw_s3_client_max_sig_ver");
if (authv > 0 &&
authv <= 3) {
return sign_request_v2(dpp, key, region, service, env, info, opt_content);
}
return sign_request_v4(dpp, key, region, service, env, info, opt_content);
}
static string extract_region_name(string&& s)
{
if (s == "s3") {
return "us-east-1";
}
if (boost::algorithm::starts_with(s, "s3-")) {
return s.substr(3);
}
return std::move(s);
}
static bool identify_scope(const DoutPrefixProvider *dpp,
CephContext *cct,
const string& host,
string *region,
string& service)
{
if (!boost::algorithm::ends_with(host, "amazonaws.com")) {
ldpp_dout(dpp, 20) << "NOTICE: cannot identify region for connection to: " << host << dendl;
return false;
}
vector<string> vec;
get_str_vec(host, ".", vec);
string ser = service;
if (service.empty()) {
service = "s3"; /* default */
}
for (auto iter = vec.begin(); iter != vec.end(); ++iter) {
auto& s = *iter;
if (s == "s3" ||
s == "execute-api" ||
s == "iam") {
if (s == "execute-api") {
service = s;
}
++iter;
if (iter == vec.end()) {
ldpp_dout(dpp, 0) << "WARNING: cannot identify region name from host name: " << host << dendl;
return false;
}
auto& next = *iter;
if (next == "amazonaws") {
*region = "us-east-1";
return true;
}
*region = next;
return true;
} else if (boost::algorithm::starts_with(s, "s3-")) {
*region = extract_region_name(std::move(s));
return true;
}
}
return false;
}
static void scope_from_api_name(const DoutPrefixProvider *dpp,
CephContext *cct,
const string& host,
std::optional<string> api_name,
string *region,
string& service)
{
if (api_name && service.empty()) {
*region = *api_name;
service = "s3";
return;
}
if (!identify_scope(dpp, cct, host, region, service)) {
if (service == "iam") {
*region = cct->_conf->rgw_zonegroup;
} else {
*region = cct->_conf->rgw_zonegroup;
service = "s3";
}
return;
}
}
int RGWRESTSimpleRequest::forward_request(const DoutPrefixProvider *dpp, const RGWAccessKey& key, req_info& info, size_t max_response, bufferlist *inbl, bufferlist *outbl, optional_yield y, std::string service)
{
string date_str;
get_new_date_str(date_str);
RGWEnv new_env;
req_info new_info(cct, &new_env);
new_info.rebuild_from(info);
string bucket_encode;
string request_uri_encode;
size_t pos = new_info.request_uri.substr(1, new_info.request_uri.size() - 1).find("/");
string bucket = new_info.request_uri.substr(1, pos);
url_encode(bucket, bucket_encode);
if (std::string::npos != pos)
request_uri_encode = string("/") + bucket_encode + new_info.request_uri.substr(pos + 1);
else
request_uri_encode = string("/") + bucket_encode;
new_info.request_uri = request_uri_encode;
for (auto& param : params) {
new_info.args.append(param.first, param.second);
}
new_env.set("HTTP_DATE", date_str.c_str());
const char* const content_md5 = info.env->get("HTTP_CONTENT_MD5");
if (content_md5) {
new_env.set("HTTP_CONTENT_MD5", content_md5);
}
string region;
string s;
if (!service.empty()) {
s = service;
}
scope_from_api_name(dpp, cct, host, api_name, ®ion, s);
const char *maybe_payload_hash = info.env->get("HTTP_X_AMZ_CONTENT_SHA256");
if (maybe_payload_hash && s != "iam") {
new_env.set("HTTP_X_AMZ_CONTENT_SHA256", maybe_payload_hash);
}
int ret = sign_request(dpp, key, region, s, new_env, new_info, nullptr);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to sign request" << dendl;
return ret;
}
if (s == "iam") {
info.args.remove("PayloadHash");
}
for (const auto& kv: new_env.get_map()) {
headers.emplace_back(kv);
}
meta_map_t& meta_map = new_info.x_meta_map;
for (const auto& kv: meta_map) {
headers.emplace_back(kv);
}
string params_str;
get_params_str(info.args.get_params(), params_str);
string new_url = url;
string& resource = new_info.request_uri;
string new_resource = resource;
if (new_url[new_url.size() - 1] == '/' && resource[0] == '/') {
new_url = new_url.substr(0, new_url.size() - 1);
} else if (resource[0] != '/') {
new_resource = "/";
new_resource.append(resource);
}
new_url.append(new_resource + params_str);
bufferlist::iterator bliter;
if (inbl) {
bliter = inbl->begin();
send_iter = &bliter;
set_send_length(inbl->length());
}
method = new_info.method;
url = new_url;
int r = process(y);
if (r < 0){
if (r == -EINVAL){
// curl_easy has errored, generally means the service is not available
r = -ERR_SERVICE_UNAVAILABLE;
}
return r;
}
response.append((char)0); /* NULL terminate response */
if (outbl) {
*outbl = std::move(response);
}
return status;
}
class RGWRESTStreamOutCB : public RGWGetDataCB {
RGWRESTStreamS3PutObj *req;
public:
explicit RGWRESTStreamOutCB(RGWRESTStreamS3PutObj *_req) : req(_req) {}
int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override; /* callback for object iteration when sending data */
};
int RGWRESTStreamOutCB::handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len)
{
dout(20) << "RGWRESTStreamOutCB::handle_data bl.length()=" << bl.length() << " bl_ofs=" << bl_ofs << " bl_len=" << bl_len << dendl;
if (!bl_ofs && bl_len == bl.length()) {
req->add_send_data(bl);
return 0;
}
bufferptr bp(bl.c_str() + bl_ofs, bl_len);
bufferlist new_bl;
new_bl.push_back(bp);
req->add_send_data(new_bl);
return 0;
}
RGWRESTStreamS3PutObj::~RGWRESTStreamS3PutObj()
{
delete out_cb;
}
static void grants_by_type_add_one_grant(map<int, string>& grants_by_type, int perm, ACLGrant& grant)
{
string& s = grants_by_type[perm];
if (!s.empty())
s.append(", ");
string id_type_str;
ACLGranteeType& type = grant.get_type();
switch (type.get_type()) {
case ACL_TYPE_GROUP:
id_type_str = "uri";
break;
case ACL_TYPE_EMAIL_USER:
id_type_str = "emailAddress";
break;
default:
id_type_str = "id";
}
rgw_user id;
grant.get_id(id);
s.append(id_type_str + "=\"" + id.to_str() + "\"");
}
struct grant_type_to_header {
int type;
const char *header;
};
struct grant_type_to_header grants_headers_def[] = {
{ RGW_PERM_FULL_CONTROL, "x-amz-grant-full-control"},
{ RGW_PERM_READ, "x-amz-grant-read"},
{ RGW_PERM_WRITE, "x-amz-grant-write"},
{ RGW_PERM_READ_ACP, "x-amz-grant-read-acp"},
{ RGW_PERM_WRITE_ACP, "x-amz-grant-write-acp"},
{ 0, NULL}
};
static bool grants_by_type_check_perm(map<int, string>& grants_by_type, int perm, ACLGrant& grant, int check_perm)
{
if ((perm & check_perm) == check_perm) {
grants_by_type_add_one_grant(grants_by_type, check_perm, grant);
return true;
}
return false;
}
static void grants_by_type_add_perm(map<int, string>& grants_by_type, int perm, ACLGrant& grant)
{
struct grant_type_to_header *t;
for (t = grants_headers_def; t->header; t++) {
if (grants_by_type_check_perm(grants_by_type, perm, grant, t->type))
return;
}
}
static void add_grants_headers(map<int, string>& grants, RGWEnv& env, meta_map_t& meta_map)
{
struct grant_type_to_header *t;
for (t = grants_headers_def; t->header; t++) {
map<int, string>::iterator iter = grants.find(t->type);
if (iter != grants.end()) {
env.set(t->header,iter->second);
meta_map[t->header] = iter->second;
}
}
}
RGWRESTGenerateHTTPHeaders::RGWRESTGenerateHTTPHeaders(CephContext *_cct, RGWEnv *_env, req_info *_info) :
DoutPrefix(_cct, dout_subsys, "rest gen http headers: "),
cct(_cct),
new_env(_env),
new_info(_info) {
}
void RGWRESTGenerateHTTPHeaders::init(const string& _method, const string& host,
const string& resource_prefix, const string& _url,
const string& resource, const param_vec_t& params,
std::optional<string> api_name)
{
scope_from_api_name(this, cct, host, api_name, ®ion, service);
string params_str;
map<string, string>& args = new_info->args.get_params();
do_get_params_str(params, args, params_str);
/* merge params with extra args so that we can sign correctly */
for (auto iter = params.begin(); iter != params.end(); ++iter) {
new_info->args.append(iter->first, iter->second);
}
url = _url + resource + params_str;
string date_str;
get_gmt_date_str(date_str);
new_env->set("HTTP_DATE", date_str.c_str());
new_env->set("HTTP_HOST", host);
method = _method;
new_info->method = method.c_str();
new_info->host = host;
new_info->script_uri = "/";
new_info->script_uri.append(resource_prefix);
new_info->script_uri.append(resource);
new_info->request_uri = new_info->script_uri;
}
static bool is_x_amz(const string& s) {
return boost::algorithm::starts_with(s, "x-amz-");
}
void RGWRESTGenerateHTTPHeaders::set_extra_headers(const map<string, string>& extra_headers)
{
for (auto iter : extra_headers) {
const string& name = lowercase_dash_http_attr(iter.first);
new_env->set(name, iter.second.c_str());
if (is_x_amz(name)) {
new_info->x_meta_map[name] = iter.second;
}
}
}
int RGWRESTGenerateHTTPHeaders::set_obj_attrs(const DoutPrefixProvider *dpp, map<string, bufferlist>& rgw_attrs)
{
map<string, string> new_attrs;
/* merge send headers */
for (auto& attr: rgw_attrs) {
bufferlist& bl = attr.second;
const string& name = attr.first;
string val = bl.c_str();
if (name.compare(0, sizeof(RGW_ATTR_META_PREFIX) - 1, RGW_ATTR_META_PREFIX) == 0) {
string header_name = RGW_AMZ_META_PREFIX;
header_name.append(name.substr(sizeof(RGW_ATTR_META_PREFIX) - 1));
new_attrs[header_name] = val;
}
}
RGWAccessControlPolicy policy;
int ret = rgw_policy_from_attrset(dpp, cct, rgw_attrs, &policy);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: couldn't get policy ret=" << ret << dendl;
return ret;
}
set_http_attrs(new_attrs);
set_policy(policy);
return 0;
}
void RGWRESTGenerateHTTPHeaders::set_http_attrs(const map<string, string>& http_attrs)
{
/* merge send headers */
for (auto& attr: http_attrs) {
const string& val = attr.second;
const string& name = lowercase_dash_http_attr(attr.first);
if (is_x_amz(name)) {
new_env->set(name, val);
new_info->x_meta_map[name] = val;
} else {
new_env->set(attr.first, val); /* Ugh, using the uppercase representation,
as the signing function calls info.env.get("CONTENT_TYPE").
This needs to be cleaned up! */
}
}
}
void RGWRESTGenerateHTTPHeaders::set_policy(RGWAccessControlPolicy& policy)
{
/* update acl headers */
RGWAccessControlList& acl = policy.get_acl();
multimap<string, ACLGrant>& grant_map = acl.get_grant_map();
multimap<string, ACLGrant>::iterator giter;
map<int, string> grants_by_type;
for (giter = grant_map.begin(); giter != grant_map.end(); ++giter) {
ACLGrant& grant = giter->second;
ACLPermission& perm = grant.get_permission();
grants_by_type_add_perm(grants_by_type, perm.get_permissions(), grant);
}
add_grants_headers(grants_by_type, *new_env, new_info->x_meta_map);
}
int RGWRESTGenerateHTTPHeaders::sign(const DoutPrefixProvider *dpp, RGWAccessKey& key, const bufferlist *opt_content)
{
int ret = sign_request(dpp, key, region, service, *new_env, *new_info, opt_content);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to sign request" << dendl;
return ret;
}
return 0;
}
void RGWRESTStreamS3PutObj::send_init(const rgw_obj& obj)
{
string resource_str;
string resource;
string new_url = url;
string new_host = host;
const auto& bucket_name = obj.bucket.name;
if (host_style == VirtualStyle) {
resource_str = obj.get_oid();
new_url = bucket_name + "." + new_url;
new_host = bucket_name + "." + new_host;
} else {
resource_str = bucket_name + "/" + obj.get_oid();
}
//do not encode slash in object key name
url_encode(resource_str, resource, false);
if (new_url[new_url.size() - 1] != '/')
new_url.append("/");
method = "PUT";
headers_gen.init(method, new_host, resource_prefix, new_url, resource, params, api_name);
url = headers_gen.get_url();
}
void RGWRESTStreamS3PutObj::send_ready(const DoutPrefixProvider *dpp, RGWAccessKey& key, map<string, bufferlist>& rgw_attrs)
{
headers_gen.set_obj_attrs(dpp, rgw_attrs);
send_ready(dpp, key);
}
void RGWRESTStreamS3PutObj::send_ready(const DoutPrefixProvider *dpp, RGWAccessKey& key, const map<string, string>& http_attrs,
RGWAccessControlPolicy& policy)
{
headers_gen.set_http_attrs(http_attrs);
headers_gen.set_policy(policy);
send_ready(dpp, key);
}
void RGWRESTStreamS3PutObj::send_ready(const DoutPrefixProvider *dpp, RGWAccessKey& key)
{
headers_gen.sign(dpp, key, nullptr);
for (const auto& kv: new_env.get_map()) {
headers.emplace_back(kv);
}
out_cb = new RGWRESTStreamOutCB(this);
}
void RGWRESTStreamS3PutObj::put_obj_init(const DoutPrefixProvider *dpp, RGWAccessKey& key, const rgw_obj& obj, map<string, bufferlist>& attrs)
{
send_init(obj);
send_ready(dpp, key, attrs);
}
void set_str_from_headers(map<string, string>& out_headers, const string& header_name, string& str)
{
map<string, string>::iterator iter = out_headers.find(header_name);
if (iter != out_headers.end()) {
str = iter->second;
} else {
str.clear();
}
}
static int parse_rgwx_mtime(const DoutPrefixProvider *dpp, CephContext *cct, const string& s, ceph::real_time *rt)
{
string err;
vector<string> vec;
get_str_vec(s, ".", vec);
if (vec.empty()) {
return -EINVAL;
}
long secs = strict_strtol(vec[0].c_str(), 10, &err);
long nsecs = 0;
if (!err.empty()) {
ldpp_dout(dpp, 0) << "ERROR: failed converting mtime (" << s << ") to real_time " << dendl;
return -EINVAL;
}
if (vec.size() > 1) {
nsecs = strict_strtol(vec[1].c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(dpp, 0) << "ERROR: failed converting mtime (" << s << ") to real_time " << dendl;
return -EINVAL;
}
}
*rt = utime_t(secs, nsecs).to_real_time();
return 0;
}
static void send_prepare_convert(const rgw_obj& obj, string *resource)
{
string urlsafe_bucket, urlsafe_object;
url_encode(obj.bucket.get_key(':', 0), urlsafe_bucket);
url_encode(obj.key.name, urlsafe_object);
*resource = urlsafe_bucket + "/" + urlsafe_object;
}
int RGWRESTStreamRWRequest::send_request(const DoutPrefixProvider *dpp, RGWAccessKey& key, map<string, string>& extra_headers, const rgw_obj& obj, RGWHTTPManager *mgr)
{
string resource;
send_prepare_convert(obj, &resource);
return send_request(dpp, &key, extra_headers, resource, mgr);
}
int RGWRESTStreamRWRequest::send_prepare(const DoutPrefixProvider *dpp, RGWAccessKey& key, map<string, string>& extra_headers, const rgw_obj& obj)
{
string resource;
send_prepare_convert(obj, &resource);
return do_send_prepare(dpp, &key, extra_headers, resource);
}
int RGWRESTStreamRWRequest::send_prepare(const DoutPrefixProvider *dpp, RGWAccessKey *key, map<string, string>& extra_headers, const string& resource,
bufferlist *send_data)
{
string new_resource;
//do not encode slash
url_encode(resource, new_resource, false);
return do_send_prepare(dpp, key, extra_headers, new_resource, send_data);
}
int RGWRESTStreamRWRequest::do_send_prepare(const DoutPrefixProvider *dpp, RGWAccessKey *key, map<string, string>& extra_headers, const string& resource,
bufferlist *send_data)
{
string new_url = url;
if (!new_url.empty() && new_url.back() != '/')
new_url.append("/");
string new_resource;
string bucket_name;
string old_resource = resource;
if (resource[0] == '/') {
new_resource = resource.substr(1);
} else {
new_resource = resource;
}
size_t pos = new_resource.find("/");
bucket_name = new_resource.substr(0, pos);
//when dest is a bucket with out other params, uri should end up with '/'
if(pos == string::npos && params.size() == 0 && host_style == VirtualStyle) {
new_resource.append("/");
}
if (host_style == VirtualStyle) {
new_url = protocol + "://" + bucket_name + "." + host;
if(pos == string::npos) {
new_resource = "";
} else {
new_resource = new_resource.substr(pos+1);
}
}
headers_gen.emplace(cct, &new_env, &new_info);
headers_gen->init(method, host, resource_prefix, new_url, new_resource, params, api_name);
headers_gen->set_http_attrs(extra_headers);
if (key) {
sign_key = *key;
}
if (send_data) {
set_send_length(send_data->length());
set_outbl(*send_data);
set_send_data_hint(true);
}
method = new_info.method;
url = headers_gen->get_url();
return 0;
}
int RGWRESTStreamRWRequest::send_request(const DoutPrefixProvider *dpp, RGWAccessKey *key, map<string, string>& extra_headers, const string& resource,
RGWHTTPManager *mgr, bufferlist *send_data)
{
int ret = send_prepare(dpp, key, extra_headers, resource, send_data);
if (ret < 0) {
return ret;
}
return send(mgr);
}
int RGWRESTStreamRWRequest::send(RGWHTTPManager *mgr)
{
if (!headers_gen) {
ldpp_dout(this, 0) << "ERROR: " << __func__ << "(): send_prepare() was not called: likey a bug!" << dendl;
return -EINVAL;
}
const bufferlist *outblp{nullptr};
if (send_len == outbl.length()) {
outblp = &outbl;
}
if (sign_key) {
int r = headers_gen->sign(this, *sign_key, outblp);
if (r < 0) {
ldpp_dout(this, 0) << "ERROR: failed to sign request" << dendl;
return r;
}
}
for (const auto& kv: new_env.get_map()) {
headers.emplace_back(kv);
}
return RGWHTTPStreamRWRequest::send(mgr);
}
int RGWHTTPStreamRWRequest::complete_request(optional_yield y,
string *etag,
real_time *mtime,
uint64_t *psize,
map<string, string> *pattrs,
map<string, string> *pheaders)
{
int ret = wait(y);
if (ret < 0) {
return ret;
}
unique_lock guard(out_headers_lock);
if (etag) {
set_str_from_headers(out_headers, "ETAG", *etag);
}
if (status >= 0) {
if (mtime) {
string mtime_str;
set_str_from_headers(out_headers, "RGWX_MTIME", mtime_str);
if (!mtime_str.empty()) {
int ret = parse_rgwx_mtime(this, cct, mtime_str, mtime);
if (ret < 0) {
return ret;
}
} else {
*mtime = real_time();
}
}
if (psize) {
string size_str;
set_str_from_headers(out_headers, "RGWX_OBJECT_SIZE", size_str);
string err;
*psize = strict_strtoll(size_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(this, 0) << "ERROR: failed parsing embedded metadata object size (" << size_str << ") to int " << dendl;
return -EIO;
}
}
}
for (auto iter = out_headers.begin(); pattrs && iter != out_headers.end(); ++iter) {
const string& attr_name = iter->first;
if (attr_name.compare(0, sizeof(RGW_HTTP_RGWX_ATTR_PREFIX) - 1, RGW_HTTP_RGWX_ATTR_PREFIX) == 0) {
string name = attr_name.substr(sizeof(RGW_HTTP_RGWX_ATTR_PREFIX) - 1);
const char *src = name.c_str();
char buf[name.size() + 1];
char *dest = buf;
for (; *src; ++src, ++dest) {
switch(*src) {
case '_':
*dest = '-';
break;
default:
*dest = tolower(*src);
}
}
*dest = '\0';
(*pattrs)[buf] = iter->second;
}
}
if (pheaders) {
*pheaders = std::move(out_headers);
}
return status;
}
int RGWHTTPStreamRWRequest::handle_header(const string& name, const string& val)
{
if (name == "RGWX_EMBEDDED_METADATA_LEN") {
string err;
long len = strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(this, 0) << "ERROR: failed converting embedded metadata len (" << val << ") to int " << dendl;
return -EINVAL;
}
cb->set_extra_data_len(len);
}
return 0;
}
int RGWHTTPStreamRWRequest::receive_data(void *ptr, size_t len, bool *pause)
{
size_t orig_len = len;
if (cb) {
in_data.append((const char *)ptr, len);
size_t orig_in_data_len = in_data.length();
int ret = cb->handle_data(in_data, pause);
if (ret < 0)
return ret;
if (ret == 0) {
in_data.clear();
} else {
/* partial read */
ceph_assert(in_data.length() <= orig_in_data_len);
len = ret;
bufferlist bl;
size_t left_to_read = orig_in_data_len - len;
if (in_data.length() > left_to_read) {
in_data.splice(0, in_data.length() - left_to_read, &bl);
}
}
}
ofs += len;
return orig_len;
}
void RGWHTTPStreamRWRequest::set_stream_write(bool s) {
std::lock_guard wl{write_lock};
stream_writes = s;
}
void RGWHTTPStreamRWRequest::unpause_receive()
{
std::lock_guard req_locker{get_req_lock()};
if (!read_paused) {
_set_read_paused(false);
}
}
void RGWHTTPStreamRWRequest::add_send_data(bufferlist& bl)
{
std::scoped_lock locker{get_req_lock(), write_lock};
outbl.claim_append(bl);
_set_write_paused(false);
}
uint64_t RGWHTTPStreamRWRequest::get_pending_send_size()
{
std::lock_guard wl{write_lock};
return outbl.length();
}
void RGWHTTPStreamRWRequest::finish_write()
{
std::scoped_lock locker{get_req_lock(), write_lock};
write_stream_complete = true;
_set_write_paused(false);
}
int RGWHTTPStreamRWRequest::send_data(void *ptr, size_t len, bool *pause)
{
uint64_t out_len;
uint64_t send_size;
{
std::lock_guard wl{write_lock};
if (outbl.length() == 0) {
if ((stream_writes && !write_stream_complete) ||
(write_ofs < send_len)) {
*pause = true;
}
return 0;
}
len = std::min(len, (size_t)outbl.length());
bufferlist bl;
outbl.splice(0, len, &bl);
send_size = bl.length();
if (send_size > 0) {
memcpy(ptr, bl.c_str(), send_size);
write_ofs += send_size;
}
out_len = outbl.length();
}
/* don't need to be under write_lock here, avoid deadlocks in case notify callback
* needs to lock */
if (write_drain_cb) {
write_drain_cb->notify(out_len);
}
return send_size;
}
int RGWHTTPStreamRWRequest::send(RGWHTTPManager *mgr)
{
if (!mgr) {
return RGWHTTP::send(this);
}
int r = mgr->add_request(this);
if (r < 0)
return r;
return 0;
}
| 30,784 | 26.364444 | 210 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_client.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "rgw_http_client.h"
class RGWGetDataCB;
class RGWHTTPSimpleRequest : public RGWHTTPClient {
protected:
int http_status;
int status;
using unique_lock = std::unique_lock<std::mutex>;
std::mutex out_headers_lock;
std::map<std::string, std::string> out_headers;
param_vec_t params;
bufferlist::iterator *send_iter;
size_t max_response; /* we need this as we don't stream out response */
bufferlist response;
virtual int handle_header(const std::string& name, const std::string& val);
void get_params_str(std::map<std::string, std::string>& extra_args, std::string& dest);
public:
RGWHTTPSimpleRequest(CephContext *_cct, const std::string& _method, const std::string& _url,
param_vec_t *_headers, param_vec_t *_params) : RGWHTTPClient(_cct, _method, _url),
http_status(0), status(0),
send_iter(NULL),
max_response(0) {
set_headers(_headers);
set_params(_params);
}
void set_headers(param_vec_t *_headers) {
if (_headers)
headers = *_headers;
}
void set_params(param_vec_t *_params) {
if (_params)
params = *_params;
}
int receive_header(void *ptr, size_t len) override;
int receive_data(void *ptr, size_t len, bool *pause) override;
int send_data(void *ptr, size_t len, bool* pause=nullptr) override;
bufferlist& get_response() { return response; }
void get_out_headers(std::map<std::string, std::string> *pheaders); /* modifies out_headers */
int get_http_status() { return http_status; }
int get_status();
};
class RGWRESTSimpleRequest : public RGWHTTPSimpleRequest {
std::optional<std::string> api_name;
public:
RGWRESTSimpleRequest(CephContext *_cct, const std::string& _method, const std::string& _url,
param_vec_t *_headers, param_vec_t *_params,
std::optional<std::string> _api_name) : RGWHTTPSimpleRequest(_cct, _method, _url, _headers, _params), api_name(_api_name) {}
int forward_request(const DoutPrefixProvider *dpp, const RGWAccessKey& key, req_info& info, size_t max_response, bufferlist *inbl, bufferlist *outbl, optional_yield y, std::string service="");
};
class RGWWriteDrainCB {
public:
RGWWriteDrainCB() = default;
virtual ~RGWWriteDrainCB() = default;
virtual void notify(uint64_t pending_size) = 0;
};
class RGWRESTGenerateHTTPHeaders : public DoutPrefix {
CephContext *cct;
RGWEnv *new_env;
req_info *new_info;
std::string region;
std::string service;
std::string method;
std::string url;
std::string resource;
public:
RGWRESTGenerateHTTPHeaders(CephContext *_cct, RGWEnv *_env, req_info *_info);
void init(const std::string& method, const std::string& host,
const std::string& resource_prefix, const std::string& url,
const std::string& resource, const param_vec_t& params,
std::optional<std::string> api_name);
void set_extra_headers(const std::map<std::string, std::string>& extra_headers);
int set_obj_attrs(const DoutPrefixProvider *dpp, std::map<std::string, bufferlist>& rgw_attrs);
void set_http_attrs(const std::map<std::string, std::string>& http_attrs);
void set_policy(RGWAccessControlPolicy& policy);
int sign(const DoutPrefixProvider *dpp, RGWAccessKey& key, const bufferlist *opt_content);
const std::string& get_url() { return url; }
};
class RGWHTTPStreamRWRequest : public RGWHTTPSimpleRequest {
public:
class ReceiveCB;
private:
ceph::mutex lock =
ceph::make_mutex("RGWHTTPStreamRWRequest");
ceph::mutex write_lock =
ceph::make_mutex("RGWHTTPStreamRWRequest::write_lock");
ReceiveCB *cb{nullptr};
RGWWriteDrainCB *write_drain_cb{nullptr};
bufferlist in_data;
size_t chunk_ofs{0};
size_t ofs{0};
uint64_t write_ofs{0};
bool read_paused{false};
bool send_paused{false};
bool stream_writes{false};
bool write_stream_complete{false};
protected:
bufferlist outbl;
int handle_header(const std::string& name, const std::string& val) override;
public:
int send_data(void *ptr, size_t len, bool *pause) override;
int receive_data(void *ptr, size_t len, bool *pause) override;
class ReceiveCB {
protected:
uint64_t extra_data_len{0};
public:
ReceiveCB() = default;
virtual ~ReceiveCB() = default;
virtual int handle_data(bufferlist& bl, bool *pause = nullptr) = 0;
virtual void set_extra_data_len(uint64_t len) {
extra_data_len = len;
}
};
RGWHTTPStreamRWRequest(CephContext *_cct, const std::string& _method, const std::string& _url,
param_vec_t *_headers, param_vec_t *_params) : RGWHTTPSimpleRequest(_cct, _method, _url, _headers, _params) {
}
RGWHTTPStreamRWRequest(CephContext *_cct, const std::string& _method, const std::string& _url, ReceiveCB *_cb,
param_vec_t *_headers, param_vec_t *_params) : RGWHTTPSimpleRequest(_cct, _method, _url, _headers, _params),
cb(_cb) {
}
virtual ~RGWHTTPStreamRWRequest() override {}
void set_outbl(bufferlist& _outbl) {
outbl.swap(_outbl);
}
void set_in_cb(ReceiveCB *_cb) { cb = _cb; }
void set_write_drain_cb(RGWWriteDrainCB *_cb) { write_drain_cb = _cb; }
void unpause_receive();
void add_send_data(bufferlist& bl);
void set_stream_write(bool s);
uint64_t get_pending_send_size();
/* finish streaming writes */
void finish_write();
virtual int send(RGWHTTPManager *mgr);
int complete_request(optional_yield y,
std::string *etag = nullptr,
real_time *mtime = nullptr,
uint64_t *psize = nullptr,
std::map<std::string, std::string> *pattrs = nullptr,
std::map<std::string, std::string> *pheaders = nullptr);
};
class RGWRESTStreamRWRequest : public RGWHTTPStreamRWRequest {
std::optional<RGWAccessKey> sign_key;
std::optional<RGWRESTGenerateHTTPHeaders> headers_gen;
RGWEnv new_env;
req_info new_info;
protected:
std::optional<std::string> api_name;
HostStyle host_style;
public:
RGWRESTStreamRWRequest(CephContext *_cct, const std::string& _method, const std::string& _url, RGWHTTPStreamRWRequest::ReceiveCB *_cb,
param_vec_t *_headers, param_vec_t *_params,
std::optional<std::string> _api_name, HostStyle _host_style = PathStyle) :
RGWHTTPStreamRWRequest(_cct, _method, _url, _cb, _headers, _params),
new_info(_cct, &new_env),
api_name(_api_name), host_style(_host_style) {
}
virtual ~RGWRESTStreamRWRequest() override {}
int send_prepare(const DoutPrefixProvider *dpp, RGWAccessKey *key, std::map<std::string, std::string>& extra_headers, const std::string& resource, bufferlist *send_data = nullptr /* optional input data */);
int send_prepare(const DoutPrefixProvider *dpp, RGWAccessKey& key, std::map<std::string, std::string>& extra_headers, const rgw_obj& obj);
int send(RGWHTTPManager *mgr) override;
int send_request(const DoutPrefixProvider *dpp, RGWAccessKey& key, std::map<std::string, std::string>& extra_headers, const rgw_obj& obj, RGWHTTPManager *mgr);
int send_request(const DoutPrefixProvider *dpp, RGWAccessKey *key, std::map<std::string, std::string>& extra_headers, const std::string& resource, RGWHTTPManager *mgr, bufferlist *send_data = nullptr /* optional input data */);
void add_params(param_vec_t *params);
private:
int do_send_prepare(const DoutPrefixProvider *dpp, RGWAccessKey *key, std::map<std::string, std::string>& extra_headers, const std::string& resource, bufferlist *send_data = nullptr /* optional input data */);
};
class RGWRESTStreamReadRequest : public RGWRESTStreamRWRequest {
public:
RGWRESTStreamReadRequest(CephContext *_cct, const std::string& _url, ReceiveCB *_cb, param_vec_t *_headers,
param_vec_t *_params, std::optional<std::string> _api_name,
HostStyle _host_style = PathStyle) : RGWRESTStreamRWRequest(_cct, "GET", _url, _cb, _headers, _params, _api_name, _host_style) {}
};
class RGWRESTStreamHeadRequest : public RGWRESTStreamRWRequest {
public:
RGWRESTStreamHeadRequest(CephContext *_cct, const std::string& _url, ReceiveCB *_cb, param_vec_t *_headers,
param_vec_t *_params, std::optional<std::string> _api_name) : RGWRESTStreamRWRequest(_cct, "HEAD", _url, _cb, _headers, _params, _api_name) {}
};
class RGWRESTStreamSendRequest : public RGWRESTStreamRWRequest {
public:
RGWRESTStreamSendRequest(CephContext *_cct, const std::string& method,
const std::string& _url,
ReceiveCB *_cb, param_vec_t *_headers, param_vec_t *_params,
std::optional<std::string> _api_name,
HostStyle _host_style = PathStyle) : RGWRESTStreamRWRequest(_cct, method, _url, _cb, _headers, _params, _api_name, _host_style) {}
};
class RGWRESTStreamS3PutObj : public RGWHTTPStreamRWRequest {
std::optional<std::string> api_name;
HostStyle host_style;
RGWGetDataCB *out_cb;
RGWEnv new_env;
req_info new_info;
RGWRESTGenerateHTTPHeaders headers_gen;
public:
RGWRESTStreamS3PutObj(CephContext *_cct, const std::string& _method, const std::string& _url, param_vec_t *_headers,
param_vec_t *_params, std::optional<std::string> _api_name,
HostStyle _host_style) : RGWHTTPStreamRWRequest(_cct, _method, _url, nullptr, _headers, _params),
api_name(_api_name), host_style(_host_style),
out_cb(NULL), new_info(cct, &new_env), headers_gen(_cct, &new_env, &new_info) {}
~RGWRESTStreamS3PutObj() override;
void send_init(const rgw_obj& obj);
void send_ready(const DoutPrefixProvider *dpp, RGWAccessKey& key, std::map<std::string, bufferlist>& rgw_attrs);
void send_ready(const DoutPrefixProvider *dpp, RGWAccessKey& key, const std::map<std::string, std::string>& http_attrs,
RGWAccessControlPolicy& policy);
void send_ready(const DoutPrefixProvider *dpp, RGWAccessKey& key);
void put_obj_init(const DoutPrefixProvider *dpp, RGWAccessKey& key, const rgw_obj& obj, std::map<std::string, bufferlist>& attrs);
RGWGetDataCB *get_out_cb() { return out_cb; }
};
| 10,392 | 39.282946 | 229 |
h
|
null |
ceph-main/src/rgw/rgw_rest_config.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/ceph_json.h"
#include "common/strtol.h"
#include "rgw_rest.h"
#include "rgw_op.h"
#include "rgw_rados.h"
#include "rgw_rest_s3.h"
#include "rgw_rest_config.h"
#include "rgw_client_io.h"
#include "rgw_sal_rados.h"
#include "common/errno.h"
#include "include/ceph_assert.h"
#include "services/svc_zone.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
void RGWOp_ZoneConfig_Get::send_response() {
const RGWZoneParams& zone_params = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_params();
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s);
if (op_ret < 0)
return;
encode_json("zone_params", zone_params, s->formatter);
flusher.flush();
}
RGWOp* RGWHandler_Config::op_get() {
bool exists;
string type = s->info.args.get("type", &exists);
if (type.compare("zone") == 0) {
return new RGWOp_ZoneConfig_Get();
}
return nullptr;
}
| 1,392 | 23.017241 | 112 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_config.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "rgw_auth_s3.h"
#include "rgw_rest.h"
#include "rgw_zone.h"
class RGWOp_ZoneConfig_Get : public RGWRESTOp {
RGWZoneParams zone_params;
public:
RGWOp_ZoneConfig_Get() {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("zone", RGW_CAP_READ);
}
int verify_permission(optional_yield) override {
return check_caps(s->user->get_caps());
}
void execute(optional_yield) override {} /* driver already has the info we need, just need to send response */
void send_response() override ;
const char* name() const override {
return "get_zone_config";
}
};
class RGWHandler_Config : public RGWHandler_Auth_S3 {
protected:
RGWOp *op_get() override;
int read_permissions(RGWOp*, optional_yield) override {
return 0;
}
public:
using RGWHandler_Auth_S3::RGWHandler_Auth_S3;
~RGWHandler_Config() override = default;
};
class RGWRESTMgr_Config : public RGWRESTMgr {
public:
RGWRESTMgr_Config() = default;
~RGWRESTMgr_Config() override = default;
RGWHandler_REST* get_handler(rgw::sal::Driver* ,
req_state*,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string&) override {
return new RGWHandler_Config(auth_registry);
}
};
| 1,739 | 25.769231 | 112 |
h
|
null |
ceph-main/src/rgw/rgw_rest_conn.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_zone.h"
#include "rgw_rest_conn.h"
#include "rgw_sal.h"
#include "rgw_rados.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
RGWRESTConn::RGWRESTConn(CephContext *_cct, rgw::sal::Driver* driver,
const string& _remote_id,
const list<string>& remote_endpoints,
std::optional<string> _api_name,
HostStyle _host_style)
: cct(_cct),
endpoints(remote_endpoints.begin(), remote_endpoints.end()),
remote_id(_remote_id),
api_name(_api_name),
host_style(_host_style)
{
if (driver) {
key = driver->get_zone()->get_system_key();
self_zone_group = driver->get_zone()->get_zonegroup().get_id();
}
}
RGWRESTConn::RGWRESTConn(CephContext *_cct,
const string& _remote_id,
const list<string>& remote_endpoints,
RGWAccessKey _cred,
std::string _zone_group,
std::optional<string> _api_name,
HostStyle _host_style)
: cct(_cct),
endpoints(remote_endpoints.begin(), remote_endpoints.end()),
key(_cred),
self_zone_group(_zone_group),
remote_id(_remote_id),
api_name(_api_name),
host_style(_host_style)
{
}
RGWRESTConn::RGWRESTConn(RGWRESTConn&& other)
: cct(other.cct),
endpoints(std::move(other.endpoints)),
key(std::move(other.key)),
self_zone_group(std::move(other.self_zone_group)),
remote_id(std::move(other.remote_id)),
counter(other.counter.load())
{
}
RGWRESTConn& RGWRESTConn::operator=(RGWRESTConn&& other)
{
cct = other.cct;
endpoints = std::move(other.endpoints);
key = std::move(other.key);
self_zone_group = std::move(other.self_zone_group);
remote_id = std::move(other.remote_id);
counter = other.counter.load();
return *this;
}
int RGWRESTConn::get_url(string& endpoint)
{
if (endpoints.empty()) {
ldout(cct, 0) << "ERROR: endpoints not configured for upstream zone" << dendl;
return -EIO;
}
int i = ++counter;
endpoint = endpoints[i % endpoints.size()];
return 0;
}
string RGWRESTConn::get_url()
{
string endpoint;
get_url(endpoint);
return endpoint;
}
void RGWRESTConn::populate_params(param_vec_t& params, const rgw_user *uid, const string& zonegroup)
{
populate_uid(params, uid);
populate_zonegroup(params, zonegroup);
}
int RGWRESTConn::forward(const DoutPrefixProvider *dpp, const rgw_user& uid, req_info& info, obj_version *objv, size_t max_response, bufferlist *inbl, bufferlist *outbl, optional_yield y)
{
string url;
int ret = get_url(url);
if (ret < 0)
return ret;
param_vec_t params;
populate_params(params, &uid, self_zone_group);
if (objv) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "tag", objv->tag));
char buf[16];
snprintf(buf, sizeof(buf), "%lld", (long long)objv->ver);
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "ver", buf));
}
RGWRESTSimpleRequest req(cct, info.method, url, NULL, ¶ms, api_name);
return req.forward_request(dpp, key, info, max_response, inbl, outbl, y);
}
int RGWRESTConn::forward_iam_request(const DoutPrefixProvider *dpp, const RGWAccessKey& key, req_info& info, obj_version *objv, size_t max_response, bufferlist *inbl, bufferlist *outbl, optional_yield y)
{
string url;
int ret = get_url(url);
if (ret < 0)
return ret;
param_vec_t params;
if (objv) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "tag", objv->tag));
char buf[16];
snprintf(buf, sizeof(buf), "%lld", (long long)objv->ver);
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "ver", buf));
}
std::string service = "iam";
RGWRESTSimpleRequest req(cct, info.method, url, NULL, ¶ms, api_name);
return req.forward_request(dpp, key, info, max_response, inbl, outbl, y, service);
}
int RGWRESTConn::put_obj_send_init(const rgw_obj& obj, const rgw_http_param_pair *extra_params, RGWRESTStreamS3PutObj **req)
{
string url;
int ret = get_url(url);
if (ret < 0)
return ret;
rgw_user uid;
param_vec_t params;
populate_params(params, &uid, self_zone_group);
if (extra_params) {
append_param_list(params, extra_params);
}
RGWRESTStreamS3PutObj *wr = new RGWRESTStreamS3PutObj(cct, "PUT", url, NULL, ¶ms, api_name, host_style);
wr->send_init(obj);
*req = wr;
return 0;
}
int RGWRESTConn::put_obj_async_init(const DoutPrefixProvider *dpp, const rgw_user& uid, const rgw_obj& obj,
map<string, bufferlist>& attrs,
RGWRESTStreamS3PutObj **req)
{
string url;
int ret = get_url(url);
if (ret < 0)
return ret;
param_vec_t params;
populate_params(params, &uid, self_zone_group);
RGWRESTStreamS3PutObj *wr = new RGWRESTStreamS3PutObj(cct, "PUT", url, NULL, ¶ms, api_name, host_style);
wr->put_obj_init(dpp, key, obj, attrs);
*req = wr;
return 0;
}
int RGWRESTConn::complete_request(RGWRESTStreamS3PutObj *req, string& etag,
real_time *mtime, optional_yield y)
{
int ret = req->complete_request(y, &etag, mtime);
delete req;
return ret;
}
static void set_date_header(const real_time *t, map<string, string>& headers, bool high_precision_time, const string& header_name)
{
if (!t) {
return;
}
stringstream s;
utime_t tm = utime_t(*t);
if (high_precision_time) {
tm.gmtime_nsec(s);
} else {
tm.gmtime(s);
}
headers[header_name] = s.str();
}
template <class T>
static void set_header(T val, map<string, string>& headers, const string& header_name)
{
stringstream s;
s << val;
headers[header_name] = s.str();
}
int RGWRESTConn::get_obj(const DoutPrefixProvider *dpp, const rgw_user& uid, req_info *info /* optional */, const rgw_obj& obj,
const real_time *mod_ptr, const real_time *unmod_ptr,
uint32_t mod_zone_id, uint64_t mod_pg_ver,
bool prepend_metadata, bool get_op, bool rgwx_stat,
bool sync_manifest, bool skip_decrypt,
rgw_zone_set_entry *dst_zone_trace, bool sync_cloudtiered,
bool send, RGWHTTPStreamRWRequest::ReceiveCB *cb, RGWRESTStreamRWRequest **req)
{
get_obj_params params;
params.uid = uid;
params.info = info;
params.mod_ptr = mod_ptr;
params.mod_pg_ver = mod_pg_ver;
params.prepend_metadata = prepend_metadata;
params.get_op = get_op;
params.rgwx_stat = rgwx_stat;
params.sync_manifest = sync_manifest;
params.skip_decrypt = skip_decrypt;
params.sync_cloudtiered = sync_cloudtiered;
params.dst_zone_trace = dst_zone_trace;
params.cb = cb;
return get_obj(dpp, obj, params, send, req);
}
int RGWRESTConn::get_obj(const DoutPrefixProvider *dpp, const rgw_obj& obj, const get_obj_params& in_params, bool send, RGWRESTStreamRWRequest **req)
{
string url;
int ret = get_url(url);
if (ret < 0)
return ret;
param_vec_t params;
populate_params(params, &in_params.uid, self_zone_group);
if (in_params.prepend_metadata) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "prepend-metadata", "true"));
}
if (in_params.rgwx_stat) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "stat", "true"));
}
if (in_params.sync_manifest) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "sync-manifest", ""));
}
if (in_params.sync_cloudtiered) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "sync-cloudtiered", ""));
}
if (in_params.skip_decrypt) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "skip-decrypt", ""));
}
if (in_params.dst_zone_trace) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "if-not-replicated-to", in_params.dst_zone_trace->to_str()));
}
if (!obj.key.instance.empty()) {
params.push_back(param_pair_t("versionId", obj.key.instance));
}
if (in_params.get_op) {
*req = new RGWRESTStreamReadRequest(cct, url, in_params.cb, NULL, ¶ms, api_name, host_style);
} else {
*req = new RGWRESTStreamHeadRequest(cct, url, in_params.cb, NULL, ¶ms, api_name);
}
map<string, string> extra_headers;
if (in_params.info) {
const auto& orig_map = in_params.info->env->get_map();
/* add original headers that start with HTTP_X_AMZ_ */
static constexpr char SEARCH_AMZ_PREFIX[] = "HTTP_X_AMZ_";
for (auto iter= orig_map.lower_bound(SEARCH_AMZ_PREFIX); iter != orig_map.end(); ++iter) {
const string& name = iter->first;
if (name == "HTTP_X_AMZ_DATE") /* don't forward date from original request */
continue;
if (name.compare(0, strlen(SEARCH_AMZ_PREFIX), SEARCH_AMZ_PREFIX) != 0)
break;
extra_headers[iter->first] = iter->second;
}
}
set_date_header(in_params.mod_ptr, extra_headers, in_params.high_precision_time, "HTTP_IF_MODIFIED_SINCE");
set_date_header(in_params.unmod_ptr, extra_headers, in_params.high_precision_time, "HTTP_IF_UNMODIFIED_SINCE");
if (!in_params.etag.empty()) {
set_header(in_params.etag, extra_headers, "HTTP_IF_MATCH");
}
if (in_params.mod_zone_id != 0) {
set_header(in_params.mod_zone_id, extra_headers, "HTTP_DEST_ZONE_SHORT_ID");
}
if (in_params.mod_pg_ver != 0) {
set_header(in_params.mod_pg_ver, extra_headers, "HTTP_DEST_PG_VER");
}
if (in_params.range_is_set) {
char buf[64];
snprintf(buf, sizeof(buf), "bytes=%lld-%lld", (long long)in_params.range_start, (long long)in_params.range_end);
set_header(buf, extra_headers, "RANGE");
}
int r = (*req)->send_prepare(dpp, key, extra_headers, obj);
if (r < 0) {
goto done_err;
}
if (!send) {
return 0;
}
r = (*req)->send(nullptr);
if (r < 0) {
goto done_err;
}
return 0;
done_err:
delete *req;
*req = nullptr;
return r;
}
int RGWRESTConn::complete_request(RGWRESTStreamRWRequest *req,
string *etag,
real_time *mtime,
uint64_t *psize,
map<string, string> *pattrs,
map<string, string> *pheaders,
optional_yield y)
{
int ret = req->complete_request(y, etag, mtime, psize, pattrs, pheaders);
delete req;
return ret;
}
int RGWRESTConn::get_resource(const DoutPrefixProvider *dpp,
const string& resource,
param_vec_t *extra_params,
map<string, string> *extra_headers,
bufferlist& bl,
bufferlist *send_data,
RGWHTTPManager *mgr,
optional_yield y)
{
string url;
int ret = get_url(url);
if (ret < 0)
return ret;
param_vec_t params;
if (extra_params) {
params.insert(params.end(), extra_params->begin(), extra_params->end());
}
populate_params(params, nullptr, self_zone_group);
RGWStreamIntoBufferlist cb(bl);
RGWRESTStreamReadRequest req(cct, url, &cb, NULL, ¶ms, api_name, host_style);
map<string, string> headers;
if (extra_headers) {
headers.insert(extra_headers->begin(), extra_headers->end());
}
ret = req.send_request(dpp, &key, headers, resource, mgr, send_data);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": send_request() resource=" << resource << " returned ret=" << ret << dendl;
return ret;
}
return req.complete_request(y);
}
int RGWRESTConn::send_resource(const DoutPrefixProvider *dpp, const std::string& method,
const std::string& resource, rgw_http_param_pair *extra_params,
std::map<std::string, std::string> *extra_headers, bufferlist& bl,
bufferlist *send_data, RGWHTTPManager *mgr, optional_yield y)
{
std::string url;
int ret = get_url(url);
if (ret < 0)
return ret;
param_vec_t params;
if (extra_params) {
params = make_param_list(extra_params);
}
populate_params(params, nullptr, self_zone_group);
RGWStreamIntoBufferlist cb(bl);
RGWRESTStreamSendRequest req(cct, method, url, &cb, NULL, ¶ms, api_name, host_style);
std::map<std::string, std::string> headers;
if (extra_headers) {
headers.insert(extra_headers->begin(), extra_headers->end());
}
ret = req.send_request(dpp, &key, headers, resource, mgr, send_data);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": send_request() resource=" << resource << " returned ret=" << ret << dendl;
return ret;
}
ret = req.complete_request(y);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": complete_request() resource=" << resource << " returned ret=" << ret << dendl;
}
return ret;
}
RGWRESTReadResource::RGWRESTReadResource(RGWRESTConn *_conn,
const string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr)
: cct(_conn->get_ctx()), conn(_conn), resource(_resource),
params(make_param_list(pp)), cb(bl), mgr(_mgr),
req(cct, conn->get_url(), &cb, NULL, NULL, _conn->get_api_name())
{
init_common(extra_headers);
}
RGWRESTReadResource::RGWRESTReadResource(RGWRESTConn *_conn,
const string& _resource,
param_vec_t& _params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr)
: cct(_conn->get_ctx()), conn(_conn), resource(_resource), params(_params),
cb(bl), mgr(_mgr), req(cct, conn->get_url(), &cb, NULL, NULL, _conn->get_api_name())
{
init_common(extra_headers);
}
void RGWRESTReadResource::init_common(param_vec_t *extra_headers)
{
conn->populate_params(params, nullptr, conn->get_self_zonegroup());
if (extra_headers) {
headers.insert(extra_headers->begin(), extra_headers->end());
}
req.set_params(¶ms);
}
int RGWRESTReadResource::read(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = req.send_request(dpp, &conn->get_key(), headers, resource, mgr);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": send_request() resource=" << resource << " returned ret=" << ret << dendl;
return ret;
}
return req.complete_request(y);
}
int RGWRESTReadResource::aio_read(const DoutPrefixProvider *dpp)
{
int ret = req.send_request(dpp, &conn->get_key(), headers, resource, mgr);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": send_request() resource=" << resource << " returned ret=" << ret << dendl;
return ret;
}
return 0;
}
RGWRESTSendResource::RGWRESTSendResource(RGWRESTConn *_conn,
const string& _method,
const string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr)
: cct(_conn->get_ctx()), conn(_conn), method(_method), resource(_resource),
params(make_param_list(pp)), cb(bl), mgr(_mgr),
req(cct, method.c_str(), conn->get_url(), &cb, NULL, NULL, _conn->get_api_name(), _conn->get_host_style())
{
init_common(extra_headers);
}
RGWRESTSendResource::RGWRESTSendResource(RGWRESTConn *_conn,
const string& _method,
const string& _resource,
param_vec_t& params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr)
: cct(_conn->get_ctx()), conn(_conn), method(_method), resource(_resource), params(params),
cb(bl), mgr(_mgr), req(cct, method.c_str(), conn->get_url(), &cb, NULL, NULL, _conn->get_api_name(), _conn->get_host_style())
{
init_common(extra_headers);
}
void RGWRESTSendResource::init_common(param_vec_t *extra_headers)
{
conn->populate_params(params, nullptr, conn->get_self_zonegroup());
if (extra_headers) {
headers.insert(extra_headers->begin(), extra_headers->end());
}
req.set_params(¶ms);
}
int RGWRESTSendResource::send(const DoutPrefixProvider *dpp, bufferlist& outbl, optional_yield y)
{
req.set_send_length(outbl.length());
req.set_outbl(outbl);
int ret = req.send_request(dpp, &conn->get_key(), headers, resource, mgr);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": send_request() resource=" << resource << " returned ret=" << ret << dendl;
return ret;
}
return req.complete_request(y);
}
int RGWRESTSendResource::aio_send(const DoutPrefixProvider *dpp, bufferlist& outbl)
{
req.set_send_length(outbl.length());
req.set_outbl(outbl);
int ret = req.send_request(dpp, &conn->get_key(), headers, resource, mgr);
if (ret < 0) {
ldpp_dout(dpp, 5) << __func__ << ": send_request() resource=" << resource << " returned ret=" << ret << dendl;
return ret;
}
return 0;
}
| 16,947 | 31.159393 | 203 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_conn.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_rest_client.h"
#include "common/ceph_json.h"
#include "common/RefCountedObj.h"
#include "include/common_fwd.h"
#include "rgw_sal_fwd.h"
#include <atomic>
class RGWSI_Zone;
template<class T>
inline int parse_decode_json(T& t, bufferlist& bl)
{
JSONParser p;
if (!p.parse(bl.c_str(), bl.length())) {
return -EINVAL;
}
try {
decode_json_obj(t, &p);
} catch (JSONDecoder::err& e) {
return -EINVAL;
}
return 0;
}
struct rgw_http_param_pair {
const char *key;
const char *val;
};
// append a null-terminated rgw_http_param_pair list into a list of string pairs
inline void append_param_list(param_vec_t& params, const rgw_http_param_pair* pp)
{
while (pp && pp->key) {
std::string k = pp->key;
std::string v = (pp->val ? pp->val : "");
params.emplace_back(make_pair(std::move(k), std::move(v)));
++pp;
}
}
// copy a null-terminated rgw_http_param_pair list into a list of std::string pairs
inline param_vec_t make_param_list(const rgw_http_param_pair* pp)
{
param_vec_t params;
append_param_list(params, pp);
return params;
}
inline param_vec_t make_param_list(const std::map<std::string, std::string> *pp)
{
param_vec_t params;
if (!pp) {
return params;
}
for (auto iter : *pp) {
params.emplace_back(make_pair(iter.first, iter.second));
}
return params;
}
class RGWRESTConn
{
CephContext *cct;
std::vector<std::string> endpoints;
RGWAccessKey key;
std::string self_zone_group;
std::string remote_id;
std::optional<std::string> api_name;
HostStyle host_style;
std::atomic<int64_t> counter = { 0 };
public:
RGWRESTConn(CephContext *_cct,
rgw::sal::Driver* driver,
const std::string& _remote_id,
const std::list<std::string>& endpoints,
std::optional<std::string> _api_name,
HostStyle _host_style = PathStyle);
RGWRESTConn(CephContext *_cct,
const std::string& _remote_id,
const std::list<std::string>& endpoints,
RGWAccessKey _cred,
std::string _zone_group,
std::optional<std::string> _api_name,
HostStyle _host_style = PathStyle);
// custom move needed for atomic
RGWRESTConn(RGWRESTConn&& other);
RGWRESTConn& operator=(RGWRESTConn&& other);
virtual ~RGWRESTConn() = default;
int get_url(std::string& endpoint);
std::string get_url();
const std::string& get_self_zonegroup() {
return self_zone_group;
}
const std::string& get_remote_id() {
return remote_id;
}
RGWAccessKey& get_key() {
return key;
}
std::optional<std::string> get_api_name() const {
return api_name;
}
HostStyle get_host_style() {
return host_style;
}
CephContext *get_ctx() {
return cct;
}
size_t get_endpoint_count() const { return endpoints.size(); }
virtual void populate_params(param_vec_t& params, const rgw_user *uid, const std::string& zonegroup);
/* sync request */
int forward(const DoutPrefixProvider *dpp, const rgw_user& uid, req_info& info, obj_version *objv, size_t max_response, bufferlist *inbl, bufferlist *outbl, optional_yield y);
/* sync request */
int forward_iam_request(const DoutPrefixProvider *dpp, const RGWAccessKey& key, req_info& info, obj_version *objv, size_t max_response, bufferlist *inbl, bufferlist *outbl, optional_yield y);
/* async requests */
int put_obj_send_init(const rgw_obj& obj, const rgw_http_param_pair *extra_params, RGWRESTStreamS3PutObj **req);
int put_obj_async_init(const DoutPrefixProvider *dpp, const rgw_user& uid, const rgw_obj& obj,
std::map<std::string, bufferlist>& attrs, RGWRESTStreamS3PutObj **req);
int complete_request(RGWRESTStreamS3PutObj *req, std::string& etag,
ceph::real_time *mtime, optional_yield y);
struct get_obj_params {
rgw_user uid;
req_info *info{nullptr};
const ceph::real_time *mod_ptr{nullptr};
const ceph::real_time *unmod_ptr{nullptr};
bool high_precision_time{true};
std::string etag;
uint32_t mod_zone_id{0};
uint64_t mod_pg_ver{0};
bool prepend_metadata{false};
bool get_op{false};
bool rgwx_stat{false};
bool sync_manifest{false};
bool sync_cloudtiered{false};
bool skip_decrypt{true};
RGWHTTPStreamRWRequest::ReceiveCB *cb{nullptr};
bool range_is_set{false};
uint64_t range_start{0};
uint64_t range_end{0};
rgw_zone_set_entry *dst_zone_trace{nullptr};
};
int get_obj(const DoutPrefixProvider *dpp, const rgw_obj& obj, const get_obj_params& params, bool send, RGWRESTStreamRWRequest **req);
int get_obj(const DoutPrefixProvider *dpp, const rgw_user& uid, req_info *info /* optional */, const rgw_obj& obj,
const ceph::real_time *mod_ptr, const ceph::real_time *unmod_ptr,
uint32_t mod_zone_id, uint64_t mod_pg_ver,
bool prepend_metadata, bool get_op, bool rgwx_stat, bool sync_manifest,
bool skip_decrypt, rgw_zone_set_entry *dst_zone_trace, bool sync_cloudtiered,
bool send, RGWHTTPStreamRWRequest::ReceiveCB *cb, RGWRESTStreamRWRequest **req);
int complete_request(RGWRESTStreamRWRequest *req,
std::string *etag,
ceph::real_time *mtime,
uint64_t *psize,
std::map<std::string, std::string> *pattrs,
std::map<std::string, std::string> *pheaders,
optional_yield y);
int get_resource(const DoutPrefixProvider *dpp,
const std::string& resource,
param_vec_t *extra_params,
std::map<std::string, std::string>* extra_headers,
bufferlist& bl,
bufferlist *send_data,
RGWHTTPManager *mgr,
optional_yield y);
int send_resource(const DoutPrefixProvider *dpp,
const std::string& method,
const std::string& resource,
rgw_http_param_pair *extra_params,
std::map<std::string, std::string>* extra_headers,
bufferlist& bl,
bufferlist *send_data,
RGWHTTPManager *mgr,
optional_yield y);
template <class T>
int get_json_resource(const DoutPrefixProvider *dpp, const std::string& resource, param_vec_t *params,
bufferlist *in_data, optional_yield y, T& t);
template <class T>
int get_json_resource(const DoutPrefixProvider *dpp, const std::string& resource, param_vec_t *params,
optional_yield y, T& t);
template <class T>
int get_json_resource(const DoutPrefixProvider *dpp, const std::string& resource, const rgw_http_param_pair *pp,
optional_yield y, T& t);
private:
void populate_zonegroup(param_vec_t& params, const std::string& zonegroup) {
if (!zonegroup.empty()) {
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "zonegroup", zonegroup));
}
}
void populate_uid(param_vec_t& params, const rgw_user *uid) {
if (uid) {
std::string uid_str = uid->to_str();
if (!uid->empty()){
params.push_back(param_pair_t(RGW_SYS_PARAM_PREFIX "uid", uid_str));
}
}
}
};
class S3RESTConn : public RGWRESTConn {
public:
S3RESTConn(CephContext *_cct, rgw::sal::Driver* driver, const std::string& _remote_id, const std::list<std::string>& endpoints, std::optional<std::string> _api_name, HostStyle _host_style = PathStyle) :
RGWRESTConn(_cct, driver, _remote_id, endpoints, _api_name, _host_style) {}
S3RESTConn(CephContext *_cct, const std::string& _remote_id, const std::list<std::string>& endpoints, RGWAccessKey _cred, std::string _zone_group, std::optional<std::string> _api_name, HostStyle _host_style = PathStyle):
RGWRESTConn(_cct, _remote_id, endpoints, _cred, _zone_group, _api_name, _host_style) {}
~S3RESTConn() override = default;
void populate_params(param_vec_t& params, const rgw_user *uid, const std::string& zonegroup) override {
// do not populate any params in S3 REST Connection.
return;
}
};
template<class T>
int RGWRESTConn::get_json_resource(const DoutPrefixProvider *dpp, const std::string& resource, param_vec_t *params,
bufferlist *in_data, optional_yield y, T& t)
{
bufferlist bl;
int ret = get_resource(dpp, resource, params, nullptr, bl, in_data, nullptr, y);
if (ret < 0) {
return ret;
}
ret = parse_decode_json(t, bl);
if (ret < 0) {
return ret;
}
return 0;
}
template<class T>
int RGWRESTConn::get_json_resource(const DoutPrefixProvider *dpp, const std::string& resource, param_vec_t *params,
optional_yield y, T& t)
{
return get_json_resource(dpp, resource, params, nullptr, y, t);
}
template<class T>
int RGWRESTConn::get_json_resource(const DoutPrefixProvider *dpp, const std::string& resource, const rgw_http_param_pair *pp,
optional_yield y, T& t)
{
param_vec_t params = make_param_list(pp);
return get_json_resource(dpp, resource, ¶ms, y, t);
}
class RGWStreamIntoBufferlist : public RGWHTTPStreamRWRequest::ReceiveCB {
bufferlist& bl;
public:
explicit RGWStreamIntoBufferlist(bufferlist& _bl) : bl(_bl) {}
int handle_data(bufferlist& inbl, bool *pause) override {
bl.claim_append(inbl);
return inbl.length();
}
};
class RGWRESTReadResource : public RefCountedObject, public RGWIOProvider {
CephContext *cct;
RGWRESTConn *conn;
std::string resource;
param_vec_t params;
std::map<std::string, std::string> headers;
bufferlist bl;
RGWStreamIntoBufferlist cb;
RGWHTTPManager *mgr;
RGWRESTStreamReadRequest req;
void init_common(param_vec_t *extra_headers);
public:
RGWRESTReadResource(RGWRESTConn *_conn,
const std::string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr);
RGWRESTReadResource(RGWRESTConn *_conn,
const std::string& _resource,
param_vec_t& _params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr);
~RGWRESTReadResource() = default;
rgw_io_id get_io_id(int io_type) {
return req.get_io_id(io_type);
}
void set_io_user_info(void *user_info) override {
req.set_io_user_info(user_info);
}
void *get_io_user_info() override {
return req.get_io_user_info();
}
template <class T>
int decode_resource(T *dest);
int read(const DoutPrefixProvider *dpp, optional_yield y);
int aio_read(const DoutPrefixProvider *dpp);
std::string to_str() {
return req.to_str();
}
int get_http_status() {
return req.get_http_status();
}
int wait(bufferlist *pbl, optional_yield y) {
int ret = req.wait(y);
if (ret < 0) {
return ret;
}
if (req.get_status() < 0) {
return req.get_status();
}
*pbl = bl;
return 0;
}
template <class T>
int wait(T *dest, optional_yield y);
template <class T>
int fetch(const DoutPrefixProvider *dpp, T *dest, optional_yield y);
};
template <class T>
int RGWRESTReadResource::decode_resource(T *dest)
{
int ret = req.get_status();
if (ret < 0) {
return ret;
}
ret = parse_decode_json(*dest, bl);
if (ret < 0) {
return ret;
}
return 0;
}
template <class T>
int RGWRESTReadResource::fetch(const DoutPrefixProvider *dpp, T *dest, optional_yield y)
{
int ret = read(dpp, y);
if (ret < 0) {
return ret;
}
ret = decode_resource(dest);
if (ret < 0) {
return ret;
}
return 0;
}
template <class T>
int RGWRESTReadResource::wait(T *dest, optional_yield y)
{
int ret = req.wait(y);
if (ret < 0) {
return ret;
}
ret = decode_resource(dest);
if (ret < 0) {
return ret;
}
return 0;
}
class RGWRESTSendResource : public RefCountedObject, public RGWIOProvider {
CephContext *cct;
RGWRESTConn *conn;
std::string method;
std::string resource;
param_vec_t params;
std::map<std::string, std::string> headers;
bufferlist bl;
RGWStreamIntoBufferlist cb;
RGWHTTPManager *mgr;
RGWRESTStreamRWRequest req;
void init_common(param_vec_t *extra_headers);
public:
RGWRESTSendResource(RGWRESTConn *_conn,
const std::string& _method,
const std::string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr);
RGWRESTSendResource(RGWRESTConn *_conn,
const std::string& _method,
const std::string& _resource,
param_vec_t& params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr);
~RGWRESTSendResource() = default;
rgw_io_id get_io_id(int io_type) {
return req.get_io_id(io_type);
}
void set_io_user_info(void *user_info) override {
req.set_io_user_info(user_info);
}
void *get_io_user_info() override {
return req.get_io_user_info();
}
int send(const DoutPrefixProvider *dpp, bufferlist& bl, optional_yield y);
int aio_send(const DoutPrefixProvider *dpp, bufferlist& bl);
std::string to_str() {
return req.to_str();
}
int get_http_status() {
return req.get_http_status();
}
template <class E = int>
int wait(bufferlist *pbl, optional_yield y, E *err_result = nullptr) {
int ret = req.wait(y);
*pbl = bl;
if (ret < 0 && err_result ) {
ret = parse_decode_json(*err_result, bl);
}
return req.get_status();
}
template <class T, class E = int>
int wait(T *dest, optional_yield y, E *err_result = nullptr);
};
template <class T, class E>
int RGWRESTSendResource::wait(T *dest, optional_yield y, E *err_result)
{
int ret = req.wait(y);
if (ret >= 0) {
ret = req.get_status();
}
if (ret < 0 && err_result) {
ret = parse_decode_json(*err_result, bl);
}
if (ret < 0) {
return ret;
}
ret = parse_decode_json(*dest, bl);
if (ret < 0) {
return ret;
}
return 0;
}
class RGWRESTPostResource : public RGWRESTSendResource {
public:
RGWRESTPostResource(RGWRESTConn *_conn,
const std::string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr) : RGWRESTSendResource(_conn, "POST", _resource,
pp, extra_headers, _mgr) {}
RGWRESTPostResource(RGWRESTConn *_conn,
const std::string& _resource,
param_vec_t& params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr) : RGWRESTSendResource(_conn, "POST", _resource,
params, extra_headers, _mgr) {}
};
class RGWRESTPutResource : public RGWRESTSendResource {
public:
RGWRESTPutResource(RGWRESTConn *_conn,
const std::string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr) : RGWRESTSendResource(_conn, "PUT", _resource,
pp, extra_headers, _mgr) {}
RGWRESTPutResource(RGWRESTConn *_conn,
const std::string& _resource,
param_vec_t& params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr) : RGWRESTSendResource(_conn, "PUT", _resource,
params, extra_headers, _mgr) {}
};
class RGWRESTDeleteResource : public RGWRESTSendResource {
public:
RGWRESTDeleteResource(RGWRESTConn *_conn,
const std::string& _resource,
const rgw_http_param_pair *pp,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr) : RGWRESTSendResource(_conn, "DELETE", _resource,
pp, extra_headers, _mgr) {}
RGWRESTDeleteResource(RGWRESTConn *_conn,
const std::string& _resource,
param_vec_t& params,
param_vec_t *extra_headers,
RGWHTTPManager *_mgr) : RGWRESTSendResource(_conn, "DELETE", _resource,
params, extra_headers, _mgr) {}
};
| 16,272 | 28.163082 | 222 |
h
|
null |
ceph-main/src/rgw/rgw_rest_iam.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <boost/tokenizer.hpp>
#include "rgw_auth_s3.h"
#include "rgw_rest_iam.h"
#include "rgw_rest_role.h"
#include "rgw_rest_user_policy.h"
#include "rgw_rest_oidc_provider.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
using op_generator = RGWOp*(*)(const bufferlist&);
static const std::unordered_map<std::string_view, op_generator> op_generators = {
{"CreateRole", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWCreateRole(bl_post_body);}},
{"DeleteRole", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWDeleteRole(bl_post_body);}},
{"GetRole", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWGetRole;}},
{"UpdateAssumeRolePolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWModifyRoleTrustPolicy(bl_post_body);}},
{"ListRoles", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWListRoles;}},
{"PutRolePolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWPutRolePolicy(bl_post_body);}},
{"GetRolePolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWGetRolePolicy;}},
{"ListRolePolicies", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWListRolePolicies;}},
{"DeleteRolePolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWDeleteRolePolicy(bl_post_body);}},
{"PutUserPolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWPutUserPolicy;}},
{"GetUserPolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWGetUserPolicy;}},
{"ListUserPolicies", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWListUserPolicies;}},
{"DeleteUserPolicy", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWDeleteUserPolicy;}},
{"CreateOpenIDConnectProvider", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWCreateOIDCProvider;}},
{"ListOpenIDConnectProviders", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWListOIDCProviders;}},
{"GetOpenIDConnectProvider", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWGetOIDCProvider;}},
{"DeleteOpenIDConnectProvider", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWDeleteOIDCProvider;}},
{"TagRole", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWTagRole(bl_post_body);}},
{"ListRoleTags", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWListRoleTags;}},
{"UntagRole", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWUntagRole(bl_post_body);}},
{"UpdateRole", [](const bufferlist& bl_post_body) -> RGWOp* {return new RGWUpdateRole(bl_post_body);}}
};
bool RGWHandler_REST_IAM::action_exists(const req_state* s)
{
if (s->info.args.exists("Action")) {
const std::string action_name = s->info.args.get("Action");
return op_generators.contains(action_name);
}
return false;
}
RGWOp *RGWHandler_REST_IAM::op_post()
{
if (s->info.args.exists("Action")) {
const std::string action_name = s->info.args.get("Action");
const auto action_it = op_generators.find(action_name);
if (action_it != op_generators.end()) {
return action_it->second(bl_post_body);
}
ldpp_dout(s, 10) << "unknown action '" << action_name << "' for IAM handler" << dendl;
} else {
ldpp_dout(s, 10) << "missing action argument in IAM handler" << dendl;
}
return nullptr;
}
int RGWHandler_REST_IAM::init(rgw::sal::Driver* driver,
req_state *s,
rgw::io::BasicClient *cio)
{
s->dialect = "iam";
s->prot_flags = RGW_REST_IAM;
return RGWHandler_REST::init(driver, s, cio);
}
int RGWHandler_REST_IAM::authorize(const DoutPrefixProvider* dpp, optional_yield y)
{
return RGW_Auth_S3::authorize(dpp, driver, auth_registry, s, y);
}
RGWHandler_REST*
RGWRESTMgr_IAM::get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix)
{
bufferlist bl;
return new RGWHandler_REST_IAM(auth_registry, bl);
}
| 4,169 | 44.824176 | 128 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_iam.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_auth.h"
#include "rgw_auth_filters.h"
#include "rgw_rest.h"
class RGWHandler_REST_IAM : public RGWHandler_REST {
const rgw::auth::StrategyRegistry& auth_registry;
bufferlist bl_post_body;
RGWOp *op_post() override;
public:
static bool action_exists(const req_state* s);
RGWHandler_REST_IAM(const rgw::auth::StrategyRegistry& auth_registry,
bufferlist& bl_post_body)
: RGWHandler_REST(),
auth_registry(auth_registry),
bl_post_body(bl_post_body) {}
~RGWHandler_REST_IAM() override = default;
int init(rgw::sal::Driver* driver,
req_state *s,
rgw::io::BasicClient *cio) override;
int authorize(const DoutPrefixProvider* dpp, optional_yield y) override;
int postauth_init(optional_yield y) override { return 0; }
};
class RGWRESTMgr_IAM : public RGWRESTMgr {
public:
RGWRESTMgr_IAM() = default;
~RGWRESTMgr_IAM() override = default;
RGWRESTMgr *get_resource_mgr(req_state* const s,
const std::string& uri,
std::string* const out_uri) override {
return this;
}
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state*,
const rgw::auth::StrategyRegistry&,
const std::string&) override;
};
| 1,445 | 28.510204 | 74 |
h
|
null |
ceph-main/src/rgw/rgw_rest_info.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_op.h"
#include "rgw_rest_info.h"
#include "rgw_sal.h"
#define dout_subsys ceph_subsys_rgw
class RGWOp_Info_Get : public RGWRESTOp {
public:
RGWOp_Info_Get() {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("info", RGW_CAP_READ);
}
void execute(optional_yield y) override;
const char* name() const override { return "get_info"; }
};
void RGWOp_Info_Get::execute(optional_yield y) {
Formatter *formatter = flusher.get_formatter();
flusher.start(0);
/* extensible array of general info sections, currently only
* storage backend is defined:
* {"info":{"storage_backends":[{"name":"rados","cluster_id":"75d1938b-2949-4933-8386-fb2d1449ff03"}]}}
*/
formatter->open_object_section("dummy");
formatter->open_object_section("info");
formatter->open_array_section("storage_backends");
// for now, just return the backend that is accessible
formatter->open_object_section("dummy");
formatter->dump_string("name", driver->get_name());
formatter->dump_string("cluster_id", driver->get_cluster_id(this, y));
formatter->close_section();
formatter->close_section();
formatter->close_section();
formatter->close_section();
flusher.flush();
} /* RGWOp_Info_Get::execute */
RGWOp *RGWHandler_Info::op_get()
{
return new RGWOp_Info_Get;
}
| 1,431 | 27.64 | 105 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_info.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_rest.h"
#include "rgw_rest_s3.h"
class RGWHandler_Info : public RGWHandler_Auth_S3 {
protected:
RGWOp *op_get() override;
public:
using RGWHandler_Auth_S3::RGWHandler_Auth_S3;
~RGWHandler_Info() override = default;
int read_permissions(RGWOp*, optional_yield) override {
return 0;
}
};
class RGWRESTMgr_Info : public RGWRESTMgr {
public:
RGWRESTMgr_Info() = default;
~RGWRESTMgr_Info() override = default;
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state*,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string&) override {
return new RGWHandler_Info(auth_registry);
}
};
| 839 | 23.705882 | 80 |
h
|
null |
ceph-main/src/rgw/rgw_rest_metadata.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "include/page.h"
#include "rgw_rest.h"
#include "rgw_op.h"
#include "rgw_rest_s3.h"
#include "rgw_rest_metadata.h"
#include "rgw_client_io.h"
#include "rgw_mdlog_types.h"
#include "rgw_sal_rados.h"
#include "common/errno.h"
#include "common/strtol.h"
#include "rgw/rgw_b64.h"
#include "include/ceph_assert.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
static inline void frame_metadata_key(req_state *s, string& out) {
bool exists;
string key = s->info.args.get("key", &exists);
string section;
if (!s->init_state.url_bucket.empty()) {
section = s->init_state.url_bucket;
} else {
section = key;
key.clear();
}
out = section;
if (!key.empty()) {
out += string(":") + key;
}
}
void RGWOp_Metadata_Get::execute(optional_yield y) {
string metadata_key;
frame_metadata_key(s, metadata_key);
auto meta_mgr = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr;
/* Get keys */
op_ret = meta_mgr->get(metadata_key, s->formatter, s->yield, s);
if (op_ret < 0) {
ldpp_dout(s, 5) << "ERROR: can't get key: " << cpp_strerror(op_ret) << dendl;
return;
}
op_ret = 0;
}
void RGWOp_Metadata_Get_Myself::execute(optional_yield y) {
string owner_id;
owner_id = s->owner.get_id().to_str();
s->info.args.append("key", owner_id);
return RGWOp_Metadata_Get::execute(y);
}
void RGWOp_Metadata_List::execute(optional_yield y) {
string marker;
ldpp_dout(this, 16) << __func__
<< " raw marker " << s->info.args.get("marker")
<< dendl;
try {
marker = s->info.args.get("marker");
if (!marker.empty()) {
marker = rgw::from_base64(marker);
}
ldpp_dout(this, 16) << __func__
<< " marker " << marker << dendl;
} catch (...) {
marker = std::string("");
}
bool max_entries_specified;
string max_entries_str =
s->info.args.get("max-entries", &max_entries_specified);
bool extended_response = (max_entries_specified); /* for backward compatibility, if max-entries is not specified
we will send the old response format */
uint64_t max_entries = 0;
if (max_entries_specified) {
string err;
max_entries = (unsigned)strict_strtol(max_entries_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(this, 5) << "Error parsing max-entries " << max_entries_str << dendl;
op_ret = -EINVAL;
return;
}
}
string metadata_key;
frame_metadata_key(s, metadata_key);
/* List keys */
void *handle;
int max = 1000;
/* example markers:
marker = "3:b55a9110:root::bu_9:head";
marker = "3:b9a8b2a6:root::sorry_janefonda_890:head";
marker = "3:bf885d8f:root::sorry_janefonda_665:head";
*/
op_ret = driver->meta_list_keys_init(this, metadata_key, marker, &handle);
if (op_ret < 0) {
ldpp_dout(this, 5) << "ERROR: can't get key: " << cpp_strerror(op_ret) << dendl;
return;
}
bool truncated;
uint64_t count = 0;
if (extended_response) {
s->formatter->open_object_section("result");
}
s->formatter->open_array_section("keys");
uint64_t left;
do {
list<string> keys;
left = (max_entries_specified ? max_entries - count : max);
op_ret = driver->meta_list_keys_next(this, handle, left, keys, &truncated);
if (op_ret < 0) {
ldpp_dout(this, 5) << "ERROR: lists_keys_next(): " << cpp_strerror(op_ret)
<< dendl;
return;
}
for (list<string>::iterator iter = keys.begin(); iter != keys.end();
++iter) {
s->formatter->dump_string("key", *iter);
++count;
}
} while (truncated && left > 0);
s->formatter->close_section();
if (extended_response) {
encode_json("truncated", truncated, s->formatter);
encode_json("count", count, s->formatter);
if (truncated) {
string esc_marker =
rgw::to_base64(driver->meta_get_marker(handle));
encode_json("marker", esc_marker, s->formatter);
}
s->formatter->close_section();
}
driver->meta_list_keys_complete(handle);
op_ret = 0;
}
int RGWOp_Metadata_Put::get_data(bufferlist& bl) {
size_t cl = 0;
char *data;
int read_len;
if (s->length)
cl = atoll(s->length);
if (cl) {
data = (char *)malloc(cl + 1);
if (!data) {
return -ENOMEM;
}
read_len = recv_body(s, data, cl);
if (cl != (size_t)read_len) {
ldpp_dout(this, 10) << "recv_body incomplete" << dendl;
}
if (read_len < 0) {
free(data);
return read_len;
}
bl.append(data, read_len);
} else {
int chunk_size = CEPH_PAGE_SIZE;
const char *enc = s->info.env->get("HTTP_TRANSFER_ENCODING");
if (!enc || strcmp(enc, "chunked")) {
return -ERR_LENGTH_REQUIRED;
}
data = (char *)malloc(chunk_size);
if (!data) {
return -ENOMEM;
}
do {
read_len = recv_body(s, data, chunk_size);
if (read_len < 0) {
free(data);
return read_len;
}
bl.append(data, read_len);
} while (read_len == chunk_size);
}
free(data);
return 0;
}
static bool string_to_sync_type(const string& sync_string,
RGWMDLogSyncType& type) {
if (sync_string.compare("update-by-version") == 0)
type = APPLY_UPDATES;
else if (sync_string.compare("update-by-timestamp") == 0)
type = APPLY_NEWER;
else if (sync_string.compare("always") == 0)
type = APPLY_ALWAYS;
else
return false;
return true;
}
void RGWOp_Metadata_Put::execute(optional_yield y) {
bufferlist bl;
string metadata_key;
op_ret = get_data(bl);
if (op_ret < 0) {
return;
}
op_ret = do_aws4_auth_completion();
if (op_ret < 0) {
return;
}
frame_metadata_key(s, metadata_key);
RGWMDLogSyncType sync_type = RGWMDLogSyncType::APPLY_ALWAYS;
bool mode_exists = false;
string mode_string = s->info.args.get("update-type", &mode_exists);
if (mode_exists) {
bool parsed = string_to_sync_type(mode_string,
sync_type);
if (!parsed) {
op_ret = -EINVAL;
return;
}
}
op_ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->put(metadata_key, bl, s->yield, s, sync_type,
false, &ondisk_version);
if (op_ret < 0) {
ldpp_dout(s, 5) << "ERROR: can't put key: " << cpp_strerror(op_ret) << dendl;
return;
}
// translate internal codes into return header
if (op_ret == STATUS_NO_APPLY)
update_status = "skipped";
else if (op_ret == STATUS_APPLIED)
update_status = "applied";
}
void RGWOp_Metadata_Put::send_response() {
int op_return_code = op_ret;
if ((op_ret == STATUS_NO_APPLY) || (op_ret == STATUS_APPLIED))
op_return_code = STATUS_NO_CONTENT;
set_req_state_err(s, op_return_code);
dump_errno(s);
stringstream ver_stream;
ver_stream << "ver:" << ondisk_version.ver
<<",tag:" << ondisk_version.tag;
dump_header_if_nonempty(s, "RGWX_UPDATE_STATUS", update_status);
dump_header_if_nonempty(s, "RGWX_UPDATE_VERSION", ver_stream.str());
end_header(s);
}
void RGWOp_Metadata_Delete::execute(optional_yield y) {
string metadata_key;
frame_metadata_key(s, metadata_key);
op_ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->remove(metadata_key, s->yield, s);
if (op_ret < 0) {
ldpp_dout(s, 5) << "ERROR: can't remove key: " << cpp_strerror(op_ret) << dendl;
return;
}
op_ret = 0;
}
RGWOp *RGWHandler_Metadata::op_get() {
if (s->info.args.exists("myself"))
return new RGWOp_Metadata_Get_Myself;
if (s->info.args.exists("key"))
return new RGWOp_Metadata_Get;
else
return new RGWOp_Metadata_List;
}
RGWOp *RGWHandler_Metadata::op_put() {
return new RGWOp_Metadata_Put;
}
RGWOp *RGWHandler_Metadata::op_delete() {
return new RGWOp_Metadata_Delete;
}
| 8,238 | 24.586957 | 117 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_metadata.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 eNovance SAS <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "rgw/rgw_rest.h"
#include "rgw/rgw_auth_s3.h"
class RGWOp_Metadata_List : public RGWRESTOp {
public:
RGWOp_Metadata_List() {}
~RGWOp_Metadata_List() override {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("metadata", RGW_CAP_READ);
}
void execute(optional_yield y) override;
const char* name() const override { return "list_metadata"; }
};
class RGWOp_Metadata_Get : public RGWRESTOp {
public:
RGWOp_Metadata_Get() {}
~RGWOp_Metadata_Get() override {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("metadata", RGW_CAP_READ);
}
void execute(optional_yield y) override;
const char* name() const override { return "get_metadata"; }
};
class RGWOp_Metadata_Get_Myself : public RGWOp_Metadata_Get {
public:
RGWOp_Metadata_Get_Myself() {}
~RGWOp_Metadata_Get_Myself() override {}
void execute(optional_yield y) override;
};
class RGWOp_Metadata_Put : public RGWRESTOp {
int get_data(bufferlist& bl);
std::string update_status;
obj_version ondisk_version;
public:
RGWOp_Metadata_Put() {}
~RGWOp_Metadata_Put() override {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("metadata", RGW_CAP_WRITE);
}
void execute(optional_yield y) override;
void send_response() override;
const char* name() const override { return "set_metadata"; }
RGWOpType get_type() override { return RGW_OP_ADMIN_SET_METADATA; }
};
class RGWOp_Metadata_Delete : public RGWRESTOp {
public:
RGWOp_Metadata_Delete() {}
~RGWOp_Metadata_Delete() override {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("metadata", RGW_CAP_WRITE);
}
void execute(optional_yield y) override;
const char* name() const override { return "remove_metadata"; }
};
class RGWHandler_Metadata : public RGWHandler_Auth_S3 {
protected:
RGWOp *op_get() override;
RGWOp *op_put() override;
RGWOp *op_delete() override;
int read_permissions(RGWOp*, optional_yield y) override {
return 0;
}
public:
using RGWHandler_Auth_S3::RGWHandler_Auth_S3;
~RGWHandler_Metadata() override = default;
};
class RGWRESTMgr_Metadata : public RGWRESTMgr {
public:
RGWRESTMgr_Metadata() = default;
~RGWRESTMgr_Metadata() override = default;
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix) override {
return new RGWHandler_Metadata(auth_registry);
}
};
| 3,039 | 27.148148 | 80 |
h
|
null |
ceph-main/src/rgw/rgw_rest_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 "common/errno.h"
#include "common/Formatter.h"
#include "common/ceph_json.h"
#include "include/types.h"
#include "rgw_string.h"
#include "rgw_common.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_role.h"
#include "rgw_rest_oidc_provider.h"
#include "rgw_oidc_provider.h"
#include "rgw_sal.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
int RGWRestOIDCProvider::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
provider_arn = s->info.args.get("OpenIDConnectProviderArn");
if (provider_arn.empty()) {
ldpp_dout(this, 20) << "ERROR: Provider ARN is empty"<< dendl;
return -EINVAL;
}
auto ret = check_caps(s->user->get_caps());
if (ret == 0) {
return ret;
}
uint64_t op = get_op();
auto rgw_arn = rgw::ARN::parse(provider_arn, true);
if (rgw_arn) {
if (!verify_user_permission(this, s, *rgw_arn, op)) {
return -EACCES;
}
} else {
return -EACCES;
}
return 0;
}
void RGWRestOIDCProvider::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this);
}
int RGWRestOIDCProviderRead::check_caps(const RGWUserCaps& caps)
{
return caps.check_cap("oidc-provider", RGW_CAP_READ);
}
int RGWRestOIDCProviderWrite::check_caps(const RGWUserCaps& caps)
{
return caps.check_cap("oidc-provider", RGW_CAP_WRITE);
}
int RGWCreateOIDCProvider::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
auto ret = check_caps(s->user->get_caps());
if (ret == 0) {
return ret;
}
string idp_url = url_remove_prefix(provider_url);
if (!verify_user_permission(this,
s,
rgw::ARN(idp_url,
"oidc-provider",
s->user->get_tenant(), true),
get_op())) {
return -EACCES;
}
return 0;
}
int RGWCreateOIDCProvider::get_params()
{
provider_url = s->info.args.get("Url");
auto val_map = s->info.args.get_params();
for (auto& it : val_map) {
if (it.first.find("ClientIDList.member.") != string::npos) {
client_ids.emplace_back(it.second);
}
if (it.first.find("ThumbprintList.member.") != string::npos) {
thumbprints.emplace_back(it.second);
}
}
if (provider_url.empty() || thumbprints.empty()) {
ldpp_dout(this, 20) << "ERROR: one of url or thumbprints is empty" << dendl;
return -EINVAL;
}
return 0;
}
void RGWCreateOIDCProvider::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::RGWOIDCProvider> provider = driver->get_oidc_provider();
provider->set_url(provider_url);
provider->set_tenant(s->user->get_tenant());
provider->set_client_ids(client_ids);
provider->set_thumbprints(thumbprints);
op_ret = provider->create(s, true, y);
if (op_ret == 0) {
s->formatter->open_object_section("CreateOpenIDConnectProviderResponse");
s->formatter->open_object_section("CreateOpenIDConnectProviderResult");
provider->dump(s->formatter);
s->formatter->close_section();
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
void RGWDeleteOIDCProvider::execute(optional_yield y)
{
std::unique_ptr<rgw::sal::RGWOIDCProvider> provider = driver->get_oidc_provider();
provider->set_arn(provider_arn);
provider->set_tenant(s->user->get_tenant());
op_ret = provider->delete_obj(s, y);
if (op_ret < 0 && op_ret != -ENOENT && op_ret != -EINVAL) {
op_ret = ERR_INTERNAL_ERROR;
}
if (op_ret == 0) {
s->formatter->open_object_section("DeleteOpenIDConnectProviderResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
void RGWGetOIDCProvider::execute(optional_yield y)
{
std::unique_ptr<rgw::sal::RGWOIDCProvider> provider = driver->get_oidc_provider();
provider->set_arn(provider_arn);
provider->set_tenant(s->user->get_tenant());
op_ret = provider->get(s, y);
if (op_ret < 0 && op_ret != -ENOENT && op_ret != -EINVAL) {
op_ret = ERR_INTERNAL_ERROR;
}
if (op_ret == 0) {
s->formatter->open_object_section("GetOpenIDConnectProviderResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("GetOpenIDConnectProviderResult");
provider->dump_all(s->formatter);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWListOIDCProviders::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if (int ret = check_caps(s->user->get_caps()); ret == 0) {
return ret;
}
if (!verify_user_permission(this,
s,
rgw::ARN(),
get_op())) {
return -EACCES;
}
return 0;
}
void RGWListOIDCProviders::execute(optional_yield y)
{
vector<std::unique_ptr<rgw::sal::RGWOIDCProvider>> result;
op_ret = driver->get_oidc_providers(s, s->user->get_tenant(), result, y);
if (op_ret == 0) {
s->formatter->open_array_section("ListOpenIDConnectProvidersResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("ListOpenIDConnectProvidersResult");
s->formatter->open_array_section("OpenIDConnectProviderList");
for (const auto& it : result) {
s->formatter->open_object_section("member");
auto& arn = it->get_arn();
ldpp_dout(s, 0) << "ARN: " << arn << dendl;
s->formatter->dump_string("Arn", arn);
s->formatter->close_section();
}
s->formatter->close_section();
s->formatter->close_section();
s->formatter->close_section();
}
}
| 6,376 | 26.252137 | 84 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_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 "rgw_rest.h"
#include "rgw_oidc_provider.h"
class RGWRestOIDCProvider : public RGWRESTOp {
protected:
std::vector<std::string> client_ids;
std::vector<std::string> thumbprints;
std::string provider_url; //'iss' field in JWT
std::string provider_arn;
public:
int verify_permission(optional_yield y) override;
void send_response() override;
virtual uint64_t get_op() = 0;
};
class RGWRestOIDCProviderRead : public RGWRestOIDCProvider {
public:
RGWRestOIDCProviderRead() = default;
int check_caps(const RGWUserCaps& caps) override;
};
class RGWRestOIDCProviderWrite : public RGWRestOIDCProvider {
public:
RGWRestOIDCProviderWrite() = default;
int check_caps(const RGWUserCaps& caps) override;
};
class RGWCreateOIDCProvider : public RGWRestOIDCProviderWrite {
public:
RGWCreateOIDCProvider() = default;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "create_oidc_provider"; }
RGWOpType get_type() override { return RGW_OP_CREATE_OIDC_PROVIDER; }
uint64_t get_op() override { return rgw::IAM::iamCreateOIDCProvider; }
};
class RGWDeleteOIDCProvider : public RGWRestOIDCProviderWrite {
public:
RGWDeleteOIDCProvider() = default;
void execute(optional_yield y) override;
const char* name() const override { return "delete_oidc_provider"; }
RGWOpType get_type() override { return RGW_OP_DELETE_OIDC_PROVIDER; }
uint64_t get_op() override { return rgw::IAM::iamDeleteOIDCProvider; }
};
class RGWGetOIDCProvider : public RGWRestOIDCProviderRead {
public:
RGWGetOIDCProvider() = default;
void execute(optional_yield y) override;
const char* name() const override { return "get_oidc_provider"; }
RGWOpType get_type() override { return RGW_OP_GET_OIDC_PROVIDER; }
uint64_t get_op() override { return rgw::IAM::iamGetOIDCProvider; }
};
class RGWListOIDCProviders : public RGWRestOIDCProviderRead {
public:
RGWListOIDCProviders() = default;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "list_oidc_providers"; }
RGWOpType get_type() override { return RGW_OP_LIST_OIDC_PROVIDERS; }
uint64_t get_op() override { return rgw::IAM::iamListOIDCProviders; }
};
| 2,457 | 33.138889 | 72 |
h
|
null |
ceph-main/src/rgw/rgw_rest_pubsub.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <optional>
#include "rgw_rest_pubsub.h"
#include "rgw_pubsub_push.h"
#include "rgw_pubsub.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_rest_s3.h"
#include "rgw_arn.h"
#include "rgw_auth_s3.h"
#include "rgw_notify.h"
#include "services/svc_zone.h"
#include "common/dout.h"
#include "rgw_url.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
static const char* AWS_SNS_NS("https://sns.amazonaws.com/doc/2010-03-31/");
bool verify_transport_security(CephContext *cct, const RGWEnv& env) {
const auto is_secure = rgw_transport_is_secure(cct, env);
if (!is_secure && g_conf().get_val<bool>("rgw_allow_notification_secrets_in_cleartext")) {
ldout(cct, 0) << "WARNING: bypassing endpoint validation, allows sending secrets over insecure transport" << dendl;
return true;
}
return is_secure;
}
// make sure that endpoint is a valid URL
// make sure that if user/password are passed inside URL, it is over secure connection
// update rgw_pubsub_dest to indicate that a password is stored in the URL
bool validate_and_update_endpoint_secret(rgw_pubsub_dest& dest, CephContext *cct, const RGWEnv& env) {
if (dest.push_endpoint.empty()) {
return true;
}
std::string user;
std::string password;
if (!rgw::parse_url_userinfo(dest.push_endpoint, user, password)) {
ldout(cct, 1) << "endpoint validation error: malformed endpoint URL:" << dest.push_endpoint << dendl;
return false;
}
// this should be verified inside parse_url()
ceph_assert(user.empty() == password.empty());
if (!user.empty()) {
dest.stored_secret = true;
if (!verify_transport_security(cct, env)) {
ldout(cct, 1) << "endpoint validation error: sending secrets over insecure transport" << dendl;
return false;
}
}
return true;
}
bool topic_has_endpoint_secret(const rgw_pubsub_topic& topic) {
return topic.dest.stored_secret;
}
bool topics_has_endpoint_secret(const rgw_pubsub_topics& topics) {
for (const auto& topic : topics.topics) {
if (topic_has_endpoint_secret(topic.second)) return true;
}
return false;
}
// command (AWS compliant):
// POST
// Action=CreateTopic&Name=<topic-name>[&OpaqueData=data][&push-endpoint=<endpoint>[&persistent][&<arg1>=<value1>]]
class RGWPSCreateTopicOp : public RGWOp {
private:
std::string topic_name;
rgw_pubsub_dest dest;
std::string topic_arn;
std::string opaque_data;
int get_params() {
topic_name = s->info.args.get("Name");
if (topic_name.empty()) {
ldpp_dout(this, 1) << "CreateTopic Action 'Name' argument is missing" << dendl;
return -EINVAL;
}
opaque_data = s->info.args.get("OpaqueData");
dest.push_endpoint = s->info.args.get("push-endpoint");
s->info.args.get_bool("persistent", &dest.persistent, false);
if (!validate_and_update_endpoint_secret(dest, s->cct, *(s->info.env))) {
return -EINVAL;
}
for (const auto& param : s->info.args.get_params()) {
if (param.first == "Action" || param.first == "Name" || param.first == "PayloadHash") {
continue;
}
dest.push_endpoint_args.append(param.first+"="+param.second+"&");
}
if (!dest.push_endpoint_args.empty()) {
// remove last separator
dest.push_endpoint_args.pop_back();
}
if (!dest.push_endpoint.empty() && dest.persistent) {
const auto ret = rgw::notify::add_persistent_topic(topic_name, s->yield);
if (ret < 0) {
ldpp_dout(this, 1) << "CreateTopic Action failed to create queue for persistent topics. error:" << ret << dendl;
return ret;
}
}
// dest object only stores endpoint info
dest.arn_topic = topic_name;
// the topic ARN will be sent in the reply
const rgw::ARN arn(rgw::Partition::aws, rgw::Service::sns,
driver->get_zone()->get_zonegroup().get_name(),
s->user->get_tenant(), topic_name);
topic_arn = arn.to_string();
return 0;
}
public:
int verify_permission(optional_yield) override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute(optional_yield) override;
const char* name() const override { return "pubsub_topic_create"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_CREATE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
void send_response() override {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret < 0) {
return;
}
const auto f = s->formatter;
f->open_object_section_in_ns("CreateTopicResponse", AWS_SNS_NS);
f->open_object_section("CreateTopicResult");
encode_xml("TopicArn", topic_arn, f);
f->close_section(); // CreateTopicResult
f->open_object_section("ResponseMetadata");
encode_xml("RequestId", s->req_id, f);
f->close_section(); // ResponseMetadata
f->close_section(); // CreateTopicResponse
rgw_flush_formatter_and_reset(s, f);
}
};
void RGWPSCreateTopicOp::execute(optional_yield y) {
op_ret = get_params();
if (op_ret < 0) {
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
op_ret = ps.create_topic(this, topic_name, dest, topic_arn, opaque_data, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to create topic '" << topic_name << "', ret=" << op_ret << dendl;
return;
}
ldpp_dout(this, 20) << "successfully created topic '" << topic_name << "'" << dendl;
}
// command (AWS compliant):
// POST
// Action=ListTopics
class RGWPSListTopicsOp : public RGWOp {
private:
rgw_pubsub_topics result;
public:
int verify_permission(optional_yield) override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute(optional_yield) override;
const char* name() const override { return "pubsub_topics_list"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPICS_LIST; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
void send_response() override {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret < 0) {
return;
}
const auto f = s->formatter;
f->open_object_section_in_ns("ListTopicsResponse", AWS_SNS_NS);
f->open_object_section("ListTopicsResult");
encode_xml("Topics", result, f);
f->close_section(); // ListTopicsResult
f->open_object_section("ResponseMetadata");
encode_xml("RequestId", s->req_id, f);
f->close_section(); // ResponseMetadat
f->close_section(); // ListTopicsResponse
rgw_flush_formatter_and_reset(s, f);
}
};
void RGWPSListTopicsOp::execute(optional_yield y) {
const RGWPubSub ps(driver, s->owner.get_id().tenant);
op_ret = ps.get_topics(this, result, y);
// if there are no topics it is not considered an error
op_ret = op_ret == -ENOENT ? 0 : op_ret;
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get topics, ret=" << op_ret << dendl;
return;
}
if (topics_has_endpoint_secret(result) && !verify_transport_security(s->cct, *(s->info.env))) {
ldpp_dout(this, 1) << "topics contain secrets and cannot be sent over insecure transport" << dendl;
op_ret = -EPERM;
return;
}
ldpp_dout(this, 20) << "successfully got topics" << dendl;
}
// command (extension to AWS):
// POST
// Action=GetTopic&TopicArn=<topic-arn>
class RGWPSGetTopicOp : public RGWOp {
private:
std::string topic_name;
rgw_pubsub_topic result;
int get_params() {
const auto topic_arn = rgw::ARN::parse((s->info.args.get("TopicArn")));
if (!topic_arn || topic_arn->resource.empty()) {
ldpp_dout(this, 1) << "GetTopic Action 'TopicArn' argument is missing or invalid" << dendl;
return -EINVAL;
}
topic_name = topic_arn->resource;
return 0;
}
public:
int verify_permission(optional_yield y) override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute(optional_yield y) override;
const char* name() const override { return "pubsub_topic_get"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_GET; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
void send_response() override {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret < 0) {
return;
}
const auto f = s->formatter;
f->open_object_section("GetTopicResponse");
f->open_object_section("GetTopicResult");
encode_xml("Topic", result, f);
f->close_section();
f->open_object_section("ResponseMetadata");
encode_xml("RequestId", s->req_id, f);
f->close_section();
f->close_section();
rgw_flush_formatter_and_reset(s, f);
}
};
void RGWPSGetTopicOp::execute(optional_yield y) {
op_ret = get_params();
if (op_ret < 0) {
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
op_ret = ps.get_topic(this, topic_name, result, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get topic '" << topic_name << "', ret=" << op_ret << dendl;
return;
}
if (topic_has_endpoint_secret(result) && !verify_transport_security(s->cct, *(s->info.env))) {
ldpp_dout(this, 1) << "topic '" << topic_name << "' contain secret and cannot be sent over insecure transport" << dendl;
op_ret = -EPERM;
return;
}
ldpp_dout(this, 1) << "successfully got topic '" << topic_name << "'" << dendl;
}
// command (AWS compliant):
// POST
// Action=GetTopicAttributes&TopicArn=<topic-arn>
class RGWPSGetTopicAttributesOp : public RGWOp {
private:
std::string topic_name;
rgw_pubsub_topic result;
int get_params() {
const auto topic_arn = rgw::ARN::parse((s->info.args.get("TopicArn")));
if (!topic_arn || topic_arn->resource.empty()) {
ldpp_dout(this, 1) << "GetTopicAttribute Action 'TopicArn' argument is missing or invalid" << dendl;
return -EINVAL;
}
topic_name = topic_arn->resource;
return 0;
}
public:
int verify_permission(optional_yield y) override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute(optional_yield y) override;
const char* name() const override { return "pubsub_topic_get"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_GET; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
void send_response() override {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret < 0) {
return;
}
const auto f = s->formatter;
f->open_object_section_in_ns("GetTopicAttributesResponse", AWS_SNS_NS);
f->open_object_section("GetTopicAttributesResult");
result.dump_xml_as_attributes(f);
f->close_section(); // GetTopicAttributesResult
f->open_object_section("ResponseMetadata");
encode_xml("RequestId", s->req_id, f);
f->close_section(); // ResponseMetadata
f->close_section(); // GetTopicAttributesResponse
rgw_flush_formatter_and_reset(s, f);
}
};
void RGWPSGetTopicAttributesOp::execute(optional_yield y) {
op_ret = get_params();
if (op_ret < 0) {
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
op_ret = ps.get_topic(this, topic_name, result, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get topic '" << topic_name << "', ret=" << op_ret << dendl;
return;
}
if (topic_has_endpoint_secret(result) && !verify_transport_security(s->cct, *(s->info.env))) {
ldpp_dout(this, 1) << "topic '" << topic_name << "' contain secret and cannot be sent over insecure transport" << dendl;
op_ret = -EPERM;
return;
}
ldpp_dout(this, 1) << "successfully got topic '" << topic_name << "'" << dendl;
}
// command (AWS compliant):
// POST
// Action=DeleteTopic&TopicArn=<topic-arn>
class RGWPSDeleteTopicOp : public RGWOp {
private:
std::string topic_name;
int get_params() {
const auto topic_arn = rgw::ARN::parse((s->info.args.get("TopicArn")));
if (!topic_arn || topic_arn->resource.empty()) {
ldpp_dout(this, 1) << "DeleteTopic Action 'TopicArn' argument is missing or invalid" << dendl;
return -EINVAL;
}
topic_name = topic_arn->resource;
// upon deletion it is not known if topic is persistent or not
// will try to delete the persistent topic anyway
const auto ret = rgw::notify::remove_persistent_topic(topic_name, s->yield);
if (ret == -ENOENT) {
// topic was not persistent, or already deleted
return 0;
}
if (ret < 0) {
ldpp_dout(this, 1) << "DeleteTopic Action failed to remove queue for persistent topics. error:" << ret << dendl;
return ret;
}
return 0;
}
public:
int verify_permission(optional_yield) override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute(optional_yield y) override;
const char* name() const override { return "pubsub_topic_delete"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_DELETE; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
void send_response() override {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret < 0) {
return;
}
const auto f = s->formatter;
f->open_object_section_in_ns("DeleteTopicResponse", AWS_SNS_NS);
f->open_object_section("ResponseMetadata");
encode_xml("RequestId", s->req_id, f);
f->close_section(); // ResponseMetadata
f->close_section(); // DeleteTopicResponse
rgw_flush_formatter_and_reset(s, f);
}
};
void RGWPSDeleteTopicOp::execute(optional_yield y) {
op_ret = get_params();
if (op_ret < 0) {
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
op_ret = ps.remove_topic(this, topic_name, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to remove topic '" << topic_name << ", ret=" << op_ret << dendl;
return;
}
ldpp_dout(this, 1) << "successfully removed topic '" << topic_name << "'" << dendl;
}
using op_generator = RGWOp*(*)();
static const std::unordered_map<std::string, op_generator> op_generators = {
{"CreateTopic", []() -> RGWOp* {return new RGWPSCreateTopicOp;}},
{"DeleteTopic", []() -> RGWOp* {return new RGWPSDeleteTopicOp;}},
{"ListTopics", []() -> RGWOp* {return new RGWPSListTopicsOp;}},
{"GetTopic", []() -> RGWOp* {return new RGWPSGetTopicOp;}},
{"GetTopicAttributes", []() -> RGWOp* {return new RGWPSGetTopicAttributesOp;}}
};
bool RGWHandler_REST_PSTopic_AWS::action_exists(const req_state* s)
{
if (s->info.args.exists("Action")) {
const std::string action_name = s->info.args.get("Action");
return op_generators.contains(action_name);
}
return false;
}
RGWOp *RGWHandler_REST_PSTopic_AWS::op_post()
{
s->dialect = "sns";
s->prot_flags = RGW_REST_STS;
if (s->info.args.exists("Action")) {
const std::string action_name = s->info.args.get("Action");
const auto action_it = op_generators.find(action_name);
if (action_it != op_generators.end()) {
return action_it->second();
}
ldpp_dout(s, 10) << "unknown action '" << action_name << "' for Topic handler" << dendl;
} else {
ldpp_dout(s, 10) << "missing action argument in Topic handler" << dendl;
}
return nullptr;
}
int RGWHandler_REST_PSTopic_AWS::authorize(const DoutPrefixProvider* dpp, optional_yield y) {
const auto rc = RGW_Auth_S3::authorize(dpp, driver, auth_registry, s, y);
if (rc < 0) {
return rc;
}
if (s->auth.identity->is_anonymous()) {
ldpp_dout(dpp, 1) << "anonymous user not allowed in topic operations" << dendl;
return -ERR_INVALID_REQUEST;
}
return 0;
}
namespace {
// return a unique topic by prefexing with the notification name: <notification>_<topic>
std::string topic_to_unique(const std::string& topic, const std::string& notification) {
return notification + "_" + topic;
}
// extract the topic from a unique topic of the form: <notification>_<topic>
[[maybe_unused]] std::string unique_to_topic(const std::string& unique_topic, const std::string& notification) {
if (unique_topic.find(notification + "_") == std::string::npos) {
return "";
}
return unique_topic.substr(notification.length() + 1);
}
// 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& notif_name) {
auto it = std::find_if(bucket_topics.topics.begin(), bucket_topics.topics.end(), [&](const auto& val) { return notif_name == 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 remove_notification_by_topic(const DoutPrefixProvider *dpp, const std::string& topic_name, const RGWPubSub::Bucket& b, optional_yield y, const RGWPubSub& ps) {
int op_ret = b.remove_notification(dpp, topic_name, y);
if (op_ret < 0) {
ldpp_dout(dpp, 1) << "failed to remove notification of topic '" << topic_name << "', ret=" << op_ret << dendl;
}
op_ret = ps.remove_topic(dpp, topic_name, y);
if (op_ret < 0) {
ldpp_dout(dpp, 1) << "failed to remove auto-generated topic '" << topic_name << "', ret=" << op_ret << dendl;
}
return op_ret;
}
int delete_all_notifications(const DoutPrefixProvider *dpp, const rgw_pubsub_bucket_topics& bucket_topics, const RGWPubSub::Bucket& b, optional_yield y, const RGWPubSub& ps) {
// delete all notifications of on a bucket
for (const auto& topic : bucket_topics.topics) {
const auto op_ret = remove_notification_by_topic(dpp, topic.first, b, y, ps);
if (op_ret < 0) {
return op_ret;
}
}
return 0;
}
// command (S3 compliant): PUT /<bucket name>?notification
// a "notification" and a subscription will be auto-generated
// actual configuration is XML encoded in the body of the message
class RGWPSCreateNotifOp : public RGWDefaultResponseOp {
int verify_params() override {
bool exists;
const auto no_value = s->info.args.get("notification", &exists);
if (!exists) {
ldpp_dout(this, 1) << "missing required param 'notification'" << dendl;
return -EINVAL;
}
if (no_value.length() > 0) {
ldpp_dout(this, 1) << "param 'notification' should not have any value" << dendl;
return -EINVAL;
}
if (s->bucket_name.empty()) {
ldpp_dout(this, 1) << "request must be on a bucket" << dendl;
return -EINVAL;
}
return 0;
}
int get_params_from_body(rgw_pubsub_s3_notifications& configurations) {
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r;
bufferlist data;
std::tie(r, data) = read_all_input(s, max_size, false);
if (r < 0) {
ldpp_dout(this, 1) << "failed to read XML payload" << dendl;
return r;
}
if (data.length() == 0) {
ldpp_dout(this, 1) << "XML payload missing" << dendl;
return -EINVAL;
}
RGWXMLDecoder::XMLParser parser;
if (!parser.init()){
ldpp_dout(this, 1) << "failed to initialize XML parser" << dendl;
return -EINVAL;
}
if (!parser.parse(data.c_str(), data.length(), 1)) {
ldpp_dout(this, 1) << "failed to parse XML payload" << dendl;
return -ERR_MALFORMED_XML;
}
try {
// NotificationConfigurations is mandatory
// It can be empty which means we delete all the notifications
RGWXMLDecoder::decode_xml("NotificationConfiguration", configurations, &parser, true);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 1) << "failed to parse XML payload. error: " << err << dendl;
return -ERR_MALFORMED_XML;
}
return 0;
}
public:
int verify_permission(optional_yield y) override;
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
const char* name() const override { return "pubsub_notification_create_s3"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_NOTIF_CREATE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
void execute(optional_yield) override;
};
void RGWPSCreateNotifOp::execute(optional_yield y) {
op_ret = verify_params();
if (op_ret < 0) {
return;
}
rgw_pubsub_s3_notifications configurations;
op_ret = get_params_from_body(configurations);
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(s->owner.get_id());
std::unique_ptr<rgw::sal::Bucket> bucket;
op_ret = driver->get_bucket(this, user.get(), s->owner.get_id().tenant, s->bucket_name, &bucket, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get bucket '" << s->bucket_name << "' info, ret = " << op_ret << dendl;
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
const RGWPubSub::Bucket b(ps, bucket.get());
if(configurations.list.empty()) {
// get all topics on a bucket
rgw_pubsub_bucket_topics bucket_topics;
op_ret = b.get_topics(this, bucket_topics, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get list of topics from bucket '" << s->bucket_name << "', ret=" << op_ret << dendl;
return;
}
op_ret = delete_all_notifications(this, bucket_topics, b, y, ps);
return;
}
for (const auto& c : configurations.list) {
const auto& notif_name = c.id;
if (notif_name.empty()) {
ldpp_dout(this, 1) << "missing notification id" << dendl;
op_ret = -EINVAL;
return;
}
if (c.topic_arn.empty()) {
ldpp_dout(this, 1) << "missing topic ARN in notification: '" << notif_name << "'" << dendl;
op_ret = -EINVAL;
return;
}
const auto arn = rgw::ARN::parse(c.topic_arn);
if (!arn || arn->resource.empty()) {
ldpp_dout(this, 1) << "topic ARN has invalid format: '" << c.topic_arn << "' in notification: '" << notif_name << "'" << dendl;
op_ret = -EINVAL;
return;
}
if (std::find(c.events.begin(), c.events.end(), rgw::notify::UnknownEvent) != c.events.end()) {
ldpp_dout(this, 1) << "unknown event type in notification: '" << notif_name << "'" << dendl;
op_ret = -EINVAL;
return;
}
const auto topic_name = arn->resource;
// get topic information. destination information is stored in the topic
rgw_pubsub_topic topic_info;
op_ret = ps.get_topic(this, topic_name, topic_info, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get topic '" << topic_name << "', ret=" << op_ret << dendl;
return;
}
// make sure that full topic configuration match
// TODO: use ARN match function
// create unique topic name. this has 2 reasons:
// (1) topics cannot be shared between different S3 notifications because they hold the filter information
// (2) make topic clneaup easier, when notification is removed
const auto unique_topic_name = topic_to_unique(topic_name, notif_name);
// generate the internal topic. destination is stored here for the "push-only" case
// when no subscription exists
// ARN is cached to make the "GET" method faster
op_ret = ps.create_topic(this, unique_topic_name, topic_info.dest, topic_info.arn, topic_info.opaque_data, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to auto-generate unique topic '" << unique_topic_name <<
"', ret=" << op_ret << dendl;
return;
}
ldpp_dout(this, 20) << "successfully auto-generated unique topic '" << unique_topic_name << "'" << dendl;
// generate the notification
rgw::notify::EventTypeList events;
op_ret = b.create_notification(this, unique_topic_name, c.events, std::make_optional(c.filter), notif_name, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to auto-generate notification for unique topic '" << unique_topic_name <<
"', ret=" << op_ret << dendl;
// rollback generated topic (ignore return value)
ps.remove_topic(this, unique_topic_name, y);
return;
}
ldpp_dout(this, 20) << "successfully auto-generated notification for unique topic '" << unique_topic_name << "'" << dendl;
}
}
int RGWPSCreateNotifOp::verify_permission(optional_yield y) {
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketNotification)) {
return -EACCES;
}
return 0;
}
// command (extension to S3): DELETE /bucket?notification[=<notification-id>]
class RGWPSDeleteNotifOp : public RGWDefaultResponseOp {
int get_params(std::string& notif_name) const {
bool exists;
notif_name = s->info.args.get("notification", &exists);
if (!exists) {
ldpp_dout(this, 1) << "missing required param 'notification'" << dendl;
return -EINVAL;
}
if (s->bucket_name.empty()) {
ldpp_dout(this, 1) << "request must be on a bucket" << dendl;
return -EINVAL;
}
return 0;
}
public:
int verify_permission(optional_yield y) override;
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
const char* name() const override { return "pubsub_notification_delete_s3"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_NOTIF_DELETE; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
void execute(optional_yield y) override;
};
void RGWPSDeleteNotifOp::execute(optional_yield y) {
std::string notif_name;
op_ret = get_params(notif_name);
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(s->owner.get_id());
std::unique_ptr<rgw::sal::Bucket> bucket;
op_ret = driver->get_bucket(this, user.get(), s->owner.get_id().tenant, s->bucket_name, &bucket, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get bucket '" << s->bucket_name << "' info, ret = " << op_ret << dendl;
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
const RGWPubSub::Bucket b(ps, bucket.get());
// get all topics on a bucket
rgw_pubsub_bucket_topics bucket_topics;
op_ret = b.get_topics(this, bucket_topics, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get list of topics from bucket '" << s->bucket_name << "', ret=" << op_ret << dendl;
return;
}
if (!notif_name.empty()) {
// delete a specific notification
const auto unique_topic = find_unique_topic(bucket_topics, notif_name);
if (unique_topic) {
const auto unique_topic_name = unique_topic->get().topic.name;
op_ret = remove_notification_by_topic(this, unique_topic_name, b, y, ps);
return;
}
// notification to be removed is not found - considered success
ldpp_dout(this, 20) << "notification '" << notif_name << "' already removed" << dendl;
return;
}
op_ret = delete_all_notifications(this, bucket_topics, b, y, ps);
}
int RGWPSDeleteNotifOp::verify_permission(optional_yield y) {
if (!verify_bucket_permission(this, s, rgw::IAM::s3PutBucketNotification)) {
return -EACCES;
}
return 0;
}
// command (S3 compliant): GET /bucket?notification[=<notification-id>]
class RGWPSListNotifsOp : public RGWOp {
rgw_pubsub_s3_notifications notifications;
int get_params(std::string& notif_name) const {
bool exists;
notif_name = s->info.args.get("notification", &exists);
if (!exists) {
ldpp_dout(this, 1) << "missing required param 'notification'" << dendl;
return -EINVAL;
}
if (s->bucket_name.empty()) {
ldpp_dout(this, 1) << "request must be on a bucket" << dendl;
return -EINVAL;
}
return 0;
}
public:
int verify_permission(optional_yield y) override;
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
const char* name() const override { return "pubsub_notifications_get_s3"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_NOTIF_LIST; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
void execute(optional_yield y) override;
void send_response() override {
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret < 0) {
return;
}
notifications.dump_xml(s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
};
void RGWPSListNotifsOp::execute(optional_yield y) {
std::string notif_name;
op_ret = get_params(notif_name);
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(s->owner.get_id());
std::unique_ptr<rgw::sal::Bucket> bucket;
op_ret = driver->get_bucket(this, user.get(), s->owner.get_id().tenant, s->bucket_name, &bucket, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get bucket '" << s->bucket_name << "' info, ret = " << op_ret << dendl;
return;
}
const RGWPubSub ps(driver, s->owner.get_id().tenant);
const RGWPubSub::Bucket b(ps, bucket.get());
// get all topics on a bucket
rgw_pubsub_bucket_topics bucket_topics;
op_ret = b.get_topics(this, bucket_topics, y);
if (op_ret < 0) {
ldpp_dout(this, 1) << "failed to get list of topics from bucket '" << s->bucket_name << "', ret=" << op_ret << dendl;
return;
}
if (!notif_name.empty()) {
// get info of a specific notification
const auto unique_topic = find_unique_topic(bucket_topics, notif_name);
if (unique_topic) {
notifications.list.emplace_back(unique_topic->get());
return;
}
op_ret = -ENOENT;
ldpp_dout(this, 1) << "failed to get notification info for '" << notif_name << "', ret=" << op_ret << dendl;
return;
}
// loop through all topics of the bucket
for (const auto& topic : bucket_topics.topics) {
if (topic.second.s3_id.empty()) {
// not an s3 notification
continue;
}
notifications.list.emplace_back(topic.second);
}
}
int RGWPSListNotifsOp::verify_permission(optional_yield y) {
if (!verify_bucket_permission(this, s, rgw::IAM::s3GetBucketNotification)) {
return -EACCES;
}
return 0;
}
RGWOp* RGWHandler_REST_PSNotifs_S3::op_get() {
return new RGWPSListNotifsOp();
}
RGWOp* RGWHandler_REST_PSNotifs_S3::op_put() {
return new RGWPSCreateNotifOp();
}
RGWOp* RGWHandler_REST_PSNotifs_S3::op_delete() {
return new RGWPSDeleteNotifOp();
}
RGWOp* RGWHandler_REST_PSNotifs_S3::create_get_op() {
return new RGWPSListNotifsOp();
}
RGWOp* RGWHandler_REST_PSNotifs_S3::create_put_op() {
return new RGWPSCreateNotifOp();
}
RGWOp* RGWHandler_REST_PSNotifs_S3::create_delete_op() {
return new RGWPSDeleteNotifOp();
}
| 30,757 | 31.410959 | 175 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_ratelimit.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_ratelimit.h"
class RGWOp_Ratelimit_Info : public RGWRESTOp {
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("ratelimit", RGW_CAP_READ);
}
void execute(optional_yield y) override;
const char* name() const override { return "get_ratelimit_info"; }
};
void RGWOp_Ratelimit_Info::execute(optional_yield y)
{
ldpp_dout(this, 20) << "" << dendl;
std::string uid_str;
std::string ratelimit_scope;
std::string bucket_name;
std::string tenant_name;
bool global = false;
RESTArgs::get_string(s, "uid", uid_str, &uid_str);
RESTArgs::get_string(s, "ratelimit-scope", ratelimit_scope, &ratelimit_scope);
RESTArgs::get_string(s, "bucket", bucket_name, &bucket_name);
RESTArgs::get_string(s, "tenant", tenant_name, &tenant_name);
// RESTArgs::get_bool default value to true even if global is empty
bool exists;
std::string sval = s->info.args.get("global", &exists);
if (exists) {
if (!boost::iequals(sval,"true") && !boost::iequals(sval,"false")) {
op_ret = -EINVAL;
ldpp_dout(this, 20) << "global is not equal to true or false" << dendl;
return;
}
}
RESTArgs::get_bool(s, "global", false, &global);
if (ratelimit_scope == "bucket" && !bucket_name.empty() && !global) {
std::unique_ptr<rgw::sal::Bucket> bucket;
int r = driver->get_bucket(s, nullptr, tenant_name, bucket_name, &bucket, y);
if (r != 0) {
op_ret = r;
ldpp_dout(this, 0) << "Error on getting bucket info" << dendl;
return;
}
RGWRateLimitInfo ratelimit_info;
auto iter = bucket->get_attrs().find(RGW_ATTR_RATELIMIT);
if (iter != bucket->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "Error on decoding ratelimit info from bucket" << dendl;
op_ret = -EIO;
return;
}
}
flusher.start(0);
s->formatter->open_object_section("bucket_ratelimit");
encode_json("bucket_ratelimit", ratelimit_info, s->formatter);
s->formatter->close_section();
flusher.flush();
return;
}
if (ratelimit_scope == "user" && !uid_str.empty() && !global) {
RGWRateLimitInfo ratelimit_info;
rgw_user user(uid_str);
std::unique_ptr<rgw::sal::User> user_sal;
user_sal = driver->get_user(user);
if (!rgw::sal::User::empty(user_sal)) {
op_ret = user_sal->load_user(this, y);
if (op_ret) {
ldpp_dout(this, 0) << "Cannot load user info" << dendl;
return;
}
} else {
ldpp_dout(this, 0) << "User does not exist" << dendl;
op_ret = -ENOENT;
return;
}
auto iter = user_sal->get_attrs().find(RGW_ATTR_RATELIMIT);
if(iter != user_sal->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "Error on decoding ratelimit info from user" << dendl;
op_ret = -EIO;
return;
}
}
flusher.start(0);
s->formatter->open_object_section("user_ratelimit");
encode_json("user_ratelimit", ratelimit_info, s->formatter);
s->formatter->close_section();
flusher.flush();
}
if (global) {
std::string realm_id = driver->get_zone()->get_realm_id();
RGWPeriodConfig period_config;
op_ret = period_config.read(this, static_cast<rgw::sal::RadosStore*>(driver)->svc()->sysobj, realm_id, y);
if (op_ret && op_ret != -ENOENT) {
ldpp_dout(this, 0) << "Error on period config read" << dendl;
return;
}
flusher.start(0);
s->formatter->open_object_section("period_config");
encode_json("bucket_ratelimit", period_config.bucket_ratelimit, s->formatter);
encode_json("user_ratelimit", period_config.user_ratelimit, s->formatter);
encode_json("anonymous_ratelimit", period_config.anon_ratelimit, s->formatter);
s->formatter->close_section();
flusher.flush();
return;
}
op_ret = -EINVAL;
return;
}
class RGWOp_Ratelimit_Set : public RGWRESTOp {
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("ratelimit", RGW_CAP_WRITE);
}
void execute(optional_yield y) override;
const char* name() const override { return "put_ratelimit_info"; }
void set_ratelimit_info(bool have_max_read_ops, int64_t max_read_ops, bool have_max_write_ops, int64_t max_write_ops,
bool have_max_read_bytes, int64_t max_read_bytes, bool have_max_write_bytes, int64_t max_write_bytes,
bool have_enabled, bool enabled, bool& ratelimit_configured, RGWRateLimitInfo& ratelimit_info);
};
void RGWOp_Ratelimit_Set::set_ratelimit_info(bool have_max_read_ops, int64_t max_read_ops, bool have_max_write_ops, int64_t max_write_ops,
bool have_max_read_bytes, int64_t max_read_bytes, bool have_max_write_bytes, int64_t max_write_bytes,
bool have_enabled, bool enabled, bool& ratelimit_configured, RGWRateLimitInfo& ratelimit_info)
{
if (have_max_read_ops) {
if (max_read_ops >= 0) {
ratelimit_info.max_read_ops = max_read_ops;
ratelimit_configured = true;
}
}
if (have_max_write_ops) {
if (max_write_ops >= 0) {
ratelimit_info.max_write_ops = max_write_ops;
ratelimit_configured = true;
}
}
if (have_max_read_bytes) {
if (max_read_bytes >= 0) {
ratelimit_info.max_read_bytes = max_read_bytes;
ratelimit_configured = true;
}
}
if (have_max_write_bytes) {
if (max_write_bytes >= 0) {
ratelimit_info.max_write_bytes = max_write_bytes;
ratelimit_configured = true;
}
}
if (have_enabled) {
ratelimit_info.enabled = enabled;
ratelimit_configured = true;
}
if (!ratelimit_configured) {
ldpp_dout(this, 0) << "No rate limit configuration arguments have been sent" << dendl;
op_ret = -EINVAL;
return;
}
}
void RGWOp_Ratelimit_Set::execute(optional_yield y)
{
std::string uid_str;
std::string ratelimit_scope;
std::string bucket_name;
std::string tenant_name;
RGWRateLimitInfo ratelimit_info;
bool ratelimit_configured = false;
bool enabled = false;
bool have_enabled = false;
bool global = false;
int64_t max_read_ops = 0;
bool have_max_read_ops = false;
int64_t max_write_ops = 0;
bool have_max_write_ops = false;
int64_t max_read_bytes = 0;
bool have_max_read_bytes = false;
int64_t max_write_bytes = 0;
bool have_max_write_bytes = false;
RESTArgs::get_string(s, "uid", uid_str, &uid_str);
RESTArgs::get_string(s, "ratelimit-scope", ratelimit_scope, &ratelimit_scope);
RESTArgs::get_string(s, "bucket", bucket_name, &bucket_name);
RESTArgs::get_string(s, "tenant", tenant_name, &tenant_name);
// check there was no -EINVAL coming from get_int64
op_ret = RESTArgs::get_int64(s, "max-read-ops", 0, &max_read_ops, &have_max_read_ops);
op_ret |= RESTArgs::get_int64(s, "max-write-ops", 0, &max_write_ops, &have_max_write_ops);
op_ret |= RESTArgs::get_int64(s, "max-read-bytes", 0, &max_read_bytes, &have_max_read_bytes);
op_ret |= RESTArgs::get_int64(s, "max-write-bytes", 0, &max_write_bytes, &have_max_write_bytes);
if (op_ret) {
ldpp_dout(this, 0) << "one of the maximum arguments could not be parsed" << dendl;
return;
}
// RESTArgs::get_bool default value to true even if enabled or global are empty
std::string sval = s->info.args.get("enabled", &have_enabled);
if (have_enabled) {
if (!boost::iequals(sval,"true") && !boost::iequals(sval,"false")) {
ldpp_dout(this, 20) << "enabled is not equal to true or false" << dendl;
op_ret = -EINVAL;
return;
}
}
RESTArgs::get_bool(s, "enabled", false, &enabled, &have_enabled);
bool exists;
sval = s->info.args.get("global", &exists);
if (exists) {
if (!boost::iequals(sval,"true") && !boost::iequals(sval,"false")) {
ldpp_dout(this, 20) << "global is not equal to true or faslse" << dendl;
op_ret = -EINVAL;
return;
}
}
RESTArgs::get_bool(s, "global", false, &global, nullptr);
set_ratelimit_info(have_max_read_ops, max_read_ops, have_max_write_ops, max_write_ops,
have_max_read_bytes, max_read_bytes, have_max_write_bytes, max_write_bytes,
have_enabled, enabled, ratelimit_configured, ratelimit_info);
if (op_ret) {
return;
}
if (ratelimit_scope == "user" && !uid_str.empty() && !global) {
rgw_user user(uid_str);
std::unique_ptr<rgw::sal::User> user_sal;
user_sal = driver->get_user(user);
if (!rgw::sal::User::empty(user_sal)) {
op_ret = user_sal->load_user(this, y);
if (op_ret) {
ldpp_dout(this, 0) << "Cannot load user info" << dendl;
return;
}
} else {
ldpp_dout(this, 0) << "User does not exist" << dendl;
op_ret = -ENOENT;
return;
}
auto iter = user_sal->get_attrs().find(RGW_ATTR_RATELIMIT);
if (iter != user_sal->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "Error on decoding ratelimit info from user" << dendl;
op_ret = -EIO;
return;
}
}
set_ratelimit_info(have_max_read_ops, max_read_ops, have_max_write_ops, max_write_ops,
have_max_read_bytes, max_read_bytes, have_max_write_bytes, max_write_bytes,
have_enabled, enabled, ratelimit_configured, ratelimit_info);
bufferlist bl;
ratelimit_info.encode(bl);
rgw::sal::Attrs attr;
attr[RGW_ATTR_RATELIMIT] = bl;
op_ret = user_sal->merge_and_store_attrs(this, attr, y);
return;
}
if (ratelimit_scope == "bucket" && !bucket_name.empty() && !global) {
ldpp_dout(this, 0) << "getting bucket info" << dendl;
std::unique_ptr<rgw::sal::Bucket> bucket;
op_ret = driver->get_bucket(this, nullptr, tenant_name, bucket_name, &bucket, y);
if (op_ret) {
ldpp_dout(this, 0) << "Error on getting bucket info" << dendl;
return;
}
auto iter = bucket->get_attrs().find(RGW_ATTR_RATELIMIT);
if (iter != bucket->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "Error on decoding ratelimit info from bucket" << dendl;
op_ret = -EIO;
return;
}
}
bufferlist bl;
set_ratelimit_info(have_max_read_ops, max_read_ops, have_max_write_ops, max_write_ops,
have_max_read_bytes, max_read_bytes, have_max_write_bytes, max_write_bytes,
have_enabled, enabled, ratelimit_configured, ratelimit_info);
ratelimit_info.encode(bl);
rgw::sal::Attrs attr;
attr[RGW_ATTR_RATELIMIT] = bl;
op_ret = bucket->merge_and_store_attrs(this, attr, y);
return;
}
if (global) {
std::string realm_id = driver->get_zone()->get_realm_id();
RGWPeriodConfig period_config;
op_ret = period_config.read(s, static_cast<rgw::sal::RadosStore*>(driver)->svc()->sysobj, realm_id, y);
if (op_ret && op_ret != -ENOENT) {
ldpp_dout(this, 0) << "Error on period config read" << dendl;
return;
}
if (ratelimit_scope == "bucket") {
ratelimit_info = period_config.bucket_ratelimit;
set_ratelimit_info(have_max_read_ops, max_read_ops, have_max_write_ops, max_write_ops,
have_max_read_bytes, max_read_bytes, have_max_write_bytes, max_write_bytes,
have_enabled, enabled, ratelimit_configured, ratelimit_info);
period_config.bucket_ratelimit = ratelimit_info;
op_ret = period_config.write(s, static_cast<rgw::sal::RadosStore*>(driver)->svc()->sysobj, realm_id, y);
return;
}
if (ratelimit_scope == "anon") {
ratelimit_info = period_config.anon_ratelimit;
set_ratelimit_info(have_max_read_ops, max_read_ops, have_max_write_ops, max_write_ops,
have_max_read_bytes, max_read_bytes, have_max_write_bytes, max_write_bytes,
have_enabled, enabled, ratelimit_configured, ratelimit_info);
period_config.anon_ratelimit = ratelimit_info;
op_ret = period_config.write(s, static_cast<rgw::sal::RadosStore*>(driver)->svc()->sysobj, realm_id, y);
return;
}
if (ratelimit_scope == "user") {
ratelimit_info = period_config.user_ratelimit;
set_ratelimit_info(have_max_read_ops, max_read_ops, have_max_write_ops, max_write_ops,
have_max_read_bytes, max_read_bytes, have_max_write_bytes, max_write_bytes,
have_enabled, enabled, ratelimit_configured, ratelimit_info);
period_config.user_ratelimit = ratelimit_info;
op_ret = period_config.write(s, static_cast<rgw::sal::RadosStore*>(driver)->svc()->sysobj, realm_id, y);
return;
}
}
op_ret = -EINVAL;
return;
}
RGWOp* RGWHandler_Ratelimit::op_get()
{
return new RGWOp_Ratelimit_Info;
}
RGWOp* RGWHandler_Ratelimit::op_post()
{
return new RGWOp_Ratelimit_Set;
}
| 13,494 | 37.557143 | 140 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_ratelimit.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_rest.h"
#include "rgw_rest_s3.h"
#include "rgw_sal_rados.h"
class RGWHandler_Ratelimit : public RGWHandler_Auth_S3 {
protected:
RGWOp *op_get() override;
RGWOp *op_post() override;
public:
using RGWHandler_Auth_S3::RGWHandler_Auth_S3;
~RGWHandler_Ratelimit() override = default;
int read_permissions(RGWOp*, optional_yield) override {
return 0;
}
};
class RGWRESTMgr_Ratelimit : public RGWRESTMgr {
public:
RGWRESTMgr_Ratelimit() = default;
~RGWRESTMgr_Ratelimit() override = default;
RGWHandler_REST *get_handler(rgw::sal::Driver* driver,
req_state*,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string&) override {
return new RGWHandler_Ratelimit(auth_registry);
}
};
| 924 | 25.428571 | 80 |
h
|
null |
ceph-main/src/rgw/rgw_rest_role.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 <regex>
#include "common/errno.h"
#include "common/Formatter.h"
#include "common/ceph_json.h"
#include "include/types.h"
#include "rgw_string.h"
#include "rgw_common.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_role.h"
#include "rgw_rest_role.h"
#include "rgw_sal.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
int RGWRestRole::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
string role_name = s->info.args.get("RoleName");
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name,
s->user->get_tenant());
if (op_ret = role->get(s, y); op_ret < 0) {
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_ROLE_FOUND;
}
return op_ret;
}
if (int ret = check_caps(s->user->get_caps()); ret == 0) {
_role = std::move(role);
return ret;
}
string resource_name = role->get_path() + role_name;
uint64_t op = get_op();
if (!verify_user_permission(this,
s,
rgw::ARN(resource_name,
"role",
s->user->get_tenant(), true),
op)) {
return -EACCES;
}
_role = std::move(role);
return 0;
}
int RGWRestRole::parse_tags()
{
vector<string> keys, vals;
auto val_map = s->info.args.get_params();
const regex pattern_key("Tags.member.([0-9]+).Key");
const regex pattern_value("Tags.member.([0-9]+).Value");
for (auto& v : val_map) {
string key_index="", value_index="";
for(sregex_iterator it = sregex_iterator(
v.first.begin(), v.first.end(), pattern_key);
it != sregex_iterator(); it++) {
smatch match;
match = *it;
key_index = match.str(1);
ldout(s->cct, 20) << "Key index: " << match.str(1) << dendl;
if (!key_index.empty()) {
int index = stoi(key_index);
auto pos = keys.begin() + (index-1);
keys.insert(pos, v.second);
}
}
for(sregex_iterator it = sregex_iterator(
v.first.begin(), v.first.end(), pattern_value);
it != sregex_iterator(); it++) {
smatch match;
match = *it;
value_index = match.str(1);
ldout(s->cct, 20) << "Value index: " << match.str(1) << dendl;
if (!value_index.empty()) {
int index = stoi(value_index);
auto pos = vals.begin() + (index-1);
vals.insert(pos, v.second);
}
}
}
if (keys.size() != vals.size()) {
ldout(s->cct, 0) << "No. of keys doesn't match with no. of values in tags" << dendl;
return -EINVAL;
}
for (size_t i = 0; i < keys.size(); i++) {
tags.emplace(keys[i], vals[i]);
ldout(s->cct, 0) << "Tag Key: " << keys[i] << " Tag Value is: " << vals[i] << dendl;
}
return 0;
}
void RGWRestRole::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this);
}
int RGWRoleRead::check_caps(const RGWUserCaps& caps)
{
return caps.check_cap("roles", RGW_CAP_READ);
}
int RGWRoleWrite::check_caps(const RGWUserCaps& caps)
{
return caps.check_cap("roles", RGW_CAP_WRITE);
}
int RGWCreateRole::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if (int ret = check_caps(s->user->get_caps()); ret == 0) {
return ret;
}
string role_name = s->info.args.get("RoleName");
string role_path = s->info.args.get("Path");
string resource_name = role_path + role_name;
if (!verify_user_permission(this,
s,
rgw::ARN(resource_name,
"role",
s->user->get_tenant(), true),
get_op())) {
return -EACCES;
}
return 0;
}
int RGWCreateRole::get_params()
{
role_name = s->info.args.get("RoleName");
role_path = s->info.args.get("Path");
trust_policy = s->info.args.get("AssumeRolePolicyDocument");
max_session_duration = s->info.args.get("MaxSessionDuration");
if (role_name.empty() || trust_policy.empty()) {
ldpp_dout(this, 20) << "ERROR: one of role name or assume role policy document is empty"
<< dendl;
return -EINVAL;
}
bufferlist bl = bufferlist::static_from_string(trust_policy);
try {
const rgw::IAM::Policy p(
s->cct, s->user->get_tenant(), bl,
s->cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
}
catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 5) << "failed to parse policy: " << e.what() << dendl;
s->err.message = e.what();
return -ERR_MALFORMED_DOC;
}
int ret = parse_tags();
if (ret < 0) {
return ret;
}
if (tags.size() > 50) {
ldout(s->cct, 0) << "No. tags is greater than 50" << dendl;
return -EINVAL;
}
return 0;
}
void RGWCreateRole::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::string user_tenant = s->user->get_tenant();
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name,
user_tenant,
role_path,
trust_policy,
max_session_duration,
tags);
if (!user_tenant.empty() && role->get_tenant() != user_tenant) {
ldpp_dout(this, 20) << "ERROR: the tenant provided in the role name does not match with the tenant of the user creating the role"
<< dendl;
op_ret = -EINVAL;
return;
}
std::string role_id;
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("Path");
s->info.args.remove("AssumeRolePolicyDocument");
s->info.args.remove("MaxSessionDuration");
s->info.args.remove("Action");
s->info.args.remove("Version");
auto& val_map = s->info.args.get_params();
for (auto it = val_map.begin(); it!= val_map.end(); it++) {
if (it->first.find("Tags.member.") == 0) {
val_map.erase(it);
}
}
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
XMLObj* create_role_resp_obj = parser.find_first("CreateRoleResponse");;
if (!create_role_resp_obj) {
ldpp_dout(this, 5) << "ERROR: unexpected xml: CreateRoleResponse" << dendl;
op_ret = -EINVAL;
return;
}
XMLObj* create_role_res_obj = create_role_resp_obj->find_first("CreateRoleResult");
if (!create_role_res_obj) {
ldpp_dout(this, 5) << "ERROR: unexpected xml: CreateRoleResult" << dendl;
op_ret = -EINVAL;
return;
}
XMLObj* role_obj = nullptr;
if (create_role_res_obj) {
role_obj = create_role_res_obj->find_first("Role");
}
if (!role_obj) {
ldpp_dout(this, 5) << "ERROR: unexpected xml: Role" << dendl;
op_ret = -EINVAL;
return;
}
try {
if (role_obj) {
RGWXMLDecoder::decode_xml("RoleId", role_id, role_obj, true);
}
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "ERROR: unexpected xml: RoleId" << dendl;
op_ret = -EINVAL;
return;
}
ldpp_dout(this, 0) << "role_id decoded from master zonegroup response is" << role_id << dendl;
}
op_ret = role->create(s, true, role_id, y);
if (op_ret == -EEXIST) {
op_ret = -ERR_ROLE_EXISTS;
return;
}
if (op_ret == 0) {
s->formatter->open_object_section("CreateRoleResponse");
s->formatter->open_object_section("CreateRoleResult");
s->formatter->open_object_section("Role");
role->dump(s->formatter);
s->formatter->close_section();
s->formatter->close_section();
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWDeleteRole::get_params()
{
role_name = s->info.args.get("RoleName");
if (role_name.empty()) {
ldpp_dout(this, 20) << "ERROR: Role name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWDeleteRole::execute(optional_yield y)
{
bool is_master = true;
int master_op_ret = 0;
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
is_master = false;
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("Action");
s->info.args.remove("Version");
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
master_op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (master_op_ret < 0) {
op_ret = master_op_ret;
ldpp_dout(this, 0) << "forward_iam_request_to_master returned ret=" << op_ret << dendl;
return;
}
}
op_ret = _role->delete_obj(s, y);
if (op_ret == -ENOENT) {
//Role has been deleted since metadata from master has synced up
if (!is_master && master_op_ret == 0) {
op_ret = 0;
} else {
op_ret = -ERR_NO_ROLE_FOUND;
}
return;
}
if (!op_ret) {
s->formatter->open_object_section("DeleteRoleResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWGetRole::verify_permission(optional_yield y)
{
return 0;
}
int RGWGetRole::_verify_permission(const rgw::sal::RGWRole* role)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if (int ret = check_caps(s->user->get_caps()); ret == 0) {
return ret;
}
string resource_name = role->get_path() + role->get_name();
if (!verify_user_permission(this,
s,
rgw::ARN(resource_name,
"role",
s->user->get_tenant(), true),
get_op())) {
return -EACCES;
}
return 0;
}
int RGWGetRole::get_params()
{
role_name = s->info.args.get("RoleName");
if (role_name.empty()) {
ldpp_dout(this, 20) << "ERROR: Role name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWGetRole::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name,
s->user->get_tenant());
op_ret = role->get(s, y);
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_ROLE_FOUND;
return;
}
op_ret = _verify_permission(role.get());
if (op_ret == 0) {
s->formatter->open_object_section("GetRoleResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("GetRoleResult");
s->formatter->open_object_section("Role");
role->dump(s->formatter);
s->formatter->close_section();
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWModifyRoleTrustPolicy::get_params()
{
role_name = s->info.args.get("RoleName");
trust_policy = s->info.args.get("PolicyDocument");
if (role_name.empty() || trust_policy.empty()) {
ldpp_dout(this, 20) << "ERROR: One of role name or trust policy is empty"<< dendl;
return -EINVAL;
}
JSONParser p;
if (!p.parse(trust_policy.c_str(), trust_policy.length())) {
ldpp_dout(this, 20) << "ERROR: failed to parse assume role policy doc" << dendl;
return -ERR_MALFORMED_DOC;
}
return 0;
}
void RGWModifyRoleTrustPolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("PolicyDocument");
s->info.args.remove("Action");
s->info.args.remove("Version");
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
}
_role->update_trust_policy(trust_policy);
op_ret = _role->update(this, y);
s->formatter->open_object_section("UpdateAssumeRolePolicyResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
int RGWListRoles::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if (int ret = check_caps(s->user->get_caps()); ret == 0) {
return ret;
}
if (!verify_user_permission(this,
s,
rgw::ARN(),
get_op())) {
return -EACCES;
}
return 0;
}
int RGWListRoles::get_params()
{
path_prefix = s->info.args.get("PathPrefix");
return 0;
}
void RGWListRoles::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
vector<std::unique_ptr<rgw::sal::RGWRole>> result;
op_ret = driver->get_roles(s, y, path_prefix, s->user->get_tenant(), result);
if (op_ret == 0) {
s->formatter->open_array_section("ListRolesResponse");
s->formatter->open_array_section("ListRolesResult");
s->formatter->open_object_section("Roles");
for (const auto& it : result) {
s->formatter->open_object_section("member");
it->dump(s->formatter);
s->formatter->close_section();
}
s->formatter->close_section();
s->formatter->close_section();
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWPutRolePolicy::get_params()
{
role_name = s->info.args.get("RoleName");
policy_name = s->info.args.get("PolicyName");
perm_policy = s->info.args.get("PolicyDocument");
if (role_name.empty() || policy_name.empty() || perm_policy.empty()) {
ldpp_dout(this, 20) << "ERROR: One of role name, policy name or perm policy is empty"<< dendl;
return -EINVAL;
}
bufferlist bl = bufferlist::static_from_string(perm_policy);
try {
const rgw::IAM::Policy p(
s->cct, s->user->get_tenant(), bl,
s->cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
}
catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 20) << "failed to parse policy: " << e.what() << dendl;
s->err.message = e.what();
return -ERR_MALFORMED_DOC;
}
return 0;
}
void RGWPutRolePolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("PolicyName");
s->info.args.remove("PolicyDocument");
s->info.args.remove("Action");
s->info.args.remove("Version");
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
}
_role->set_perm_policy(policy_name, perm_policy);
op_ret = _role->update(this, y);
if (op_ret == 0) {
s->formatter->open_object_section("PutRolePolicyResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWGetRolePolicy::get_params()
{
role_name = s->info.args.get("RoleName");
policy_name = s->info.args.get("PolicyName");
if (role_name.empty() || policy_name.empty()) {
ldpp_dout(this, 20) << "ERROR: One of role name or policy name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWGetRolePolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
string perm_policy;
op_ret = _role->get_role_policy(this, policy_name, perm_policy);
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_SUCH_ENTITY;
}
if (op_ret == 0) {
s->formatter->open_object_section("GetRolePolicyResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("GetRolePolicyResult");
s->formatter->dump_string("PolicyName", policy_name);
s->formatter->dump_string("RoleName", role_name);
s->formatter->dump_string("PolicyDocument", perm_policy);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWListRolePolicies::get_params()
{
role_name = s->info.args.get("RoleName");
if (role_name.empty()) {
ldpp_dout(this, 20) << "ERROR: Role name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWListRolePolicies::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::vector<string> policy_names = _role->get_role_policy_names();
s->formatter->open_object_section("ListRolePoliciesResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("ListRolePoliciesResult");
s->formatter->open_array_section("PolicyNames");
for (const auto& it : policy_names) {
s->formatter->dump_string("member", it);
}
s->formatter->close_section();
s->formatter->close_section();
s->formatter->close_section();
}
int RGWDeleteRolePolicy::get_params()
{
role_name = s->info.args.get("RoleName");
policy_name = s->info.args.get("PolicyName");
if (role_name.empty() || policy_name.empty()) {
ldpp_dout(this, 20) << "ERROR: One of role name or policy name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWDeleteRolePolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("PolicyName");
s->info.args.remove("Action");
s->info.args.remove("Version");
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
}
op_ret = _role->delete_policy(this, policy_name);
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_ROLE_FOUND;
return;
}
if (op_ret == 0) {
op_ret = _role->update(this, y);
}
s->formatter->open_object_section("DeleteRolePoliciesResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
int RGWTagRole::get_params()
{
role_name = s->info.args.get("RoleName");
if (role_name.empty()) {
ldout(s->cct, 0) << "ERROR: Role name is empty" << dendl;
return -EINVAL;
}
int ret = parse_tags();
if (ret < 0) {
return ret;
}
return 0;
}
void RGWTagRole::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("Action");
s->info.args.remove("Version");
auto& val_map = s->info.args.get_params();
for (auto it = val_map.begin(); it!= val_map.end(); it++) {
if (it->first.find("Tags.member.") == 0) {
val_map.erase(it);
}
}
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
}
op_ret = _role->set_tags(this, tags);
if (op_ret == 0) {
op_ret = _role->update(this, y);
}
if (op_ret == 0) {
s->formatter->open_object_section("TagRoleResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWListRoleTags::get_params()
{
role_name = s->info.args.get("RoleName");
if (role_name.empty()) {
ldout(s->cct, 0) << "ERROR: Role name is empty" << dendl;
return -EINVAL;
}
return 0;
}
void RGWListRoleTags::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
boost::optional<multimap<string,string>> tag_map = _role->get_tags();
s->formatter->open_object_section("ListRoleTagsResponse");
s->formatter->open_object_section("ListRoleTagsResult");
if (tag_map) {
s->formatter->open_array_section("Tags");
for (const auto& it : tag_map.get()) {
s->formatter->open_object_section("Key");
encode_json("Key", it.first, s->formatter);
s->formatter->close_section();
s->formatter->open_object_section("Value");
encode_json("Value", it.second, s->formatter);
s->formatter->close_section();
}
s->formatter->close_section();
}
s->formatter->close_section();
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
int RGWUntagRole::get_params()
{
role_name = s->info.args.get("RoleName");
if (role_name.empty()) {
ldout(s->cct, 0) << "ERROR: Role name is empty" << dendl;
return -EINVAL;
}
auto val_map = s->info.args.get_params();
for (auto& it : val_map) {
if (it.first.find("TagKeys.member.") != string::npos) {
tagKeys.emplace_back(it.second);
}
}
return 0;
}
void RGWUntagRole::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("Action");
s->info.args.remove("Version");
auto& val_map = s->info.args.get_params();
std::vector<std::multimap<std::string, std::string>::iterator> iters;
for (auto it = val_map.begin(); it!= val_map.end(); it++) {
if (it->first.find("Tags.member.") == 0) {
iters.emplace_back(it);
}
}
for (auto& it : iters) {
val_map.erase(it);
}
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
}
_role->erase_tags(tagKeys);
op_ret = _role->update(this, y);
if (op_ret == 0) {
s->formatter->open_object_section("UntagRoleResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWUpdateRole::get_params()
{
role_name = s->info.args.get("RoleName");
max_session_duration = s->info.args.get("MaxSessionDuration");
if (role_name.empty()) {
ldpp_dout(this, 20) << "ERROR: Role name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWUpdateRole::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
if (!driver->is_meta_master()) {
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize xml parser" << dendl;
op_ret = -EINVAL;
return;
}
bufferlist data;
s->info.args.remove("RoleName");
s->info.args.remove("MaxSessionDuration");
s->info.args.remove("Action");
s->info.args.remove("Version");
RGWUserInfo info = s->user->get_info();
const auto& it = info.access_keys.begin();
RGWAccessKey key;
if (it != info.access_keys.end()) {
key.id = it->first;
RGWAccessKey cred = it->second;
key.key = cred.key;
}
op_ret = driver->forward_iam_request_to_master(s, key, nullptr, bl_post_body, &parser, s->info, y);
if (op_ret < 0) {
ldpp_dout(this, 20) << "ERROR: forward_iam_request_to_master failed with error code: " << op_ret << dendl;
return;
}
}
if (!_role->validate_max_session_duration(this)) {
op_ret = -EINVAL;
return;
}
_role->update_max_session_duration(max_session_duration);
op_ret = _role->update(this, y);
s->formatter->open_object_section("UpdateRoleResponse");
s->formatter->open_object_section("UpdateRoleResult");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
| 28,257 | 26.622678 | 133 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_role.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "common/async/yield_context.h"
#include "rgw_role.h"
#include "rgw_rest.h"
class RGWRestRole : public RGWRESTOp {
protected:
std::string role_name;
std::string role_path;
std::string trust_policy;
std::string policy_name;
std::string perm_policy;
std::string path_prefix;
std::string max_session_duration;
std::multimap<std::string,std::string> tags;
std::vector<std::string> tagKeys;
std::unique_ptr<rgw::sal::RGWRole> _role;
int verify_permission(optional_yield y) override;
void send_response() override;
virtual uint64_t get_op() = 0;
int parse_tags();
};
class RGWRoleRead : public RGWRestRole {
public:
RGWRoleRead() = default;
int check_caps(const RGWUserCaps& caps) override;
};
class RGWRoleWrite : public RGWRestRole {
public:
RGWRoleWrite() = default;
int check_caps(const RGWUserCaps& caps) override;
};
class RGWCreateRole : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWCreateRole(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "create_role"; }
RGWOpType get_type() override { return RGW_OP_CREATE_ROLE; }
uint64_t get_op() override { return rgw::IAM::iamCreateRole; }
};
class RGWDeleteRole : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWDeleteRole(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "delete_role"; }
RGWOpType get_type() override { return RGW_OP_DELETE_ROLE; }
uint64_t get_op() override { return rgw::IAM::iamDeleteRole; }
};
class RGWGetRole : public RGWRoleRead {
int _verify_permission(const rgw::sal::RGWRole* role);
public:
RGWGetRole() = default;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "get_role"; }
RGWOpType get_type() override { return RGW_OP_GET_ROLE; }
uint64_t get_op() override { return rgw::IAM::iamGetRole; }
};
class RGWModifyRoleTrustPolicy : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWModifyRoleTrustPolicy(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "modify_role_trust_policy"; }
RGWOpType get_type() override { return RGW_OP_MODIFY_ROLE_TRUST_POLICY; }
uint64_t get_op() override { return rgw::IAM::iamModifyRoleTrustPolicy; }
};
class RGWListRoles : public RGWRoleRead {
public:
RGWListRoles() = default;
int verify_permission(optional_yield y) override;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "list_roles"; }
RGWOpType get_type() override { return RGW_OP_LIST_ROLES; }
uint64_t get_op() override { return rgw::IAM::iamListRoles; }
};
class RGWPutRolePolicy : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWPutRolePolicy(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "put_role_policy"; }
RGWOpType get_type() override { return RGW_OP_PUT_ROLE_POLICY; }
uint64_t get_op() override { return rgw::IAM::iamPutRolePolicy; }
};
class RGWGetRolePolicy : public RGWRoleRead {
public:
RGWGetRolePolicy() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "get_role_policy"; }
RGWOpType get_type() override { return RGW_OP_GET_ROLE_POLICY; }
uint64_t get_op() override { return rgw::IAM::iamGetRolePolicy; }
};
class RGWListRolePolicies : public RGWRoleRead {
public:
RGWListRolePolicies() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "list_role_policies"; }
RGWOpType get_type() override { return RGW_OP_LIST_ROLE_POLICIES; }
uint64_t get_op() override { return rgw::IAM::iamListRolePolicies; }
};
class RGWDeleteRolePolicy : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWDeleteRolePolicy(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "delete_role_policy"; }
RGWOpType get_type() override { return RGW_OP_DELETE_ROLE_POLICY; }
uint64_t get_op() override { return rgw::IAM::iamDeleteRolePolicy; }
};
class RGWTagRole : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWTagRole(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "tag_role"; }
RGWOpType get_type() override { return RGW_OP_TAG_ROLE; }
uint64_t get_op() override { return rgw::IAM::iamTagRole; }
};
class RGWListRoleTags : public RGWRoleRead {
public:
RGWListRoleTags() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "list_role_tags"; }
RGWOpType get_type() override { return RGW_OP_LIST_ROLE_TAGS; }
uint64_t get_op() override { return rgw::IAM::iamListRoleTags; }
};
class RGWUntagRole : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWUntagRole(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "untag_role"; }
RGWOpType get_type() override { return RGW_OP_UNTAG_ROLE; }
uint64_t get_op() override { return rgw::IAM::iamUntagRole; }
};
class RGWUpdateRole : public RGWRoleWrite {
bufferlist bl_post_body;
public:
RGWUpdateRole(const bufferlist& bl_post_body) : bl_post_body(bl_post_body) {};
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "update_role"; }
RGWOpType get_type() override { return RGW_OP_UPDATE_ROLE; }
uint64_t get_op() override { return rgw::IAM::iamUpdateRole; }
};
| 6,347 | 34.071823 | 91 |
h
|
null |
ceph-main/src/rgw/rgw_rest_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 <array>
#include <string.h>
#include <string_view>
#include "common/ceph_crypto.h"
#include "common/split.h"
#include "common/Formatter.h"
#include "common/utf8.h"
#include "common/ceph_json.h"
#include "common/safe_io.h"
#include "common/errno.h"
#include "auth/Crypto.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/tokenizer.hpp>
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#ifdef HAVE_WARN_IMPLICIT_CONST_INT_FLOAT_CONVERSION
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wimplicit-const-int-float-conversion"
#endif
#ifdef HAVE_WARN_IMPLICIT_CONST_INT_FLOAT_CONVERSION
#pragma clang diagnostic pop
#endif
#undef BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <liboath/oath.h>
#include "rgw_rest.h"
#include "rgw_rest_s3.h"
#include "rgw_rest_s3website.h"
#include "rgw_rest_pubsub.h"
#include "rgw_auth_s3.h"
#include "rgw_acl.h"
#include "rgw_policy_s3.h"
#include "rgw_user.h"
#include "rgw_cors.h"
#include "rgw_cors_s3.h"
#include "rgw_tag_s3.h"
#include "rgw_client_io.h"
#include "rgw_keystone.h"
#include "rgw_auth_keystone.h"
#include "rgw_auth_registry.h"
#include "rgw_es_query.h"
#include <typeinfo> // for 'typeid'
#include "rgw_ldap.h"
#include "rgw_token.h"
#include "rgw_rest_role.h"
#include "rgw_crypt.h"
#include "rgw_crypt_sanitize.h"
#include "rgw_rest_user_policy.h"
#include "rgw_zone.h"
#include "rgw_bucket_sync.h"
#include "include/ceph_assert.h"
#include "rgw_role.h"
#include "rgw_rest_sts.h"
#include "rgw_rest_iam.h"
#include "rgw_sts.h"
#include "rgw_sal_rados.h"
#include "rgw_s3select.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
using namespace rgw;
using namespace ceph::crypto;
void list_all_buckets_start(req_state *s)
{
s->formatter->open_array_section_in_ns("ListAllMyBucketsResult", XMLNS_AWS_S3);
}
void list_all_buckets_end(req_state *s)
{
s->formatter->close_section();
}
void dump_bucket(req_state *s, rgw::sal::Bucket& obj)
{
s->formatter->open_object_section("Bucket");
s->formatter->dump_string("Name", obj.get_name());
dump_time(s, "CreationDate", obj.get_creation_time());
s->formatter->close_section();
}
void rgw_get_errno_s3(rgw_http_error *e , int err_no)
{
rgw_http_errors::const_iterator r = rgw_http_s3_errors.find(err_no);
if (r != rgw_http_s3_errors.end()) {
e->http_ret = r->second.first;
e->s3_code = r->second.second;
} else {
e->http_ret = 500;
e->s3_code = "UnknownError";
}
}
static inline std::string get_s3_expiration_header(
req_state* s,
const ceph::real_time& mtime)
{
return rgw::lc::s3_expiration_header(
s, s->object->get_key(), s->tagset, mtime, s->bucket_attrs);
}
static inline bool get_s3_multipart_abort_header(
req_state* s, const ceph::real_time& mtime,
ceph::real_time& date, std::string& rule_id)
{
return rgw::lc::s3_multipart_abort_header(
s, s->object->get_key(), mtime, s->bucket_attrs, date, rule_id);
}
struct response_attr_param {
const char *param;
const char *http_attr;
};
static struct response_attr_param resp_attr_params[] = {
{"response-content-type", "Content-Type"},
{"response-content-language", "Content-Language"},
{"response-expires", "Expires"},
{"response-cache-control", "Cache-Control"},
{"response-content-disposition", "Content-Disposition"},
{"response-content-encoding", "Content-Encoding"},
{NULL, NULL},
};
#define SSE_C_GROUP 1
#define KMS_GROUP 2
int get_encryption_defaults(req_state *s)
{
int meta_sse_group = 0;
constexpr auto sse_c_prefix = "x-amz-server-side-encryption-customer-";
constexpr auto encrypt_attr = "x-amz-server-side-encryption";
constexpr auto context_attr = "x-amz-server-side-encryption-context";
constexpr auto kms_attr = "x-amz-server-side-encryption-aws-kms-key-id";
constexpr auto bucket_key_attr = "x-amz-server-side-encryption-bucket-key-enabled";
bool bucket_configuration_found { false };
bool rest_only { false };
for (auto& kv : s->info.crypt_attribute_map) {
if (kv.first.find(sse_c_prefix) == 0)
meta_sse_group |= SSE_C_GROUP;
else if (kv.first.find(encrypt_attr) == 0)
meta_sse_group |= KMS_GROUP;
}
if (meta_sse_group == (SSE_C_GROUP|KMS_GROUP)) {
s->err.message = "Server side error - can't do sse-c & sse-kms|sse-s3";
return -EINVAL;
}
const auto& buck_attrs = s->bucket_attrs;
auto aiter = buck_attrs.find(RGW_ATTR_BUCKET_ENCRYPTION_POLICY);
RGWBucketEncryptionConfig bucket_encryption_conf;
if (aiter != buck_attrs.end()) {
ldpp_dout(s, 5) << "Found RGW_ATTR_BUCKET_ENCRYPTION_POLICY on "
<< s->bucket_name << dendl;
bufferlist::const_iterator iter{&aiter->second};
try {
bucket_encryption_conf.decode(iter);
bucket_configuration_found = true;
} catch (const buffer::error& e) {
s->err.message = "Server side error - can't decode bucket_encryption_conf";
ldpp_dout(s, 5) << __func__ << "decode bucket_encryption_conf failed" << dendl;
return -EINVAL;
}
}
if (meta_sse_group & SSE_C_GROUP) {
ldpp_dout(s, 20) << "get_encryption_defaults: no defaults cause sse-c forced"
<< dendl;
return 0; // sse-c: no defaults here
}
std::string sse_algorithm { bucket_encryption_conf.sse_algorithm() };
auto kms_master_key_id { bucket_encryption_conf.kms_master_key_id() };
bool bucket_key_enabled { bucket_encryption_conf.bucket_key_enabled() };
bool kms_attr_seen = false;
if (bucket_configuration_found) {
ldpp_dout(s, 5) << "RGW_ATTR_BUCKET_ENCRYPTION ALGO: "
<< sse_algorithm << dendl;
}
auto iter = s->info.crypt_attribute_map.find(encrypt_attr);
if (iter != s->info.crypt_attribute_map.end()) {
ldpp_dout(s, 20) << "get_encryption_defaults: found encrypt_attr " << encrypt_attr << " = " << iter->second << ", setting sse_algorithm to that" << dendl;
rest_only = true;
sse_algorithm = iter->second;
} else if (sse_algorithm != "") {
rgw_set_amz_meta_header(s->info.crypt_attribute_map, encrypt_attr, sse_algorithm, OVERWRITE);
}
iter = s->info.crypt_attribute_map.find(kms_attr);
if (iter != s->info.crypt_attribute_map.end()) {
ldpp_dout(s, 20) << "get_encryption_defaults: found kms_attr " << kms_attr << " = " << iter->second << ", setting kms_attr_seen" << dendl;
if (!rest_only) {
s->err.message = std::string("incomplete rest sse parms: ") + kms_attr + " not valid without kms";
ldpp_dout(s, 5) << __func__ << "argument problem: " << s->err.message << dendl;
return -EINVAL;
}
kms_attr_seen = true;
} else if (!rest_only && kms_master_key_id != "") {
ldpp_dout(s, 20) << "get_encryption_defaults: no kms_attr, but kms_master_key_id = " << kms_master_key_id << ", settig kms_attr_seen" << dendl;
kms_attr_seen = true;
rgw_set_amz_meta_header(s->info.crypt_attribute_map, kms_attr, kms_master_key_id, OVERWRITE);
}
iter = s->info.crypt_attribute_map.find(bucket_key_attr);
if (iter != s->info.crypt_attribute_map.end()) {
ldpp_dout(s, 20) << "get_encryption_defaults: found bucket_key_attr " << bucket_key_attr << " = " << iter->second << ", setting kms_attr_seen" << dendl;
if (!rest_only) {
s->err.message = std::string("incomplete rest sse parms: ") + bucket_key_attr + " not valid without kms";
ldpp_dout(s, 5) << __func__ << "argument problem: " << s->err.message << dendl;
return -EINVAL;
}
kms_attr_seen = true;
} else if (!rest_only && bucket_key_enabled) {
ldpp_dout(s, 20) << "get_encryption_defaults: no bucket_key_attr, but bucket_key_enabled, setting kms_attr_seen" << dendl;
kms_attr_seen = true;
rgw_set_amz_meta_header(s->info.crypt_attribute_map, bucket_key_attr, "true", OVERWRITE);
}
iter = s->info.crypt_attribute_map.find(context_attr);
if (iter != s->info.crypt_attribute_map.end()) {
ldpp_dout(s, 20) << "get_encryption_defaults: found context_attr " << context_attr << " = " << iter->second << ", setting kms_attr_seen" << dendl;
if (!rest_only) {
s->err.message = std::string("incomplete rest sse parms: ") + context_attr + " not valid without kms";
ldpp_dout(s, 5) << __func__ << "argument problem: " << s->err.message << dendl;
return -EINVAL;
}
kms_attr_seen = true;
}
if (kms_attr_seen && sse_algorithm == "") {
ldpp_dout(s, 20) << "get_encryption_defaults: kms_attr but no algorithm, defaulting to aws_kms" << dendl;
sse_algorithm = "aws:kms";
}
for (const auto& kv: s->info.crypt_attribute_map) {
ldpp_dout(s, 20) << "get_encryption_defaults: final map: " << kv.first << " = " << kv.second << dendl;
}
ldpp_dout(s, 20) << "get_encryption_defaults: kms_attr_seen is " << kms_attr_seen << " and sse_algorithm is " << sse_algorithm << dendl;
if (kms_attr_seen && sse_algorithm != "aws:kms") {
s->err.message = "algorithm <" + sse_algorithm + "> but got sse-kms attributes";
return -EINVAL;
}
return 0;
}
int RGWGetObj_ObjStore_S3Website::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) {
map<string, bufferlist>::iterator iter;
iter = attrs.find(RGW_ATTR_AMZ_WEBSITE_REDIRECT_LOCATION);
if (iter != attrs.end()) {
bufferlist &bl = iter->second;
s->redirect = bl.c_str();
s->err.http_ret = 301;
ldpp_dout(this, 20) << __CEPH_ASSERT_FUNCTION << " redirecting per x-amz-website-redirect-location=" << s->redirect << dendl;
op_ret = -ERR_WEBSITE_REDIRECT;
set_req_state_err(s, op_ret);
dump_errno(s);
dump_content_length(s, 0);
dump_redirect(s, s->redirect);
end_header(s, this);
return op_ret;
} else {
return RGWGetObj_ObjStore_S3::send_response_data(bl, bl_ofs, bl_len);
}
}
int RGWGetObj_ObjStore_S3Website::send_response_data_error(optional_yield y)
{
return RGWGetObj_ObjStore_S3::send_response_data_error(y);
}
int RGWGetObj_ObjStore_S3::get_params(optional_yield y)
{
// for multisite sync requests, only read the slo manifest itself, rather than
// all of the data from its parts. the parts will sync as separate objects
skip_manifest = s->info.args.exists(RGW_SYS_PARAM_PREFIX "sync-manifest");
// multisite sync requests should fetch encrypted data, along with the
// attributes needed to support decryption on the other zone
if (s->system_request) {
skip_decrypt = s->info.args.exists(RGW_SYS_PARAM_PREFIX "skip-decrypt");
}
// multisite sync requests should fetch cloudtiered objects
sync_cloudtiered = s->info.args.exists(RGW_SYS_PARAM_PREFIX "sync-cloudtiered");
dst_zone_trace = s->info.args.get(RGW_SYS_PARAM_PREFIX "if-not-replicated-to");
get_torrent = s->info.args.exists("torrent");
return RGWGetObj_ObjStore::get_params(y);
}
int RGWGetObj_ObjStore_S3::send_response_data_error(optional_yield y)
{
bufferlist bl;
return send_response_data(bl, 0 , 0);
}
template <class T>
int decode_attr_bl_single_value(map<string, bufferlist>& attrs, const char *attr_name, T *result, T def_val)
{
map<string, bufferlist>::iterator iter = attrs.find(attr_name);
if (iter == attrs.end()) {
*result = def_val;
return 0;
}
bufferlist& bl = iter->second;
if (bl.length() == 0) {
*result = def_val;
return 0;
}
auto bliter = bl.cbegin();
try {
decode(*result, bliter);
} catch (buffer::error& err) {
return -EIO;
}
return 0;
}
inline bool str_has_cntrl(const std::string s) {
return std::any_of(s.begin(), s.end(), ::iscntrl);
}
inline bool str_has_cntrl(const char* s) {
std::string _s(s);
return str_has_cntrl(_s);
}
int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,
off_t bl_len)
{
const char *content_type = NULL;
string content_type_str;
map<string, string> response_attrs;
map<string, string>::iterator riter;
bufferlist metadata_bl;
string expires = get_s3_expiration_header(s, lastmod);
if (sent_header)
goto send_data;
if (custom_http_ret) {
set_req_state_err(s, 0);
dump_errno(s, custom_http_ret);
} else {
set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT
: op_ret);
dump_errno(s);
}
if (op_ret)
goto done;
if (range_str)
dump_range(s, start, end, s->obj_size);
if (s->system_request &&
s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) {
dump_header(s, "Rgwx-Object-Size", (long long)total_len);
if (rgwx_stat) {
/*
* in this case, we're not returning the object's content, only the prepended
* extra metadata
*/
total_len = 0;
}
/* JSON encode object metadata */
JSONFormatter jf;
jf.open_object_section("obj_metadata");
encode_json("attrs", attrs, &jf);
utime_t ut(lastmod);
encode_json("mtime", ut, &jf);
jf.close_section();
stringstream ss;
jf.flush(ss);
metadata_bl.append(ss.str());
dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length());
total_len += metadata_bl.length();
}
if (s->system_request && !real_clock::is_zero(lastmod)) {
/* we end up dumping mtime in two different methods, a bit redundant */
dump_epoch_header(s, "Rgwx-Mtime", lastmod);
uint64_t pg_ver = 0;
int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);
if (r < 0) {
ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl;
}
dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver);
uint32_t source_zone_short_id = 0;
r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);
if (r < 0) {
ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl;
}
if (source_zone_short_id != 0) {
dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id);
}
}
for (auto &it : crypt_http_responses)
dump_header(s, it.first, it.second);
dump_content_length(s, total_len);
dump_last_modified(s, lastmod);
dump_header_if_nonempty(s, "x-amz-version-id", version_id);
dump_header_if_nonempty(s, "x-amz-expiration", expires);
if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {
dump_header(s, "x-rgw-object-type", "Appendable");
dump_header(s, "x-rgw-next-append-position", s->obj_size);
} else {
dump_header(s, "x-rgw-object-type", "Normal");
}
// replication status
if (auto i = attrs.find(RGW_ATTR_OBJ_REPLICATION_STATUS);
i != attrs.end()) {
dump_header(s, "x-amz-replication-status", i->second);
}
if (auto i = attrs.find(RGW_ATTR_OBJ_REPLICATION_TRACE);
i != attrs.end()) {
try {
std::vector<rgw_zone_set_entry> zones;
auto p = i->second.cbegin();
decode(zones, p);
for (const auto& zone : zones) {
dump_header(s, "x-rgw-replicated-from", zone.to_str());
}
} catch (const buffer::error&) {} // omit x-rgw-replicated-from headers
}
if (! op_ret) {
if (! lo_etag.empty()) {
/* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly
* legit to perform GET on them through S3 API. In such situation,
* a client should receive the composited content with corresponding
* etag value. */
dump_etag(s, lo_etag);
} else {
auto iter = attrs.find(RGW_ATTR_ETAG);
if (iter != attrs.end()) {
dump_etag(s, iter->second.to_str());
}
}
for (struct response_attr_param *p = resp_attr_params; p->param; p++) {
bool exists;
string val = s->info.args.get(p->param, &exists);
if (exists) {
/* reject unauthenticated response header manipulation, see
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */
if (s->auth.identity->is_anonymous()) {
return -ERR_INVALID_REQUEST;
}
/* HTTP specification says no control characters should be present in
* header values: https://tools.ietf.org/html/rfc7230#section-3.2
* field-vchar = VCHAR / obs-text
*
* Failure to validate this permits a CRLF injection in HTTP headers,
* whereas S3 GetObject only permits specific headers.
*/
if(str_has_cntrl(val)) {
/* TODO: return a more distinct error in future;
* stating what the problem is */
return -ERR_INVALID_REQUEST;
}
if (strcmp(p->param, "response-content-type") != 0) {
response_attrs[p->http_attr] = val;
} else {
content_type_str = val;
content_type = content_type_str.c_str();
}
}
}
for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {
const char *name = iter->first.c_str();
map<string, string>::iterator aiter = rgw_to_http_attrs.find(name);
if (aiter != rgw_to_http_attrs.end()) {
if (response_attrs.count(aiter->second) == 0) {
/* Was not already overridden by a response param. */
size_t len = iter->second.length();
string s(iter->second.c_str(), len);
while (len && !s[len - 1]) {
--len;
s.resize(len);
}
response_attrs[aiter->second] = s;
}
} else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {
/* Special handling for content_type. */
if (!content_type) {
content_type_str = rgw_bl_str(iter->second);
content_type = content_type_str.c_str();
}
} else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {
// this attr has an extra length prefix from encode() in prior versions
dump_header(s, "X-Object-Meta-Static-Large-Object", "True");
} else if (strncmp(name, RGW_ATTR_META_PREFIX,
sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {
/* User custom metadata. */
name += sizeof(RGW_ATTR_PREFIX) - 1;
dump_header(s, name, iter->second);
} else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {
RGWObjTags obj_tags;
try{
auto it = iter->second.cbegin();
obj_tags.decode(it);
} catch (buffer::error &err) {
ldpp_dout(this,0) << "Error caught buffer::error couldn't decode TagSet " << dendl;
}
dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());
} else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){
RGWObjectRetention retention;
try {
decode(retention, iter->second);
dump_header(s, "x-amz-object-lock-mode", retention.get_mode());
string date = ceph::to_iso_8601(retention.get_retain_until_date());
dump_header(s, "x-amz-object-lock-retain-until-date", date.c_str());
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl;
}
} else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {
RGWObjectLegalHold legal_hold;
try {
decode(legal_hold, iter->second);
dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status());
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl;
}
}
}
}
done:
for (riter = response_attrs.begin(); riter != response_attrs.end();
++riter) {
dump_header(s, riter->first, riter->second);
}
if (op_ret == -ERR_NOT_MODIFIED) {
end_header(s, this);
} else {
if (!content_type)
content_type = "binary/octet-stream";
end_header(s, this, content_type);
}
if (metadata_bl.length()) {
dump_body(s, metadata_bl);
}
sent_header = true;
send_data:
if (get_data && !op_ret) {
int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);
if (r < 0)
return r;
}
return 0;
}
int RGWGetObj_ObjStore_S3::get_decrypt_filter(std::unique_ptr<RGWGetObj_Filter> *filter, RGWGetObj_Filter* cb, bufferlist* manifest_bl)
{
if (skip_decrypt) { // bypass decryption for multisite sync requests
return 0;
}
int res = 0;
std::unique_ptr<BlockCrypt> block_crypt;
res = rgw_s3_prepare_decrypt(s, attrs, &block_crypt, crypt_http_responses);
if (res == 0) {
if (block_crypt != nullptr) {
auto f = std::make_unique<RGWGetObj_BlockDecrypt>(s, s->cct, cb, std::move(block_crypt), s->yield);
if (manifest_bl != nullptr) {
res = f->read_manifest(this, *manifest_bl);
if (res == 0) {
*filter = std::move(f);
}
}
}
}
return res;
}
int RGWGetObj_ObjStore_S3::verify_requester(const rgw::auth::StrategyRegistry& auth_registry, optional_yield y)
{
int ret = -EINVAL;
ret = RGWOp::verify_requester(auth_registry, y);
if(!s->user->get_caps().check_cap("amz-cache", RGW_CAP_READ) && !ret && s->info.env->exists("HTTP_X_AMZ_CACHE"))
ret = override_range_hdr(auth_registry, y);
return ret;
}
int RGWGetObj_ObjStore_S3::override_range_hdr(const rgw::auth::StrategyRegistry& auth_registry, optional_yield y)
{
int ret = -EINVAL;
ldpp_dout(this, 10) << "cache override headers" << dendl;
RGWEnv* rgw_env = const_cast<RGWEnv *>(s->info.env);
const char* backup_range = rgw_env->get("HTTP_RANGE");
const char hdrs_split[2] = {(char)178,'\0'};
const char kv_split[2] = {(char)177,'\0'};
const char* cache_hdr = rgw_env->get("HTTP_X_AMZ_CACHE");
for (std::string_view hdr : ceph::split(cache_hdr, hdrs_split)) {
auto kv = ceph::split(hdr, kv_split);
auto k = kv.begin();
if (std::distance(k, kv.end()) != 2) {
return -EINVAL;
}
auto v = std::next(k);
std::string key = "HTTP_";
key.append(*k);
boost::replace_all(key, "-", "_");
ldpp_dout(this, 10) << "after splitting cache kv key: " << key << " " << *v << dendl;
rgw_env->set(std::move(key), std::string(*v));
}
ret = RGWOp::verify_requester(auth_registry, y);
if(!ret && backup_range) {
rgw_env->set("HTTP_RANGE",backup_range);
} else {
rgw_env->remove("HTTP_RANGE");
}
return ret;
}
void RGWGetObjTags_ObjStore_S3::send_response_data(bufferlist& bl)
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (!op_ret){
s->formatter->open_object_section_in_ns("Tagging", XMLNS_AWS_S3);
s->formatter->open_object_section("TagSet");
if (has_tags){
RGWObjTagSet_S3 tagset;
auto iter = bl.cbegin();
try {
tagset.decode(iter);
} catch (buffer::error& err) {
ldpp_dout(this,0) << "ERROR: caught buffer::error, couldn't decode TagSet" << dendl;
op_ret= -EIO;
return;
}
tagset.dump_xml(s->formatter);
}
s->formatter->close_section();
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
int RGWPutObjTags_ObjStore_S3::get_params(optional_yield y)
{
RGWXMLParser parser;
if (!parser.init()){
return -EINVAL;
}
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r = 0;
bufferlist data;
std::tie(r, data) = read_all_input(s, max_size, false);
if (r < 0)
return r;
if (!parser.parse(data.c_str(), data.length(), 1)) {
return -ERR_MALFORMED_XML;
}
RGWObjTagging_S3 tagging;
try {
RGWXMLDecoder::decode_xml("Tagging", tagging, &parser);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "Malformed tagging request: " << err << dendl;
return -ERR_MALFORMED_XML;
}
RGWObjTags obj_tags;
r = tagging.rebuild(obj_tags);
if (r < 0)
return r;
obj_tags.encode(tags_bl);
ldpp_dout(this, 20) << "Read " << obj_tags.count() << "tags" << dendl;
return 0;
}
void RGWPutObjTags_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWDeleteObjTags_ObjStore_S3::send_response()
{
if (op_ret == 0){
op_ret = STATUS_NO_CONTENT;
}
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWGetBucketTags_ObjStore_S3::send_response_data(bufferlist& bl)
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (!op_ret) {
s->formatter->open_object_section_in_ns("Tagging", XMLNS_AWS_S3);
s->formatter->open_object_section("TagSet");
if (has_tags){
RGWObjTagSet_S3 tagset;
auto iter = bl.cbegin();
try {
tagset.decode(iter);
} catch (buffer::error& err) {
ldpp_dout(this,0) << "ERROR: caught buffer::error, couldn't decode TagSet" << dendl;
op_ret= -EIO;
return;
}
tagset.dump_xml(s->formatter);
}
s->formatter->close_section();
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
int RGWPutBucketTags_ObjStore_S3::get_params(const DoutPrefixProvider *dpp, optional_yield y)
{
RGWXMLParser parser;
if (!parser.init()){
return -EINVAL;
}
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r = 0;
bufferlist data;
std::tie(r, data) = read_all_input(s, max_size, false);
if (r < 0)
return r;
if (!parser.parse(data.c_str(), data.length(), 1)) {
return -ERR_MALFORMED_XML;
}
RGWObjTagging_S3 tagging;
try {
RGWXMLDecoder::decode_xml("Tagging", tagging, &parser);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(dpp, 5) << "Malformed tagging request: " << err << dendl;
return -ERR_MALFORMED_XML;
}
RGWObjTags obj_tags(50); // A tag set can contain as many as 50 tags, or it can be empty.
r = tagging.rebuild(obj_tags);
if (r < 0)
return r;
obj_tags.encode(tags_bl);
ldpp_dout(dpp, 20) << "Read " << obj_tags.count() << "tags" << dendl;
// forward bucket tags requests to meta master zone
if (!driver->is_meta_master()) {
/* only need to keep this data around if we're not meta master */
in_data = std::move(data);
}
return 0;
}
void RGWPutBucketTags_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWDeleteBucketTags_ObjStore_S3::send_response()
{
// A successful DeleteBucketTagging should
// return a 204 status code.
if (op_ret == 0)
op_ret = STATUS_NO_CONTENT;
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
namespace {
bool is_valid_status(const string& s) {
return (s == "Enabled" ||
s == "Disabled");
}
static string enabled_group_id = "s3-bucket-replication:enabled";
static string disabled_group_id = "s3-bucket-replication:disabled";
struct ReplicationConfiguration {
string role;
struct Rule {
struct DeleteMarkerReplication {
string status;
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Status", status, obj);
}
void dump_xml(Formatter *f) const {
encode_xml("Status", status, f);
}
bool is_valid(CephContext *cct) const {
bool result = is_valid_status(status);
if (!result) {
ldout(cct, 5) << "NOTICE: bad status provided in DeleteMarkerReplication element (status=" << status << ")" << dendl;
}
return result;
}
};
struct Source { /* rgw extension */
std::vector<string> zone_names;
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Zone", zone_names, obj);
}
void dump_xml(Formatter *f) const {
encode_xml("Zone", zone_names, f);
}
};
struct Destination {
struct AccessControlTranslation {
string owner;
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Owner", owner, obj);
}
void dump_xml(Formatter *f) const {
encode_xml("Owner", owner, f);
}
};
std::optional<AccessControlTranslation> acl_translation;
std::optional<string> account;
string bucket;
std::optional<string> storage_class;
std::vector<string> zone_names;
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("AccessControlTranslation", acl_translation, obj);
RGWXMLDecoder::decode_xml("Account", account, obj);
if (account && account->empty()) {
account.reset();
}
RGWXMLDecoder::decode_xml("Bucket", bucket, obj);
RGWXMLDecoder::decode_xml("StorageClass", storage_class, obj);
if (storage_class && storage_class->empty()) {
storage_class.reset();
}
RGWXMLDecoder::decode_xml("Zone", zone_names, obj); /* rgw extension */
}
void dump_xml(Formatter *f) const {
encode_xml("AccessControlTranslation", acl_translation, f);
encode_xml("Account", account, f);
encode_xml("Bucket", bucket, f);
encode_xml("StorageClass", storage_class, f);
encode_xml("Zone", zone_names, f);
}
};
struct Filter {
struct Tag {
string key;
string value;
bool empty() const {
return key.empty() && value.empty();
}
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Key", key, obj);
RGWXMLDecoder::decode_xml("Value", value, obj);
};
void dump_xml(Formatter *f) const {
encode_xml("Key", key, f);
encode_xml("Value", value, f);
}
};
struct AndElements {
std::optional<string> prefix;
std::vector<Tag> tags;
bool empty() const {
return !prefix &&
(tags.size() == 0);
}
void decode_xml(XMLObj *obj) {
std::vector<Tag> _tags;
RGWXMLDecoder::decode_xml("Prefix", prefix, obj);
if (prefix && prefix->empty()) {
prefix.reset();
}
RGWXMLDecoder::decode_xml("Tag", _tags, obj);
for (auto& t : _tags) {
if (!t.empty()) {
tags.push_back(std::move(t));
}
}
};
void dump_xml(Formatter *f) const {
encode_xml("Prefix", prefix, f);
encode_xml("Tag", tags, f);
}
};
std::optional<string> prefix;
std::optional<Tag> tag;
std::optional<AndElements> and_elements;
bool empty() const {
return (!prefix && !tag && !and_elements);
}
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Prefix", prefix, obj);
if (prefix && prefix->empty()) {
prefix.reset();
}
RGWXMLDecoder::decode_xml("Tag", tag, obj);
if (tag && tag->empty()) {
tag.reset();
}
RGWXMLDecoder::decode_xml("And", and_elements, obj);
if (and_elements && and_elements->empty()) {
and_elements.reset();
}
};
void dump_xml(Formatter *f) const {
encode_xml("Prefix", prefix, f);
encode_xml("Tag", tag, f);
encode_xml("And", and_elements, f);
}
bool is_valid(CephContext *cct) const {
if (tag && prefix) {
ldout(cct, 5) << "NOTICE: both tag and prefix were provided in replication filter rule" << dendl;
return false;
}
if (and_elements) {
if (prefix && and_elements->prefix) {
ldout(cct, 5) << "NOTICE: too many prefixes were provided in re" << dendl;
return false;
}
}
return true;
};
int to_sync_pipe_filter(CephContext *cct,
rgw_sync_pipe_filter *f) const {
if (!is_valid(cct)) {
return -EINVAL;
}
if (prefix) {
f->prefix = *prefix;
}
if (tag) {
f->tags.insert(rgw_sync_pipe_filter_tag(tag->key, tag->value));
}
if (and_elements) {
if (and_elements->prefix) {
f->prefix = *and_elements->prefix;
}
for (auto& t : and_elements->tags) {
f->tags.insert(rgw_sync_pipe_filter_tag(t.key, t.value));
}
}
return 0;
}
void from_sync_pipe_filter(const rgw_sync_pipe_filter& f) {
if (f.prefix && f.tags.empty()) {
prefix = f.prefix;
return;
}
if (f.prefix) {
and_elements.emplace();
and_elements->prefix = f.prefix;
} else if (f.tags.size() == 1) {
auto iter = f.tags.begin();
if (iter == f.tags.end()) {
/* should never happen */
return;
}
auto& t = *iter;
tag.emplace();
tag->key = t.key;
tag->value = t.value;
return;
}
if (f.tags.empty()) {
return;
}
if (!and_elements) {
and_elements.emplace();
}
for (auto& t : f.tags) {
auto& tag = and_elements->tags.emplace_back();
tag.key = t.key;
tag.value = t.value;
}
}
};
set<rgw_zone_id> get_zone_ids_from_names(rgw::sal::Driver* driver,
const vector<string>& zone_names) const {
set<rgw_zone_id> ids;
for (auto& name : zone_names) {
std::unique_ptr<rgw::sal::Zone> zone;
int ret = driver->get_zone()->get_zonegroup().get_zone_by_name(name, &zone);
if (ret >= 0) {
rgw_zone_id id = zone->get_id();
ids.insert(std::move(id));
}
}
return ids;
}
vector<string> get_zone_names_from_ids(rgw::sal::Driver* driver,
const set<rgw_zone_id>& zone_ids) const {
vector<string> names;
for (auto& id : zone_ids) {
std::unique_ptr<rgw::sal::Zone> zone;
int ret = driver->get_zone()->get_zonegroup().get_zone_by_id(id.id, &zone);
if (ret >= 0) {
names.emplace_back(zone->get_name());
}
}
return names;
}
std::optional<DeleteMarkerReplication> delete_marker_replication;
std::optional<Source> source;
Destination destination;
std::optional<Filter> filter;
string id;
int32_t priority;
string status;
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("DeleteMarkerReplication", delete_marker_replication, obj);
RGWXMLDecoder::decode_xml("Source", source, obj);
RGWXMLDecoder::decode_xml("Destination", destination, obj);
RGWXMLDecoder::decode_xml("ID", id, obj);
std::optional<string> prefix;
RGWXMLDecoder::decode_xml("Prefix", prefix, obj);
if (prefix) {
filter.emplace();
filter->prefix = prefix;
}
if (!filter) {
RGWXMLDecoder::decode_xml("Filter", filter, obj);
} else {
/* don't want to have filter reset because it might have been initialized
* when decoding prefix
*/
RGWXMLDecoder::decode_xml("Filter", *filter, obj);
}
RGWXMLDecoder::decode_xml("Priority", priority, obj);
RGWXMLDecoder::decode_xml("Status", status, obj);
}
void dump_xml(Formatter *f) const {
encode_xml("DeleteMarkerReplication", delete_marker_replication, f);
encode_xml("Source", source, f);
encode_xml("Destination", destination, f);
encode_xml("Filter", filter, f);
encode_xml("ID", id, f);
encode_xml("Priority", priority, f);
encode_xml("Status", status, f);
}
bool is_valid(CephContext *cct) const {
if (!is_valid_status(status)) {
ldout(cct, 5) << "NOTICE: bad status provided in rule (status=" << status << ")" << dendl;
return false;
}
if ((filter && !filter->is_valid(cct)) ||
(delete_marker_replication && !delete_marker_replication->is_valid(cct))) {
return false;
}
return true;
}
int to_sync_policy_pipe(req_state *s, rgw::sal::Driver* driver,
rgw_sync_bucket_pipes *pipe,
bool *enabled) const {
if (!is_valid(s->cct)) {
return -EINVAL;
}
pipe->id = id;
pipe->params.priority = priority;
const auto& user_id = s->user->get_id();
rgw_bucket_key dest_bk(user_id.tenant,
destination.bucket);
if (source && !source->zone_names.empty()) {
pipe->source.zones = get_zone_ids_from_names(driver, source->zone_names);
} else {
pipe->source.set_all_zones(true);
}
if (!destination.zone_names.empty()) {
pipe->dest.zones = get_zone_ids_from_names(driver, destination.zone_names);
} else {
pipe->dest.set_all_zones(true);
}
pipe->dest.bucket.emplace(dest_bk);
if (filter) {
int r = filter->to_sync_pipe_filter(s->cct, &pipe->params.source.filter);
if (r < 0) {
return r;
}
}
if (destination.acl_translation) {
rgw_user u;
u.tenant = user_id.tenant;
u.from_str(destination.acl_translation->owner); /* explicit tenant will override tenant,
otherwise will inherit it from s->user */
pipe->params.dest.acl_translation.emplace();
pipe->params.dest.acl_translation->owner = u;
}
pipe->params.dest.storage_class = destination.storage_class;
*enabled = (status == "Enabled");
pipe->params.mode = rgw_sync_pipe_params::Mode::MODE_USER;
pipe->params.user = user_id.to_str();
return 0;
}
void from_sync_policy_pipe(rgw::sal::Driver* driver,
const rgw_sync_bucket_pipes& pipe,
bool enabled) {
id = pipe.id;
status = (enabled ? "Enabled" : "Disabled");
priority = pipe.params.priority;
if (pipe.source.all_zones) {
source.reset();
} else if (pipe.source.zones) {
source.emplace();
source->zone_names = get_zone_names_from_ids(driver, *pipe.source.zones);
}
if (!pipe.dest.all_zones &&
pipe.dest.zones) {
destination.zone_names = get_zone_names_from_ids(driver, *pipe.dest.zones);
}
if (pipe.params.dest.acl_translation) {
destination.acl_translation.emplace();
destination.acl_translation->owner = pipe.params.dest.acl_translation->owner.to_str();
}
if (pipe.params.dest.storage_class) {
destination.storage_class = *pipe.params.dest.storage_class;
}
if (pipe.dest.bucket) {
destination.bucket = pipe.dest.bucket->get_key();
}
filter.emplace();
filter->from_sync_pipe_filter(pipe.params.source.filter);
if (filter->empty()) {
filter.reset();
}
}
};
std::vector<Rule> rules;
void decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("Role", role, obj);
RGWXMLDecoder::decode_xml("Rule", rules, obj);
}
void dump_xml(Formatter *f) const {
encode_xml("Role", role, f);
encode_xml("Rule", rules, f);
}
int to_sync_policy_groups(req_state *s, rgw::sal::Driver* driver,
vector<rgw_sync_policy_group> *result) const {
result->resize(2);
rgw_sync_policy_group& enabled_group = (*result)[0];
rgw_sync_policy_group& disabled_group = (*result)[1];
enabled_group.id = enabled_group_id;
enabled_group.status = rgw_sync_policy_group::Status::ENABLED;
disabled_group.id = disabled_group_id;
disabled_group.status = rgw_sync_policy_group::Status::ALLOWED; /* not enabled, not forbidden */
for (auto& rule : rules) {
rgw_sync_bucket_pipes pipe;
bool enabled;
int r = rule.to_sync_policy_pipe(s, driver, &pipe, &enabled);
if (r < 0) {
ldpp_dout(s, 5) << "NOTICE: failed to convert replication configuration into sync policy pipe (rule.id=" << rule.id << "): " << cpp_strerror(-r) << dendl;
return r;
}
if (enabled) {
enabled_group.pipes.emplace_back(std::move(pipe));
} else {
disabled_group.pipes.emplace_back(std::move(pipe));
}
}
return 0;
}
void from_sync_policy_group(rgw::sal::Driver* driver,
const rgw_sync_policy_group& group) {
bool enabled = (group.status == rgw_sync_policy_group::Status::ENABLED);
for (auto& pipe : group.pipes) {
auto& rule = rules.emplace_back();
rule.from_sync_policy_pipe(driver, pipe, enabled);
}
}
};
}
void RGWGetBucketReplication_ObjStore_S3::send_response_data()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
ReplicationConfiguration conf;
if (s->bucket->get_info().sync_policy) {
auto policy = s->bucket->get_info().sync_policy;
auto iter = policy->groups.find(enabled_group_id);
if (iter != policy->groups.end()) {
conf.from_sync_policy_group(driver, iter->second);
}
iter = policy->groups.find(disabled_group_id);
if (iter != policy->groups.end()) {
conf.from_sync_policy_group(driver, iter->second);
}
}
if (!op_ret) {
s->formatter->open_object_section_in_ns("ReplicationConfiguration", XMLNS_AWS_S3);
conf.dump_xml(s->formatter);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
int RGWPutBucketReplication_ObjStore_S3::get_params(optional_yield y)
{
RGWXMLParser parser;
if (!parser.init()){
return -EINVAL;
}
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r = 0;
bufferlist data;
std::tie(r, data) = read_all_input(s, max_size, false);
if (r < 0)
return r;
if (!parser.parse(data.c_str(), data.length(), 1)) {
return -ERR_MALFORMED_XML;
}
ReplicationConfiguration conf;
try {
RGWXMLDecoder::decode_xml("ReplicationConfiguration", conf, &parser);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "Malformed tagging request: " << err << dendl;
return -ERR_MALFORMED_XML;
}
r = conf.to_sync_policy_groups(s, driver, &sync_policy_groups);
if (r < 0) {
return r;
}
// forward requests to meta master zone
if (!driver->is_meta_master()) {
/* only need to keep this data around if we're not meta master */
in_data = std::move(data);
}
return 0;
}
void RGWPutBucketReplication_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWDeleteBucketReplication_ObjStore_S3::update_sync_policy(rgw_sync_policy_info *policy)
{
policy->groups.erase(enabled_group_id);
policy->groups.erase(disabled_group_id);
}
void RGWDeleteBucketReplication_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWListBuckets_ObjStore_S3::send_response_begin(bool has_buckets)
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
dump_start(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, NULL, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
if (! op_ret) {
list_all_buckets_start(s);
dump_owner(s, s->user->get_id(), s->user->get_display_name());
s->formatter->open_array_section("Buckets");
sent_data = true;
}
}
void RGWListBuckets_ObjStore_S3::send_response_data(rgw::sal::BucketList& buckets)
{
if (!sent_data)
return;
auto& m = buckets.get_buckets();
for (auto iter = m.begin(); iter != m.end(); ++iter) {
auto& bucket = iter->second;
dump_bucket(s, *bucket);
}
rgw_flush_formatter(s, s->formatter);
}
void RGWListBuckets_ObjStore_S3::send_response_end()
{
if (sent_data) {
s->formatter->close_section();
list_all_buckets_end(s);
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
int RGWGetUsage_ObjStore_S3::get_params(optional_yield y)
{
start_date = s->info.args.get("start-date");
end_date = s->info.args.get("end-date");
return 0;
}
static void dump_usage_categories_info(Formatter *formatter, const rgw_usage_log_entry& entry, map<string, bool> *categories)
{
formatter->open_array_section("categories");
map<string, rgw_usage_data>::const_iterator uiter;
for (uiter = entry.usage_map.begin(); uiter != entry.usage_map.end(); ++uiter) {
if (categories && !categories->empty() && !categories->count(uiter->first))
continue;
const rgw_usage_data& usage = uiter->second;
formatter->open_object_section("Entry");
encode_json("Category", uiter->first, formatter);
encode_json("BytesSent", usage.bytes_sent, formatter);
encode_json("BytesReceived", usage.bytes_received, formatter);
encode_json("Ops", usage.ops, formatter);
encode_json("SuccessfulOps", usage.successful_ops, formatter);
formatter->close_section(); // Entry
}
formatter->close_section(); // Category
}
static void dump_usage_bucket_info(Formatter *formatter, const std::string& name, const bucket_meta_entry& entry)
{
formatter->open_object_section("Entry");
encode_json("Bucket", name, formatter);
encode_json("Bytes", entry.size, formatter);
encode_json("Bytes_Rounded", entry.size_rounded, formatter);
formatter->close_section(); // entry
}
void RGWGetUsage_ObjStore_S3::send_response()
{
if (op_ret < 0)
set_req_state_err(s, op_ret);
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
dump_start(s);
if (op_ret < 0)
return;
Formatter *formatter = s->formatter;
string last_owner;
bool user_section_open = false;
formatter->open_object_section("Usage");
if (show_log_entries) {
formatter->open_array_section("Entries");
}
map<rgw_user_bucket, rgw_usage_log_entry>::iterator iter;
for (iter = usage.begin(); iter != usage.end(); ++iter) {
const rgw_user_bucket& ub = iter->first;
const rgw_usage_log_entry& entry = iter->second;
if (show_log_entries) {
if (ub.user.compare(last_owner) != 0) {
if (user_section_open) {
formatter->close_section();
formatter->close_section();
}
formatter->open_object_section("User");
formatter->dump_string("Owner", ub.user);
formatter->open_array_section("Buckets");
user_section_open = true;
last_owner = ub.user;
}
formatter->open_object_section("Bucket");
formatter->dump_string("Bucket", ub.bucket);
utime_t ut(entry.epoch, 0);
ut.gmtime(formatter->dump_stream("Time"));
formatter->dump_int("Epoch", entry.epoch);
dump_usage_categories_info(formatter, entry, &categories);
formatter->close_section(); // bucket
}
summary_map[ub.user].aggregate(entry, &categories);
}
if (show_log_entries) {
if (user_section_open) {
formatter->close_section(); // buckets
formatter->close_section(); //user
}
formatter->close_section(); // entries
}
if (show_log_sum) {
formatter->open_array_section("Summary");
map<string, rgw_usage_log_entry>::iterator siter;
for (siter = summary_map.begin(); siter != summary_map.end(); ++siter) {
const rgw_usage_log_entry& entry = siter->second;
formatter->open_object_section("User");
formatter->dump_string("User", siter->first);
dump_usage_categories_info(formatter, entry, &categories);
rgw_usage_data total_usage;
entry.sum(total_usage, categories);
formatter->open_object_section("Total");
encode_json("BytesSent", total_usage.bytes_sent, formatter);
encode_json("BytesReceived", total_usage.bytes_received, formatter);
encode_json("Ops", total_usage.ops, formatter);
encode_json("SuccessfulOps", total_usage.successful_ops, formatter);
formatter->close_section(); // total
formatter->close_section(); // user
}
if (s->cct->_conf->rgw_rest_getusage_op_compat) {
formatter->open_object_section("Stats");
}
// send info about quota config
auto user_info = s->user->get_info();
encode_json("QuotaMaxBytes", user_info.quota.user_quota.max_size, formatter);
encode_json("QuotaMaxBuckets", user_info.max_buckets, formatter);
encode_json("QuotaMaxObjCount", user_info.quota.user_quota.max_objects, formatter);
encode_json("QuotaMaxBytesPerBucket", user_info.quota.bucket_quota.max_objects, formatter);
encode_json("QuotaMaxObjCountPerBucket", user_info.quota.bucket_quota.max_size, formatter);
// send info about user's capacity utilization
encode_json("TotalBytes", stats.size, formatter);
encode_json("TotalBytesRounded", stats.size_rounded, formatter);
encode_json("TotalEntries", stats.num_objects, formatter);
if (s->cct->_conf->rgw_rest_getusage_op_compat) {
formatter->close_section(); //Stats
}
formatter->close_section(); // summary
}
formatter->open_array_section("CapacityUsed");
formatter->open_object_section("User");
formatter->open_array_section("Buckets");
for (const auto& biter : buckets_usage) {
const bucket_meta_entry& entry = biter.second;
dump_usage_bucket_info(formatter, biter.first, entry);
}
formatter->close_section(); // Buckets
formatter->close_section(); // User
formatter->close_section(); // CapacityUsed
formatter->close_section(); // usage
rgw_flush_formatter_and_reset(s, s->formatter);
}
int RGWListBucket_ObjStore_S3::get_common_params()
{
list_versions = s->info.args.exists("versions");
prefix = s->info.args.get("prefix");
// non-standard
s->info.args.get_bool("allow-unordered", &allow_unordered, false);
delimiter = s->info.args.get("delimiter");
max_keys = s->info.args.get("max-keys");
op_ret = parse_max_keys();
if (op_ret < 0) {
return op_ret;
}
encoding_type = s->info.args.get("encoding-type");
if (s->system_request) {
s->info.args.get_bool("objs-container", &objs_container, false);
const char *shard_id_str = s->info.env->get("HTTP_RGWX_SHARD_ID");
if (shard_id_str) {
string err;
shard_id = strict_strtol(shard_id_str, 10, &err);
if (!err.empty()) {
ldpp_dout(this, 5) << "bad shard id specified: " << shard_id_str << dendl;
return -EINVAL;
}
} else {
shard_id = s->bucket_instance_shard_id;
}
}
return 0;
}
int RGWListBucket_ObjStore_S3::get_params(optional_yield y)
{
int ret = get_common_params();
if (ret < 0) {
return ret;
}
if (!list_versions) {
marker = s->info.args.get("marker");
} else {
marker.name = s->info.args.get("key-marker");
marker.instance = s->info.args.get("version-id-marker");
}
return 0;
}
int RGWListBucket_ObjStore_S3v2::get_params(optional_yield y)
{
int ret = get_common_params();
if (ret < 0) {
return ret;
}
s->info.args.get_bool("fetch-owner", &fetchOwner, false);
startAfter = s->info.args.get("start-after", &start_after_exist);
continuation_token = s->info.args.get("continuation-token", &continuation_token_exist);
if(!continuation_token_exist) {
marker = startAfter;
} else {
marker = continuation_token;
}
return 0;
}
void RGWListBucket_ObjStore_S3::send_common_versioned_response()
{
if (!s->bucket_tenant.empty()) {
s->formatter->dump_string("Tenant", s->bucket_tenant);
}
s->formatter->dump_string("Name", s->bucket_name);
s->formatter->dump_string("Prefix", prefix);
s->formatter->dump_int("MaxKeys", max);
if (!delimiter.empty()) {
s->formatter->dump_string("Delimiter", delimiter);
}
s->formatter->dump_string("IsTruncated", (max && is_truncated ? "true"
: "false"));
if (!common_prefixes.empty()) {
map<string, bool>::iterator pref_iter;
for (pref_iter = common_prefixes.begin();
pref_iter != common_prefixes.end(); ++pref_iter) {
s->formatter->open_array_section("CommonPrefixes");
if (encode_key) {
s->formatter->dump_string("Prefix", url_encode(pref_iter->first, false));
} else {
s->formatter->dump_string("Prefix", pref_iter->first);
}
s->formatter->close_section();
}
}
}
void RGWListBucket_ObjStore_S3::send_versioned_response()
{
s->formatter->open_object_section_in_ns("ListVersionsResult", XMLNS_AWS_S3);
if (strcasecmp(encoding_type.c_str(), "url") == 0) {
s->formatter->dump_string("EncodingType", "url");
encode_key = true;
}
RGWListBucket_ObjStore_S3::send_common_versioned_response();
s->formatter->dump_string("KeyMarker", marker.name);
s->formatter->dump_string("VersionIdMarker", marker.instance);
if (is_truncated && !next_marker.empty()) {
s->formatter->dump_string("NextKeyMarker", next_marker.name);
if (next_marker.instance.empty()) {
s->formatter->dump_string("NextVersionIdMarker", "null");
}
else {
s->formatter->dump_string("NextVersionIdMarker", next_marker.instance);
}
}
if (op_ret >= 0) {
if (objs_container) {
s->formatter->open_array_section("Entries");
}
vector<rgw_bucket_dir_entry>::iterator iter;
for (iter = objs.begin(); iter != objs.end(); ++iter) {
const char *section_name = (iter->is_delete_marker() ? "DeleteMarker"
: "Version");
s->formatter->open_object_section(section_name);
if (objs_container) {
s->formatter->dump_bool("IsDeleteMarker", iter->is_delete_marker());
}
rgw_obj_key key(iter->key);
if (encode_key) {
string key_name;
url_encode(key.name, key_name);
s->formatter->dump_string("Key", key_name);
}
else {
s->formatter->dump_string("Key", key.name);
}
string version_id = key.instance;
if (version_id.empty()) {
version_id = "null";
}
if (s->system_request) {
if (iter->versioned_epoch > 0) {
s->formatter->dump_int("VersionedEpoch", iter->versioned_epoch);
}
s->formatter->dump_string("RgwxTag", iter->tag);
utime_t ut(iter->meta.mtime);
ut.gmtime_nsec(s->formatter->dump_stream("RgwxMtime"));
}
s->formatter->dump_string("VersionId", version_id);
s->formatter->dump_bool("IsLatest", iter->is_current());
dump_time(s, "LastModified", iter->meta.mtime);
if (!iter->is_delete_marker()) {
s->formatter->dump_format("ETag", "\"%s\"", iter->meta.etag.c_str());
s->formatter->dump_int("Size", iter->meta.accounted_size);
auto& storage_class = rgw_placement_rule::get_canonical_storage_class(iter->meta.storage_class);
s->formatter->dump_string("StorageClass", storage_class.c_str());
}
dump_owner(s, rgw_user(iter->meta.owner), iter->meta.owner_display_name);
if (iter->meta.appendable) {
s->formatter->dump_string("Type", "Appendable");
} else {
s->formatter->dump_string("Type", "Normal");
}
s->formatter->close_section(); // Version/DeleteMarker
}
if (objs_container) {
s->formatter->close_section(); // Entries
}
s->formatter->close_section(); // ListVersionsResult
}
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWListBucket_ObjStore_S3::send_common_response()
{
if (!s->bucket_tenant.empty()) {
s->formatter->dump_string("Tenant", s->bucket_tenant);
}
s->formatter->dump_string("Name", s->bucket_name);
s->formatter->dump_string("Prefix", prefix);
s->formatter->dump_int("MaxKeys", max);
if (!delimiter.empty()) {
if (encode_key) {
s->formatter->dump_string("Delimiter", url_encode(delimiter, false));
} else {
s->formatter->dump_string("Delimiter", delimiter);
}
}
s->formatter->dump_string("IsTruncated", (max && is_truncated ? "true"
: "false"));
if (!common_prefixes.empty()) {
map<string, bool>::iterator pref_iter;
for (pref_iter = common_prefixes.begin();
pref_iter != common_prefixes.end(); ++pref_iter) {
s->formatter->open_array_section("CommonPrefixes");
if (encode_key) {
s->formatter->dump_string("Prefix", url_encode(pref_iter->first, false));
} else {
s->formatter->dump_string("Prefix", pref_iter->first);
}
s->formatter->close_section();
}
}
}
void RGWListBucket_ObjStore_S3::send_response()
{
if (op_ret < 0) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
dump_start(s);
if (op_ret < 0) {
return;
}
if (list_versions) {
send_versioned_response();
return;
}
s->formatter->open_object_section_in_ns("ListBucketResult", XMLNS_AWS_S3);
if (strcasecmp(encoding_type.c_str(), "url") == 0) {
s->formatter->dump_string("EncodingType", "url");
encode_key = true;
}
RGWListBucket_ObjStore_S3::send_common_response();
if (op_ret >= 0) {
if (s->format == RGWFormat::JSON) {
s->formatter->open_array_section("Contents");
}
vector<rgw_bucket_dir_entry>::iterator iter;
for (iter = objs.begin(); iter != objs.end(); ++iter) {
rgw_obj_key key(iter->key);
std::string key_name;
if (encode_key) {
url_encode(key.name, key_name);
} else {
key_name = key.name;
}
/* conditionally format JSON in the obvious way--I'm unsure if
* AWS actually does this */
if (s->format == RGWFormat::XML) {
s->formatter->open_array_section("Contents");
} else {
// json
s->formatter->open_object_section("dummy");
}
s->formatter->dump_string("Key", key_name);
dump_time(s, "LastModified", iter->meta.mtime);
s->formatter->dump_format("ETag", "\"%s\"", iter->meta.etag.c_str());
s->formatter->dump_int("Size", iter->meta.accounted_size);
auto& storage_class = rgw_placement_rule::get_canonical_storage_class(iter->meta.storage_class);
s->formatter->dump_string("StorageClass", storage_class.c_str());
dump_owner(s, rgw_user(iter->meta.owner), iter->meta.owner_display_name);
if (s->system_request) {
s->formatter->dump_string("RgwxTag", iter->tag);
}
if (iter->meta.appendable) {
s->formatter->dump_string("Type", "Appendable");
} else {
s->formatter->dump_string("Type", "Normal");
}
// JSON has one extra section per element
s->formatter->close_section();
} // foreach obj
if (s->format == RGWFormat::JSON) {
s->formatter->close_section();
}
}
s->formatter->dump_string("Marker", marker.name);
if (is_truncated && !next_marker.empty()) {
s->formatter->dump_string("NextMarker", next_marker.name);
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
} /* RGWListBucket_ObjStore_S3::send_response() */
void RGWListBucket_ObjStore_S3v2::send_versioned_response()
{
s->formatter->open_object_section_in_ns("ListVersionsResult", XMLNS_AWS_S3);
RGWListBucket_ObjStore_S3v2::send_common_versioned_response();
s->formatter->dump_string("KeyContinuationToken", marker.name);
s->formatter->dump_string("VersionIdContinuationToken", marker.instance);
if (is_truncated && !next_marker.empty()) {
s->formatter->dump_string("NextKeyContinuationToken", next_marker.name);
s->formatter->dump_string("NextVersionIdContinuationToken", next_marker.instance);
}
if (strcasecmp(encoding_type.c_str(), "url") == 0) {
s->formatter->dump_string("EncodingType", "url");
encode_key = true;
}
if (op_ret >= 0) {
if (objs_container) {
s->formatter->open_array_section("Entries");
}
vector<rgw_bucket_dir_entry>::iterator iter;
for (iter = objs.begin(); iter != objs.end(); ++iter) {
const char *section_name = (iter->is_delete_marker() ? "DeleteContinuationToken"
: "Version");
s->formatter->open_object_section(section_name);
if (objs_container) {
s->formatter->dump_bool("IsDeleteContinuationToken", iter->is_delete_marker());
}
rgw_obj_key key(iter->key);
if (encode_key) {
string key_name;
url_encode(key.name, key_name);
s->formatter->dump_string("Key", key_name);
}
else {
s->formatter->dump_string("Key", key.name);
}
string version_id = key.instance;
if (version_id.empty()) {
version_id = "null";
}
if (s->system_request) {
if (iter->versioned_epoch > 0) {
s->formatter->dump_int("VersionedEpoch", iter->versioned_epoch);
}
s->formatter->dump_string("RgwxTag", iter->tag);
utime_t ut(iter->meta.mtime);
ut.gmtime_nsec(s->formatter->dump_stream("RgwxMtime"));
}
s->formatter->dump_string("VersionId", version_id);
s->formatter->dump_bool("IsLatest", iter->is_current());
dump_time(s, "LastModified", iter->meta.mtime);
if (!iter->is_delete_marker()) {
s->formatter->dump_format("ETag", "\"%s\"", iter->meta.etag.c_str());
s->formatter->dump_int("Size", iter->meta.accounted_size);
auto& storage_class = rgw_placement_rule::get_canonical_storage_class(iter->meta.storage_class);
s->formatter->dump_string("StorageClass", storage_class.c_str());
}
if (fetchOwner == true) {
dump_owner(s, rgw_user(iter->meta.owner), iter->meta.owner_display_name);
}
s->formatter->close_section();
}
if (objs_container) {
s->formatter->close_section();
}
if (!common_prefixes.empty()) {
map<string, bool>::iterator pref_iter;
for (pref_iter = common_prefixes.begin();
pref_iter != common_prefixes.end(); ++pref_iter) {
s->formatter->open_array_section("CommonPrefixes");
if (encode_key) {
s->formatter->dump_string("Prefix", url_encode(pref_iter->first, false));
} else {
s->formatter->dump_string("Prefix", pref_iter->first);
}
s->formatter->dump_int("KeyCount",objs.size());
if (start_after_exist) {
s->formatter->dump_string("StartAfter", startAfter);
}
s->formatter->close_section();
}
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
void RGWListBucket_ObjStore_S3v2::send_response()
{
if (op_ret < 0) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
dump_start(s);
if (op_ret < 0) {
return;
}
if (list_versions) {
send_versioned_response();
return;
}
s->formatter->open_object_section_in_ns("ListBucketResult", XMLNS_AWS_S3);
if (strcasecmp(encoding_type.c_str(), "url") == 0) {
s->formatter->dump_string("EncodingType", "url");
encode_key = true;
}
RGWListBucket_ObjStore_S3::send_common_response();
if (op_ret >= 0) {
vector<rgw_bucket_dir_entry>::iterator iter;
for (iter = objs.begin(); iter != objs.end(); ++iter) {
rgw_obj_key key(iter->key);
s->formatter->open_array_section("Contents");
if (encode_key) {
string key_name;
url_encode(key.name, key_name);
s->formatter->dump_string("Key", key_name);
}
else {
s->formatter->dump_string("Key", key.name);
}
dump_time(s, "LastModified", iter->meta.mtime);
s->formatter->dump_format("ETag", "\"%s\"", iter->meta.etag.c_str());
s->formatter->dump_int("Size", iter->meta.accounted_size);
auto& storage_class = rgw_placement_rule::get_canonical_storage_class(iter->meta.storage_class);
s->formatter->dump_string("StorageClass", storage_class.c_str());
if (fetchOwner == true) {
dump_owner(s, rgw_user(iter->meta.owner), iter->meta.owner_display_name);
}
if (s->system_request) {
s->formatter->dump_string("RgwxTag", iter->tag);
}
if (iter->meta.appendable) {
s->formatter->dump_string("Type", "Appendable");
} else {
s->formatter->dump_string("Type", "Normal");
}
s->formatter->close_section();
}
}
if (continuation_token_exist) {
s->formatter->dump_string("ContinuationToken", continuation_token);
}
if (is_truncated && !next_marker.empty()) {
s->formatter->dump_string("NextContinuationToken", next_marker.name);
}
s->formatter->dump_int("KeyCount", objs.size() + common_prefixes.size());
if (start_after_exist) {
s->formatter->dump_string("StartAfter", startAfter);
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWGetBucketLogging_ObjStore_S3::send_response()
{
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
s->formatter->open_object_section_in_ns("BucketLoggingStatus", XMLNS_AWS_S3);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWGetBucketLocation_ObjStore_S3::send_response()
{
dump_errno(s);
end_header(s, this);
dump_start(s);
std::unique_ptr<rgw::sal::ZoneGroup> zonegroup;
string api_name;
int ret = driver->get_zonegroup(s->bucket->get_info().zonegroup, &zonegroup);
if (ret >= 0) {
api_name = zonegroup->get_api_name();
} else {
if (s->bucket->get_info().zonegroup != "default") {
api_name = s->bucket->get_info().zonegroup;
}
}
s->formatter->dump_format_ns("LocationConstraint", XMLNS_AWS_S3,
"%s", api_name.c_str());
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWGetBucketVersioning_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
s->formatter->open_object_section_in_ns("VersioningConfiguration", XMLNS_AWS_S3);
if (versioned) {
const char *status = (versioning_enabled ? "Enabled" : "Suspended");
s->formatter->dump_string("Status", status);
const char *mfa_status = (mfa_enabled ? "Enabled" : "Disabled");
s->formatter->dump_string("MfaDelete", mfa_status);
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
struct ver_config_status {
int status{VersioningSuspended};
enum MFAStatus {
MFA_UNKNOWN,
MFA_DISABLED,
MFA_ENABLED,
} mfa_status{MFA_UNKNOWN};
int retcode{0};
void decode_xml(XMLObj *obj) {
string status_str;
string mfa_str;
RGWXMLDecoder::decode_xml("Status", status_str, obj);
if (status_str == "Enabled") {
status = VersioningEnabled;
} else if (status_str != "Suspended") {
status = VersioningStatusInvalid;
}
if (RGWXMLDecoder::decode_xml("MfaDelete", mfa_str, obj)) {
if (mfa_str == "Enabled") {
mfa_status = MFA_ENABLED;
} else if (mfa_str == "Disabled") {
mfa_status = MFA_DISABLED;
} else {
retcode = -EINVAL;
}
}
}
};
int RGWSetBucketVersioning_ObjStore_S3::get_params(optional_yield y)
{
int r = 0;
bufferlist data;
std::tie(r, data) =
read_all_input(s, s->cct->_conf->rgw_max_put_param_size, false);
if (r < 0) {
return r;
}
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
return -EIO;
}
char* buf = data.c_str();
if (!parser.parse(buf, data.length(), 1)) {
ldpp_dout(this, 10) << "NOTICE: failed to parse data: " << buf << dendl;
r = -EINVAL;
return r;
}
ver_config_status status_conf;
if (!RGWXMLDecoder::decode_xml("VersioningConfiguration", status_conf, &parser)) {
ldpp_dout(this, 10) << "NOTICE: bad versioning config input" << dendl;
return -EINVAL;
}
if (!driver->is_meta_master()) {
/* only need to keep this data around if we're not meta master */
in_data.append(data);
}
versioning_status = status_conf.status;
if (versioning_status == VersioningStatusInvalid) {
r = -EINVAL;
}
if (status_conf.mfa_status != ver_config_status::MFA_UNKNOWN) {
mfa_set_status = true;
switch (status_conf.mfa_status) {
case ver_config_status::MFA_DISABLED:
mfa_status = false;
break;
case ver_config_status::MFA_ENABLED:
mfa_status = true;
break;
default:
ldpp_dout(this, 0) << "ERROR: RGWSetBucketVersioning_ObjStore_S3::get_params(optional_yield y): unexpected switch case mfa_status=" << status_conf.mfa_status << dendl;
r = -EIO;
}
} else if (status_conf.retcode < 0) {
r = status_conf.retcode;
}
return r;
}
void RGWSetBucketVersioning_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
}
int RGWSetBucketWebsite_ObjStore_S3::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r = 0;
bufferlist data;
std::tie(r, data) = read_all_input(s, max_size, false);
if (r < 0) {
return r;
}
in_data.append(data);
RGWXMLDecoder::XMLParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
return -EIO;
}
char* buf = data.c_str();
if (!parser.parse(buf, data.length(), 1)) {
ldpp_dout(this, 5) << "failed to parse xml: " << buf << dendl;
return -EINVAL;
}
try {
RGWXMLDecoder::decode_xml("WebsiteConfiguration", website_conf, &parser, true);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "unexpected xml: " << buf << dendl;
return -EINVAL;
}
if (website_conf.is_redirect_all && website_conf.redirect_all.hostname.empty()) {
s->err.message = "A host name must be provided to redirect all requests (e.g. \"example.com\").";
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
} else if (!website_conf.is_redirect_all && !website_conf.is_set_index_doc) {
s->err.message = "A value for IndexDocument Suffix must be provided if RedirectAllRequestsTo is empty";
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
} else if (!website_conf.is_redirect_all && website_conf.is_set_index_doc &&
website_conf.index_doc_suffix.empty()) {
s->err.message = "The IndexDocument Suffix is not well formed";
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
}
#define WEBSITE_ROUTING_RULES_MAX_NUM 50
int max_num = s->cct->_conf->rgw_website_routing_rules_max_num;
if (max_num < 0) {
max_num = WEBSITE_ROUTING_RULES_MAX_NUM;
}
int routing_rules_num = website_conf.routing_rules.rules.size();
if (routing_rules_num > max_num) {
ldpp_dout(this, 4) << "An website routing config can have up to "
<< max_num
<< " rules, request website routing rules num: "
<< routing_rules_num << dendl;
op_ret = -ERR_INVALID_WEBSITE_ROUTING_RULES_ERROR;
s->err.message = std::to_string(routing_rules_num) +" routing rules provided, the number of routing rules in a website configuration is limited to "
+ std::to_string(max_num)
+ ".";
return -ERR_INVALID_REQUEST;
}
return 0;
}
void RGWSetBucketWebsite_ObjStore_S3::send_response()
{
if (op_ret < 0)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
}
void RGWDeleteBucketWebsite_ObjStore_S3::send_response()
{
if (op_ret == 0) {
op_ret = STATUS_NO_CONTENT;
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
}
void RGWGetBucketWebsite_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (op_ret < 0) {
return;
}
RGWBucketWebsiteConf& conf = s->bucket->get_info().website_conf;
s->formatter->open_object_section_in_ns("WebsiteConfiguration", XMLNS_AWS_S3);
conf.dump_xml(s->formatter);
s->formatter->close_section(); // WebsiteConfiguration
rgw_flush_formatter_and_reset(s, s->formatter);
}
static void dump_bucket_metadata(req_state *s, rgw::sal::Bucket* bucket)
{
dump_header(s, "X-RGW-Object-Count", static_cast<long long>(bucket->get_count()));
dump_header(s, "X-RGW-Bytes-Used", static_cast<long long>(bucket->get_size()));
// only bucket's owner is allowed to get the quota settings of the account
if (bucket->is_owner(s->user.get())) {
auto user_info = s->user->get_info();
dump_header(s, "X-RGW-Quota-User-Size", static_cast<long long>(user_info.quota.user_quota.max_size));
dump_header(s, "X-RGW-Quota-User-Objects", static_cast<long long>(user_info.quota.user_quota.max_objects));
dump_header(s, "X-RGW-Quota-Max-Buckets", static_cast<long long>(user_info.max_buckets));
dump_header(s, "X-RGW-Quota-Bucket-Size", static_cast<long long>(user_info.quota.bucket_quota.max_size));
dump_header(s, "X-RGW-Quota-Bucket-Objects", static_cast<long long>(user_info.quota.bucket_quota.max_objects));
}
}
void RGWStatBucket_ObjStore_S3::send_response()
{
if (op_ret >= 0) {
dump_bucket_metadata(s, bucket.get());
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this);
dump_start(s);
}
static int create_s3_policy(req_state *s, rgw::sal::Driver* driver,
RGWAccessControlPolicy_S3& s3policy,
ACLOwner& owner)
{
if (s->has_acl_header) {
if (!s->canned_acl.empty())
return -ERR_INVALID_REQUEST;
return s3policy.create_from_headers(s, driver, s->info.env, owner);
}
return s3policy.create_canned(owner, s->bucket_owner, s->canned_acl);
}
class RGWLocationConstraint : public XMLObj
{
public:
RGWLocationConstraint() {}
~RGWLocationConstraint() override {}
bool xml_end(const char *el) override {
if (!el)
return false;
location_constraint = get_data();
return true;
}
string location_constraint;
};
class RGWCreateBucketConfig : public XMLObj
{
public:
RGWCreateBucketConfig() {}
~RGWCreateBucketConfig() override {}
};
class RGWCreateBucketParser : public RGWXMLParser
{
XMLObj *alloc_obj(const char *el) override {
return new XMLObj;
}
public:
RGWCreateBucketParser() {}
~RGWCreateBucketParser() override {}
bool get_location_constraint(string& zone_group) {
XMLObj *config = find_first("CreateBucketConfiguration");
if (!config)
return false;
XMLObj *constraint = config->find_first("LocationConstraint");
if (!constraint)
return false;
zone_group = constraint->get_data();
return true;
}
};
int RGWCreateBucket_ObjStore_S3::get_params(optional_yield y)
{
RGWAccessControlPolicy_S3 s3policy(s->cct);
bool relaxed_names = s->cct->_conf->rgw_relaxed_s3_bucket_names;
int r;
if (!s->system_request) {
r = valid_s3_bucket_name(s->bucket_name, relaxed_names);
if (r) return r;
}
r = create_s3_policy(s, driver, s3policy, s->owner);
if (r < 0)
return r;
policy = s3policy;
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int op_ret = 0;
bufferlist data;
std::tie(op_ret, data) = read_all_input(s, max_size, false);
if ((op_ret < 0) && (op_ret != -ERR_LENGTH_REQUIRED))
return op_ret;
in_data.append(data);
if (data.length()) {
RGWCreateBucketParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
return -EIO;
}
char* buf = data.c_str();
bool success = parser.parse(buf, data.length(), 1);
ldpp_dout(this, 20) << "create bucket input data=" << buf << dendl;
if (!success) {
ldpp_dout(this, 0) << "failed to parse input: " << buf << dendl;
return -EINVAL;
}
if (!parser.get_location_constraint(location_constraint)) {
ldpp_dout(this, 0) << "provided input did not specify location constraint correctly" << dendl;
return -EINVAL;
}
ldpp_dout(this, 10) << "create bucket location constraint: "
<< location_constraint << dendl;
}
size_t pos = location_constraint.find(':');
if (pos != string::npos) {
placement_rule.init(location_constraint.substr(pos + 1), s->info.storage_class);
location_constraint = location_constraint.substr(0, pos);
} else {
placement_rule.storage_class = s->info.storage_class;
}
auto iter = s->info.x_meta_map.find("x-amz-bucket-object-lock-enabled");
if (iter != s->info.x_meta_map.end()) {
if (!boost::algorithm::iequals(iter->second, "true") && !boost::algorithm::iequals(iter->second, "false")) {
return -EINVAL;
}
obj_lock_enabled = boost::algorithm::iequals(iter->second, "true");
}
return 0;
}
void RGWCreateBucket_ObjStore_S3::send_response()
{
if (op_ret == -ERR_BUCKET_EXISTS)
op_ret = 0;
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s);
if (op_ret < 0)
return;
if (s->system_request) {
JSONFormatter f; /* use json formatter for system requests output */
f.open_object_section("info");
encode_json("entry_point_object_ver", ep_objv, &f);
encode_json("object_ver", info.objv_tracker.read_version, &f);
encode_json("bucket_info", info, &f);
f.close_section();
rgw_flush_formatter_and_reset(s, &f);
}
}
void RGWDeleteBucket_ObjStore_S3::send_response()
{
int r = op_ret;
if (!r)
r = STATUS_NO_CONTENT;
set_req_state_err(s, r);
dump_errno(s);
end_header(s, this);
}
static inline void map_qs_metadata(req_state* s, bool crypto_too)
{
/* merge S3 valid user metadata from the query-string into
* x_meta_map, which maps them to attributes */
const auto& params = const_cast<RGWHTTPArgs&>(s->info.args).get_params();
for (const auto& elt : params) {
std::string k = boost::algorithm::to_lower_copy(elt.first);
if (k.find("x-amz-meta-") == /* offset */ 0) {
rgw_add_amz_meta_header(s->info.x_meta_map, k, elt.second);
}
if (crypto_too && k.find("x-amz-server-side-encryption") == /* offset */ 0) {
rgw_set_amz_meta_header(s->info.crypt_attribute_map, k, elt.second, OVERWRITE);
}
}
}
int RGWPutObj_ObjStore_S3::get_params(optional_yield y)
{
if (!s->length) {
const char *encoding = s->info.env->get("HTTP_TRANSFER_ENCODING");
if (!encoding || strcmp(encoding, "chunked") != 0) {
ldout(s->cct, 20) << "neither length nor chunked encoding" << dendl;
return -ERR_LENGTH_REQUIRED;
}
chunked_upload = true;
}
int ret;
map_qs_metadata(s, true);
ret = get_encryption_defaults(s);
if (ret < 0) {
ldpp_dout(this, 5) << __func__ << "(): get_encryption_defaults() returned ret=" << ret << dendl;
return ret;
}
RGWAccessControlPolicy_S3 s3policy(s->cct);
ret = create_s3_policy(s, driver, s3policy, s->owner);
if (ret < 0)
return ret;
policy = s3policy;
if_match = s->info.env->get("HTTP_IF_MATCH");
if_nomatch = s->info.env->get("HTTP_IF_NONE_MATCH");
/* handle object tagging */
auto tag_str = s->info.env->get("HTTP_X_AMZ_TAGGING");
if (tag_str){
obj_tags = std::make_unique<RGWObjTags>();
ret = obj_tags->set_from_string(tag_str);
if (ret < 0){
ldpp_dout(this,0) << "setting obj tags failed with " << ret << dendl;
if (ret == -ERR_INVALID_TAG){
ret = -EINVAL; //s3 returns only -EINVAL for PUT requests
}
return ret;
}
}
//handle object lock
auto obj_lock_mode_str = s->info.env->get("HTTP_X_AMZ_OBJECT_LOCK_MODE");
auto obj_lock_date_str = s->info.env->get("HTTP_X_AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE");
auto obj_legal_hold_str = s->info.env->get("HTTP_X_AMZ_OBJECT_LOCK_LEGAL_HOLD");
if (obj_lock_mode_str && obj_lock_date_str) {
boost::optional<ceph::real_time> date = ceph::from_iso_8601(obj_lock_date_str);
if (boost::none == date || ceph::real_clock::to_time_t(*date) <= ceph_clock_now()) {
ret = -EINVAL;
ldpp_dout(this,0) << "invalid x-amz-object-lock-retain-until-date value" << dendl;
return ret;
}
if (strcmp(obj_lock_mode_str, "GOVERNANCE") != 0 && strcmp(obj_lock_mode_str, "COMPLIANCE") != 0) {
ret = -EINVAL;
ldpp_dout(this,0) << "invalid x-amz-object-lock-mode value" << dendl;
return ret;
}
obj_retention = new RGWObjectRetention(obj_lock_mode_str, *date);
} else if ((obj_lock_mode_str && !obj_lock_date_str) || (!obj_lock_mode_str && obj_lock_date_str)) {
ret = -EINVAL;
ldpp_dout(this,0) << "need both x-amz-object-lock-mode and x-amz-object-lock-retain-until-date " << dendl;
return ret;
}
if (obj_legal_hold_str) {
if (strcmp(obj_legal_hold_str, "ON") != 0 && strcmp(obj_legal_hold_str, "OFF") != 0) {
ret = -EINVAL;
ldpp_dout(this,0) << "invalid x-amz-object-lock-legal-hold value" << dendl;
return ret;
}
obj_legal_hold = new RGWObjectLegalHold(obj_legal_hold_str);
}
if (!s->bucket->get_info().obj_lock_enabled() && (obj_retention || obj_legal_hold)) {
ldpp_dout(this, 0) << "ERROR: object retention or legal hold can't be set if bucket object lock not configured" << dendl;
ret = -ERR_INVALID_REQUEST;
return ret;
}
multipart_upload_id = s->info.args.get("uploadId");
multipart_part_str = s->info.args.get("partNumber");
if (!multipart_part_str.empty()) {
string err;
multipart_part_num = strict_strtol(multipart_part_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(s, 10) << "bad part number: " << multipart_part_str << ": " << err << dendl;
return -EINVAL;
}
} else if (!multipart_upload_id.empty()) {
ldpp_dout(s, 10) << "part number with no multipart upload id" << dendl;
return -EINVAL;
}
append = s->info.args.exists("append");
if (append) {
string pos_str = s->info.args.get("position");
string err;
long long pos_tmp = strict_strtoll(pos_str.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(s, 10) << "bad position: " << pos_str << ": " << err << dendl;
return -EINVAL;
} else if (pos_tmp < 0) {
ldpp_dout(s, 10) << "bad position: " << pos_str << ": " << "position shouldn't be negative" << dendl;
return -EINVAL;
}
position = uint64_t(pos_tmp);
}
return RGWPutObj_ObjStore::get_params(y);
}
int RGWPutObj_ObjStore_S3::get_data(bufferlist& bl)
{
const int ret = RGWPutObj_ObjStore::get_data(bl);
if (ret == 0) {
const int ret_auth = do_aws4_auth_completion();
if (ret_auth < 0) {
return ret_auth;
}
}
return ret;
}
static int get_success_retcode(int code)
{
switch (code) {
case 201:
return STATUS_CREATED;
case 204:
return STATUS_NO_CONTENT;
}
return 0;
}
void RGWPutObj_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
dump_errno(s);
} else {
if (s->cct->_conf->rgw_s3_success_create_obj_status) {
op_ret = get_success_retcode(
s->cct->_conf->rgw_s3_success_create_obj_status);
set_req_state_err(s, op_ret);
}
string expires = get_s3_expiration_header(s, mtime);
if (copy_source.empty()) {
dump_errno(s);
dump_etag(s, etag);
dump_content_length(s, 0);
dump_header_if_nonempty(s, "x-amz-version-id", version_id);
dump_header_if_nonempty(s, "x-amz-expiration", expires);
for (auto &it : crypt_http_responses)
dump_header(s, it.first, it.second);
} else {
dump_errno(s);
dump_header_if_nonempty(s, "x-amz-version-id", version_id);
dump_header_if_nonempty(s, "x-amz-expiration", expires);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
struct tm tmp;
utime_t ut(mtime);
time_t secs = (time_t)ut.sec();
gmtime_r(&secs, &tmp);
char buf[TIME_BUF_SIZE];
s->formatter->open_object_section_in_ns("CopyPartResult",
"http://s3.amazonaws.com/doc/2006-03-01/");
if (strftime(buf, sizeof(buf), "%Y-%m-%dT%T.000Z", &tmp) > 0) {
s->formatter->dump_string("LastModified", buf);
}
s->formatter->dump_string("ETag", etag);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
return;
}
}
if (append) {
if (op_ret == 0 || op_ret == -ERR_POSITION_NOT_EQUAL_TO_LENGTH) {
dump_header(s, "x-rgw-next-append-position", cur_accounted_size);
}
}
if (s->system_request && !real_clock::is_zero(mtime)) {
dump_epoch_header(s, "Rgwx-Mtime", mtime);
}
end_header(s, this);
}
static inline void set_attr(map<string, bufferlist>& attrs, const char* key, const std::string& value)
{
bufferlist bl;
encode(value,bl);
attrs.emplace(key, std::move(bl));
}
static inline void set_attr(map<string, bufferlist>& attrs, const char* key, const char* value)
{
bufferlist bl;
encode(value,bl);
attrs.emplace(key, std::move(bl));
}
int RGWPutObj_ObjStore_S3::get_decrypt_filter(
std::unique_ptr<RGWGetObj_Filter>* filter,
RGWGetObj_Filter* cb,
map<string, bufferlist>& attrs,
bufferlist* manifest_bl)
{
std::map<std::string, std::string> crypt_http_responses_unused;
int res = 0;
std::unique_ptr<BlockCrypt> block_crypt;
res = rgw_s3_prepare_decrypt(s, attrs, &block_crypt, crypt_http_responses_unused);
if (res == 0) {
if (block_crypt != nullptr) {
auto f = std::unique_ptr<RGWGetObj_BlockDecrypt>(new RGWGetObj_BlockDecrypt(s, s->cct, cb, std::move(block_crypt), s->yield));
if (f != nullptr) {
if (manifest_bl != nullptr) {
res = f->read_manifest(this, *manifest_bl);
if (res == 0) {
*filter = std::move(f);
}
}
}
}
}
return res;
}
int RGWPutObj_ObjStore_S3::get_encrypt_filter(
std::unique_ptr<rgw::sal::DataProcessor> *filter,
rgw::sal::DataProcessor *cb)
{
int res = 0;
if (!multipart_upload_id.empty()) {
std::unique_ptr<rgw::sal::MultipartUpload> upload =
s->bucket->get_multipart_upload(s->object->get_name(),
multipart_upload_id);
std::unique_ptr<rgw::sal::Object> obj = upload->get_meta_obj();
obj->set_in_extra_data(true);
res = obj->get_obj_attrs(s->yield, this);
if (res == 0) {
std::unique_ptr<BlockCrypt> block_crypt;
/* We are adding to existing object.
* We use crypto mode that configured as if we were decrypting. */
res = rgw_s3_prepare_decrypt(s, obj->get_attrs(), &block_crypt, crypt_http_responses);
if (res == 0 && block_crypt != nullptr)
filter->reset(new RGWPutObj_BlockEncrypt(s, s->cct, cb, std::move(block_crypt), s->yield));
}
/* it is ok, to not have encryption at all */
}
else
{
std::unique_ptr<BlockCrypt> block_crypt;
res = rgw_s3_prepare_encrypt(s, attrs, &block_crypt, crypt_http_responses);
if (res == 0 && block_crypt != nullptr) {
filter->reset(new RGWPutObj_BlockEncrypt(s, s->cct, cb, std::move(block_crypt), s->yield));
}
}
return res;
}
void RGWPostObj_ObjStore_S3::rebuild_key(rgw::sal::Object* obj)
{
string key = obj->get_name();
static string var = "${filename}";
int pos = key.find(var);
if (pos < 0)
return;
string new_key = key.substr(0, pos);
new_key.append(filename);
new_key.append(key.substr(pos + var.size()));
obj->set_key(new_key);
}
std::string RGWPostObj_ObjStore_S3::get_current_filename() const
{
return s->object->get_name();
}
std::string RGWPostObj_ObjStore_S3::get_current_content_type() const
{
return content_type;
}
int RGWPostObj_ObjStore_S3::get_params(optional_yield y)
{
op_ret = RGWPostObj_ObjStore::get_params(y);
if (op_ret < 0) {
return op_ret;
}
map_qs_metadata(s, false);
ldpp_dout(this, 20) << "adding bucket to policy env: " << s->bucket->get_name()
<< dendl;
env.add_var("bucket", s->bucket->get_name());
bool done;
do {
struct post_form_part part;
int r = read_form_part_header(&part, done);
if (r < 0)
return r;
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
ldpp_dout(this, 20) << "read part header -- part.name="
<< part.name << dendl;
for (const auto& pair : part.fields) {
ldpp_dout(this, 20) << "field.name=" << pair.first << dendl;
ldpp_dout(this, 20) << "field.val=" << pair.second.val << dendl;
ldpp_dout(this, 20) << "field.params:" << dendl;
for (const auto& param_pair : pair.second.params) {
ldpp_dout(this, 20) << " " << param_pair.first
<< " -> " << param_pair.second << dendl;
}
}
}
if (done) { /* unexpected here */
err_msg = "Malformed request";
return -EINVAL;
}
if (stringcasecmp(part.name, "file") == 0) { /* beginning of data transfer */
struct post_part_field& field = part.fields["Content-Disposition"];
map<string, string>::iterator iter = field.params.find("filename");
if (iter != field.params.end()) {
filename = iter->second;
}
parts[part.name] = part;
break;
}
bool boundary;
uint64_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
r = read_data(part.data, chunk_size, boundary, done);
if (r < 0 || !boundary) {
err_msg = "Couldn't find boundary";
return -EINVAL;
}
parts[part.name] = part;
string part_str(part.data.c_str(), part.data.length());
env.add_var(part.name, part_str);
} while (!done);
for (auto &p: parts) {
if (! boost::istarts_with(p.first, "x-amz-server-side-encryption")) {
continue;
}
bufferlist &d { p.second.data };
std::string v { rgw_trim_whitespace(std::string_view(d.c_str(), d.length())) };
rgw_set_amz_meta_header(s->info.crypt_attribute_map, p.first, v, OVERWRITE);
}
int r = get_encryption_defaults(s);
if (r < 0) {
ldpp_dout(this, 5) << __func__ << "(): get_encryption_defaults() returned ret=" << r << dendl;
return r;
}
string object_str;
if (!part_str(parts, "key", &object_str)) {
err_msg = "Key not specified";
return -EINVAL;
}
s->object = s->bucket->get_object(rgw_obj_key(object_str));
rebuild_key(s->object.get());
if (rgw::sal::Object::empty(s->object.get())) {
err_msg = "Empty object name";
return -EINVAL;
}
env.add_var("key", s->object->get_name());
part_str(parts, "Content-Type", &content_type);
/* AWS permits POST without Content-Type: http://tracker.ceph.com/issues/20201 */
if (! content_type.empty()) {
env.add_var("Content-Type", content_type);
}
std::string storage_class;
part_str(parts, "x-amz-storage-class", &storage_class);
if (! storage_class.empty()) {
s->dest_placement.storage_class = storage_class;
if (!driver->valid_placement(s->dest_placement)) {
ldpp_dout(this, 0) << "NOTICE: invalid dest placement: " << s->dest_placement.to_str() << dendl;
err_msg = "The storage class you specified is not valid";
return -EINVAL;
}
}
map<string, struct post_form_part, ltstr_nocase>::iterator piter =
parts.upper_bound(RGW_AMZ_META_PREFIX);
for (; piter != parts.end(); ++piter) {
string n = piter->first;
if (strncasecmp(n.c_str(), RGW_AMZ_META_PREFIX,
sizeof(RGW_AMZ_META_PREFIX) - 1) != 0)
break;
string attr_name = RGW_ATTR_PREFIX;
attr_name.append(n);
/* need to null terminate it */
bufferlist& data = piter->second.data;
string str = string(data.c_str(), data.length());
bufferlist attr_bl;
attr_bl.append(str.c_str(), str.size() + 1);
attrs[attr_name] = attr_bl;
}
// TODO: refactor this and the above loop to share code
piter = parts.find(RGW_AMZ_WEBSITE_REDIRECT_LOCATION);
if (piter != parts.end()) {
string n = piter->first;
string attr_name = RGW_ATTR_PREFIX;
attr_name.append(n);
/* need to null terminate it */
bufferlist& data = piter->second.data;
string str = string(data.c_str(), data.length());
bufferlist attr_bl;
attr_bl.append(str.c_str(), str.size() + 1);
attrs[attr_name] = attr_bl;
}
r = get_policy(y);
if (r < 0)
return r;
r = get_tags();
if (r < 0)
return r;
min_len = post_policy.min_length;
max_len = post_policy.max_length;
return 0;
}
int RGWPostObj_ObjStore_S3::get_tags()
{
string tags_str;
if (part_str(parts, "tagging", &tags_str)) {
RGWXMLParser parser;
if (!parser.init()){
ldpp_dout(this, 0) << "Couldn't init RGWObjTags XML parser" << dendl;
err_msg = "Server couldn't process the request";
return -EINVAL; // TODO: This class of errors in rgw code should be a 5XX error
}
if (!parser.parse(tags_str.c_str(), tags_str.size(), 1)) {
ldpp_dout(this,0 ) << "Invalid Tagging XML" << dendl;
err_msg = "Invalid Tagging XML";
return -EINVAL;
}
RGWObjTagging_S3 tagging;
try {
RGWXMLDecoder::decode_xml("Tagging", tagging, &parser);
} catch (RGWXMLDecoder::err& err) {
ldpp_dout(this, 5) << "Malformed tagging request: " << err << dendl;
return -EINVAL;
}
RGWObjTags obj_tags;
int r = tagging.rebuild(obj_tags);
if (r < 0)
return r;
bufferlist tags_bl;
obj_tags.encode(tags_bl);
ldpp_dout(this, 20) << "Read " << obj_tags.count() << "tags" << dendl;
attrs[RGW_ATTR_TAGS] = tags_bl;
}
return 0;
}
int RGWPostObj_ObjStore_S3::get_policy(optional_yield y)
{
if (part_bl(parts, "policy", &s->auth.s3_postobj_creds.encoded_policy)) {
bool aws4_auth = false;
/* x-amz-algorithm handling */
using rgw::auth::s3::AWS4_HMAC_SHA256_STR;
if ((part_str(parts, "x-amz-algorithm", &s->auth.s3_postobj_creds.x_amz_algorithm)) &&
(s->auth.s3_postobj_creds.x_amz_algorithm == AWS4_HMAC_SHA256_STR)) {
ldpp_dout(this, 0) << "Signature verification algorithm AWS v4 (AWS4-HMAC-SHA256)" << dendl;
aws4_auth = true;
} else {
ldpp_dout(this, 0) << "Signature verification algorithm AWS v2" << dendl;
}
// check that the signature matches the encoded policy
if (aws4_auth) {
/* AWS4 */
/* x-amz-credential handling */
if (!part_str(parts, "x-amz-credential",
&s->auth.s3_postobj_creds.x_amz_credential)) {
ldpp_dout(this, 0) << "No S3 aws4 credential found!" << dendl;
err_msg = "Missing aws4 credential";
return -EINVAL;
}
/* x-amz-signature handling */
if (!part_str(parts, "x-amz-signature",
&s->auth.s3_postobj_creds.signature)) {
ldpp_dout(this, 0) << "No aws4 signature found!" << dendl;
err_msg = "Missing aws4 signature";
return -EINVAL;
}
/* x-amz-date handling */
std::string received_date_str;
if (!part_str(parts, "x-amz-date", &received_date_str)) {
ldpp_dout(this, 0) << "No aws4 date found!" << dendl;
err_msg = "Missing aws4 date";
return -EINVAL;
}
} else {
/* AWS2 */
// check that the signature matches the encoded policy
if (!part_str(parts, "AWSAccessKeyId",
&s->auth.s3_postobj_creds.access_key)) {
ldpp_dout(this, 0) << "No S3 aws2 access key found!" << dendl;
err_msg = "Missing aws2 access key";
return -EINVAL;
}
if (!part_str(parts, "signature", &s->auth.s3_postobj_creds.signature)) {
ldpp_dout(this, 0) << "No aws2 signature found!" << dendl;
err_msg = "Missing aws2 signature";
return -EINVAL;
}
}
if (part_str(parts, "x-amz-security-token", &s->auth.s3_postobj_creds.x_amz_security_token)) {
if (s->auth.s3_postobj_creds.x_amz_security_token.size() == 0) {
err_msg = "Invalid token";
return -EINVAL;
}
}
/* FIXME: this is a makeshift solution. The browser upload authentication will be
* handled by an instance of rgw::auth::Completer spawned in Handler's authorize()
* method. */
const int ret = rgw::auth::Strategy::apply(this, auth_registry_ptr->get_s3_post(), s, y);
if (ret != 0) {
return -EACCES;
} else {
/* Populate the owner info. */
s->owner.set_id(s->user->get_id());
s->owner.set_name(s->user->get_display_name());
ldpp_dout(this, 20) << "Successful Signature Verification!" << dendl;
}
ceph::bufferlist decoded_policy;
try {
decoded_policy.decode_base64(s->auth.s3_postobj_creds.encoded_policy);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "failed to decode_base64 policy" << dendl;
err_msg = "Could not decode policy";
return -EINVAL;
}
decoded_policy.append('\0'); // NULL terminate
ldpp_dout(this, 20) << "POST policy: " << decoded_policy.c_str() << dendl;
int r = post_policy.from_json(decoded_policy, err_msg);
if (r < 0) {
if (err_msg.empty()) {
err_msg = "Failed to parse policy";
}
ldpp_dout(this, 0) << "failed to parse policy" << dendl;
return -EINVAL;
}
if (aws4_auth) {
/* AWS4 */
post_policy.set_var_checked("x-amz-signature");
} else {
/* AWS2 */
post_policy.set_var_checked("AWSAccessKeyId");
post_policy.set_var_checked("signature");
}
post_policy.set_var_checked("policy");
r = post_policy.check(&env, err_msg);
if (r < 0) {
if (err_msg.empty()) {
err_msg = "Policy check failed";
}
ldpp_dout(this, 0) << "policy check failed" << dendl;
return r;
}
} else {
ldpp_dout(this, 0) << "No attached policy found!" << dendl;
}
string canned_acl;
part_str(parts, "acl", &canned_acl);
RGWAccessControlPolicy_S3 s3policy(s->cct);
ldpp_dout(this, 20) << "canned_acl=" << canned_acl << dendl;
if (s3policy.create_canned(s->owner, s->bucket_owner, canned_acl) < 0) {
err_msg = "Bad canned ACLs";
return -EINVAL;
}
policy = s3policy;
return 0;
}
int RGWPostObj_ObjStore_S3::complete_get_params()
{
bool done;
do {
struct post_form_part part;
int r = read_form_part_header(&part, done);
if (r < 0) {
return r;
}
ceph::bufferlist part_data;
bool boundary;
uint64_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
r = read_data(part.data, chunk_size, boundary, done);
if (r < 0 || !boundary) {
return -EINVAL;
}
/* Just reading the data but not storing any results of that. */
} while (!done);
return 0;
}
int RGWPostObj_ObjStore_S3::get_data(ceph::bufferlist& bl, bool& again)
{
bool boundary;
bool done;
const uint64_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
int r = read_data(bl, chunk_size, boundary, done);
if (r < 0) {
return r;
}
if (boundary) {
if (!done) {
/* Reached end of data, let's drain the rest of the params */
r = complete_get_params();
if (r < 0) {
return r;
}
}
}
again = !boundary;
return bl.length();
}
void RGWPostObj_ObjStore_S3::send_response()
{
if (op_ret == 0 && parts.count("success_action_redirect")) {
string redirect;
part_str(parts, "success_action_redirect", &redirect);
string tenant;
string bucket;
string key;
string etag_str = "\"";
etag_str.append(etag);
etag_str.append("\"");
string etag_url;
url_encode(s->bucket_tenant, tenant); /* surely overkill, but cheap */
url_encode(s->bucket_name, bucket);
url_encode(s->object->get_name(), key);
url_encode(etag_str, etag_url);
if (!s->bucket_tenant.empty()) {
/*
* What we really would like is to quaily the bucket name, so
* that the client could simply copy it and paste into next request.
* Unfortunately, in S3 we cannot know if the client will decide
* to come through DNS, with "bucket.tenant" sytanx, or through
* URL with "tenant\bucket" syntax. Therefore, we provide the
* tenant separately.
*/
redirect.append("?tenant=");
redirect.append(tenant);
redirect.append("&bucket=");
redirect.append(bucket);
} else {
redirect.append("?bucket=");
redirect.append(bucket);
}
redirect.append("&key=");
redirect.append(key);
redirect.append("&etag=");
redirect.append(etag_url);
int r = check_utf8(redirect.c_str(), redirect.size());
if (r < 0) {
op_ret = r;
goto done;
}
dump_redirect(s, redirect);
op_ret = STATUS_REDIRECT;
} else if (op_ret == 0 && parts.count("success_action_status")) {
string status_string;
uint32_t status_int;
part_str(parts, "success_action_status", &status_string);
int r = stringtoul(status_string, &status_int);
if (r < 0) {
op_ret = r;
goto done;
}
switch (status_int) {
case 200:
break;
case 201:
op_ret = STATUS_CREATED;
break;
default:
op_ret = STATUS_NO_CONTENT;
break;
}
} else if (! op_ret) {
op_ret = STATUS_NO_CONTENT;
}
done:
if (op_ret == STATUS_CREATED) {
for (auto &it : crypt_http_responses)
dump_header(s, it.first, it.second);
s->formatter->open_object_section("PostResponse");
std::string base_uri = compute_domain_uri(s);
if (!s->bucket_tenant.empty()){
s->formatter->dump_format("Location", "%s/%s:%s/%s",
base_uri.c_str(),
url_encode(s->bucket_tenant).c_str(),
url_encode(s->bucket_name).c_str(),
url_encode(s->object->get_name()).c_str());
s->formatter->dump_string("Tenant", s->bucket_tenant);
} else {
s->formatter->dump_format("Location", "%s/%s/%s",
base_uri.c_str(),
url_encode(s->bucket_name).c_str(),
url_encode(s->object->get_name()).c_str());
}
s->formatter->dump_string("Bucket", s->bucket_name);
s->formatter->dump_string("Key", s->object->get_name());
s->formatter->dump_string("ETag", etag);
s->formatter->close_section();
}
s->err.message = err_msg;
set_req_state_err(s, op_ret);
dump_errno(s);
if (op_ret >= 0) {
dump_content_length(s, s->formatter->get_len());
}
end_header(s, this);
if (op_ret != STATUS_CREATED)
return;
rgw_flush_formatter_and_reset(s, s->formatter);
}
int RGWPostObj_ObjStore_S3::get_encrypt_filter(
std::unique_ptr<rgw::sal::DataProcessor> *filter,
rgw::sal::DataProcessor *cb)
{
std::unique_ptr<BlockCrypt> block_crypt;
int res = rgw_s3_prepare_encrypt(s, attrs, &block_crypt,
crypt_http_responses);
if (res == 0 && block_crypt != nullptr) {
filter->reset(new RGWPutObj_BlockEncrypt(s, s->cct, cb, std::move(block_crypt), s->yield));
}
return res;
}
int RGWDeleteObj_ObjStore_S3::get_params(optional_yield y)
{
const char *if_unmod = s->info.env->get("HTTP_X_AMZ_DELETE_IF_UNMODIFIED_SINCE");
if (s->system_request) {
s->info.args.get_bool(RGW_SYS_PARAM_PREFIX "no-precondition-error", &no_precondition_error, false);
}
if (if_unmod) {
std::string if_unmod_decoded = url_decode(if_unmod);
uint64_t epoch;
uint64_t nsec;
if (utime_t::parse_date(if_unmod_decoded, &epoch, &nsec) < 0) {
ldpp_dout(this, 10) << "failed to parse time: " << if_unmod_decoded << dendl;
return -EINVAL;
}
unmod_since = utime_t(epoch, nsec).to_real_time();
}
const char *bypass_gov_header = s->info.env->get("HTTP_X_AMZ_BYPASS_GOVERNANCE_RETENTION");
if (bypass_gov_header) {
std::string bypass_gov_decoded = url_decode(bypass_gov_header);
bypass_governance_mode = boost::algorithm::iequals(bypass_gov_decoded, "true");
}
return 0;
}
void RGWDeleteObj_ObjStore_S3::send_response()
{
int r = op_ret;
if (r == -ENOENT)
r = 0;
if (!r)
r = STATUS_NO_CONTENT;
set_req_state_err(s, r);
dump_errno(s);
dump_header_if_nonempty(s, "x-amz-version-id", version_id);
if (delete_marker) {
dump_header(s, "x-amz-delete-marker", "true");
}
end_header(s, this);
}
int RGWCopyObj_ObjStore_S3::init_dest_policy()
{
RGWAccessControlPolicy_S3 s3policy(s->cct);
/* build a policy for the target object */
int r = create_s3_policy(s, driver, s3policy, s->owner);
if (r < 0)
return r;
dest_policy = s3policy;
return 0;
}
int RGWCopyObj_ObjStore_S3::get_params(optional_yield y)
{
//handle object lock
auto obj_lock_mode_str = s->info.env->get("HTTP_X_AMZ_OBJECT_LOCK_MODE");
auto obj_lock_date_str = s->info.env->get("HTTP_X_AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE");
auto obj_legal_hold_str = s->info.env->get("HTTP_X_AMZ_OBJECT_LOCK_LEGAL_HOLD");
if (obj_lock_mode_str && obj_lock_date_str) {
boost::optional<ceph::real_time> date = ceph::from_iso_8601(obj_lock_date_str);
if (boost::none == date || ceph::real_clock::to_time_t(*date) <= ceph_clock_now()) {
s->err.message = "invalid x-amz-object-lock-retain-until-date value";
ldpp_dout(this,0) << s->err.message << dendl;
return -EINVAL;
}
if (strcmp(obj_lock_mode_str, "GOVERNANCE") != 0 && strcmp(obj_lock_mode_str, "COMPLIANCE") != 0) {
s->err.message = "invalid x-amz-object-lock-mode value";
ldpp_dout(this,0) << s->err.message << dendl;
return -EINVAL;
}
obj_retention = new RGWObjectRetention(obj_lock_mode_str, *date);
} else if (obj_lock_mode_str || obj_lock_date_str) {
s->err.message = "need both x-amz-object-lock-mode and x-amz-object-lock-retain-until-date ";
ldpp_dout(this,0) << s->err.message << dendl;
return -EINVAL;
}
if (obj_legal_hold_str) {
if (strcmp(obj_legal_hold_str, "ON") != 0 && strcmp(obj_legal_hold_str, "OFF") != 0) {
s->err.message = "invalid x-amz-object-lock-legal-hold value";
ldpp_dout(this,0) << s->err.message << dendl;
return -EINVAL;
}
obj_legal_hold = new RGWObjectLegalHold(obj_legal_hold_str);
}
if_mod = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE_IF_MODIFIED_SINCE");
if_unmod = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE_IF_UNMODIFIED_SINCE");
if_match = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE_IF_MATCH");
if_nomatch = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE_IF_NONE_MATCH");
if (s->system_request) {
source_zone = s->info.args.get(RGW_SYS_PARAM_PREFIX "source-zone");
s->info.args.get_bool(RGW_SYS_PARAM_PREFIX "copy-if-newer", ©_if_newer, false);
}
const char *copy_source_temp = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE");
if (copy_source_temp) {
copy_source = copy_source_temp;
}
auto tmp_md_d = s->info.env->get("HTTP_X_AMZ_METADATA_DIRECTIVE");
if (tmp_md_d) {
if (strcasecmp(tmp_md_d, "COPY") == 0) {
attrs_mod = rgw::sal::ATTRSMOD_NONE;
} else if (strcasecmp(tmp_md_d, "REPLACE") == 0) {
attrs_mod = rgw::sal::ATTRSMOD_REPLACE;
} else if (!source_zone.empty()) {
attrs_mod = rgw::sal::ATTRSMOD_NONE; // default for intra-zone_group copy
} else {
s->err.message = "Unknown metadata directive.";
ldpp_dout(this, 0) << s->err.message << dendl;
return -EINVAL;
}
md_directive = tmp_md_d;
}
if (source_zone.empty() &&
(s->bucket->get_tenant() == s->src_tenant_name) &&
(s->bucket->get_name() == s->src_bucket_name) &&
(s->object->get_name() == s->src_object->get_name()) &&
s->src_object->get_instance().empty() &&
(attrs_mod != rgw::sal::ATTRSMOD_REPLACE)) {
need_to_check_storage_class = true;
}
return 0;
}
int RGWCopyObj_ObjStore_S3::check_storage_class(const rgw_placement_rule& src_placement)
{
if (src_placement == s->dest_placement) {
/* can only copy object into itself if replacing attrs */
s->err.message = "This copy request is illegal because it is trying to copy "
"an object to itself without changing the object's metadata, "
"storage class, website redirect location or encryption attributes.";
ldpp_dout(this, 0) << s->err.message << dendl;
return -ERR_INVALID_REQUEST;
}
return 0;
}
void RGWCopyObj_ObjStore_S3::send_partial_response(off_t ofs)
{
if (! sent_header) {
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
dump_start(s);
if (op_ret == 0) {
s->formatter->open_object_section_in_ns("CopyObjectResult", XMLNS_AWS_S3);
}
sent_header = true;
} else {
/* Send progress field. Note that this diverge from the original S3
* spec. We do this in order to keep connection alive.
*/
s->formatter->dump_int("Progress", (uint64_t)ofs);
}
rgw_flush_formatter(s, s->formatter);
}
void RGWCopyObj_ObjStore_S3::send_response()
{
if (!sent_header)
send_partial_response(0);
if (op_ret == 0) {
dump_time(s, "LastModified", mtime);
if (!etag.empty()) {
s->formatter->dump_format("ETag", "\"%s\"",etag.c_str());
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
void RGWGetACLs_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
rgw_flush_formatter(s, s->formatter);
dump_body(s, acls);
}
int RGWPutACLs_ObjStore_S3::get_params(optional_yield y)
{
int ret = RGWPutACLs_ObjStore::get_params(y);
if (ret >= 0) {
const int ret_auth = do_aws4_auth_completion();
if (ret_auth < 0) {
return ret_auth;
}
} else {
/* a request body is not required an S3 PutACLs request--n.b.,
* s->length is non-null iff a content length was parsed (the
* ACP or canned ACL could be in any of 3 headers, don't worry
* about that here) */
if ((ret == -ERR_LENGTH_REQUIRED) &&
!!(s->length)) {
return 0;
}
}
return ret;
}
int RGWPutACLs_ObjStore_S3::get_policy_from_state(rgw::sal::Driver* driver,
req_state *s,
stringstream& ss)
{
RGWAccessControlPolicy_S3 s3policy(s->cct);
// bucket-* canned acls do not apply to bucket
if (rgw::sal::Object::empty(s->object.get())) {
if (s->canned_acl.find("bucket") != string::npos)
s->canned_acl.clear();
}
int r = create_s3_policy(s, driver, s3policy, owner);
if (r < 0)
return r;
s3policy.to_xml(ss);
return 0;
}
void RGWPutACLs_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWGetLC_ObjStore_S3::execute(optional_yield y)
{
config.set_ctx(s->cct);
map<string, bufferlist>::iterator aiter = s->bucket_attrs.find(RGW_ATTR_LC);
if (aiter == s->bucket_attrs.end()) {
op_ret = -ENOENT;
return;
}
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;
op_ret = -EIO;
return;
}
}
void RGWGetLC_ObjStore_S3::send_response()
{
if (op_ret) {
if (op_ret == -ENOENT) {
set_req_state_err(s, ERR_NO_SUCH_LC);
} else {
set_req_state_err(s, op_ret);
}
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (op_ret < 0)
return;
encode_xml("LifecycleConfiguration", XMLNS_AWS_S3, config, s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWPutLC_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWDeleteLC_ObjStore_S3::send_response()
{
if (op_ret == 0)
op_ret = STATUS_NO_CONTENT;
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
}
void RGWGetCORS_ObjStore_S3::send_response()
{
if (op_ret) {
if (op_ret == -ENOENT)
set_req_state_err(s, ERR_NO_SUCH_CORS_CONFIGURATION);
else
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, NULL, to_mime_type(s->format));
dump_start(s);
if (! op_ret) {
string cors;
RGWCORSConfiguration_S3 *s3cors =
static_cast<RGWCORSConfiguration_S3 *>(&bucket_cors);
stringstream ss;
s3cors->to_xml(ss);
cors = ss.str();
dump_body(s, cors);
}
}
int RGWPutCORS_ObjStore_S3::get_params(optional_yield y)
{
RGWCORSXMLParser_S3 parser(this, s->cct);
RGWCORSConfiguration_S3 *cors_config;
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r = 0;
bufferlist data;
std::tie(r, data) = read_all_input(s, max_size, false);
if (r < 0) {
return r;
}
if (!parser.init()) {
return -EINVAL;
}
char* buf = data.c_str();
if (!buf || !parser.parse(buf, data.length(), 1)) {
return -ERR_MALFORMED_XML;
}
cors_config =
static_cast<RGWCORSConfiguration_S3 *>(parser.find_first(
"CORSConfiguration"));
if (!cors_config) {
return -ERR_MALFORMED_XML;
}
#define CORS_RULES_MAX_NUM 100
int max_num = s->cct->_conf->rgw_cors_rules_max_num;
if (max_num < 0) {
max_num = CORS_RULES_MAX_NUM;
}
int cors_rules_num = cors_config->get_rules().size();
if (cors_rules_num > max_num) {
ldpp_dout(this, 4) << "An cors config can have up to "
<< max_num
<< " rules, request cors rules num: "
<< cors_rules_num << dendl;
op_ret = -ERR_INVALID_CORS_RULES_ERROR;
s->err.message = "The number of CORS rules should not exceed allowed limit of "
+ std::to_string(max_num) + " rules.";
return -ERR_INVALID_REQUEST;
}
// forward bucket cors requests to meta master zone
if (!driver->is_meta_master()) {
/* only need to keep this data around if we're not meta master */
in_data.append(data);
}
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 15>()) {
ldpp_dout(this, 15) << "CORSConfiguration";
cors_config->to_xml(*_dout);
*_dout << dendl;
}
cors_config->encode(cors_bl);
return 0;
}
void RGWPutCORS_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, NULL, to_mime_type(s->format));
dump_start(s);
}
void RGWDeleteCORS_ObjStore_S3::send_response()
{
int r = op_ret;
if (!r || r == -ENOENT)
r = STATUS_NO_CONTENT;
set_req_state_err(s, r);
dump_errno(s);
end_header(s, NULL);
}
void RGWOptionsCORS_ObjStore_S3::send_response()
{
string hdrs, exp_hdrs;
uint32_t max_age = CORS_MAX_AGE_INVALID;
/*EACCES means, there is no CORS registered yet for the bucket
*ENOENT means, there is no match of the Origin in the list of CORSRule
*/
if (op_ret == -ENOENT)
op_ret = -EACCES;
if (op_ret < 0) {
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, NULL);
return;
}
get_response_params(hdrs, exp_hdrs, &max_age);
dump_errno(s);
dump_access_control(s, origin, req_meth, hdrs.c_str(), exp_hdrs.c_str(),
max_age);
end_header(s, NULL);
}
void RGWPutBucketEncryption_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
void RGWGetBucketEncryption_ObjStore_S3::send_response()
{
if (op_ret) {
if (op_ret == -ENOENT)
set_req_state_err(s, ERR_NO_SUCH_BUCKET_ENCRYPTION_CONFIGURATION);
else
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (!op_ret) {
encode_xml("ServerSideEncryptionConfiguration", XMLNS_AWS_S3,
bucket_encryption_conf, s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
void RGWDeleteBucketEncryption_ObjStore_S3::send_response()
{
if (op_ret == 0) {
op_ret = STATUS_NO_CONTENT;
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s);
}
void RGWGetRequestPayment_ObjStore_S3::send_response()
{
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
s->formatter->open_object_section_in_ns("RequestPaymentConfiguration", XMLNS_AWS_S3);
const char *payer = requester_pays ? "Requester" : "BucketOwner";
s->formatter->dump_string("Payer", payer);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
class RGWSetRequestPaymentParser : public RGWXMLParser
{
XMLObj *alloc_obj(const char *el) override {
return new XMLObj;
}
public:
RGWSetRequestPaymentParser() {}
~RGWSetRequestPaymentParser() override {}
int get_request_payment_payer(bool *requester_pays) {
XMLObj *config = find_first("RequestPaymentConfiguration");
if (!config)
return -EINVAL;
*requester_pays = false;
XMLObj *field = config->find_first("Payer");
if (!field)
return 0;
auto& s = field->get_data();
if (stringcasecmp(s, "Requester") == 0) {
*requester_pays = true;
} else if (stringcasecmp(s, "BucketOwner") != 0) {
return -EINVAL;
}
return 0;
}
};
int RGWSetRequestPayment_ObjStore_S3::get_params(optional_yield y)
{
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int r = 0;
std::tie(r, in_data) = read_all_input(s, max_size, false);
if (r < 0) {
return r;
}
RGWSetRequestPaymentParser parser;
if (!parser.init()) {
ldpp_dout(this, 0) << "ERROR: failed to initialize parser" << dendl;
return -EIO;
}
char* buf = in_data.c_str();
if (!parser.parse(buf, in_data.length(), 1)) {
ldpp_dout(this, 10) << "failed to parse data: " << buf << dendl;
return -EINVAL;
}
return parser.get_request_payment_payer(&requester_pays);
}
void RGWSetRequestPayment_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s);
}
int RGWInitMultipart_ObjStore_S3::get_params(optional_yield y)
{
int ret;
ret = get_encryption_defaults(s);
if (ret < 0) {
ldpp_dout(this, 5) << __func__ << "(): get_encryption_defaults() returned ret=" << ret << dendl;
return ret;
}
RGWAccessControlPolicy_S3 s3policy(s->cct);
ret = create_s3_policy(s, driver, s3policy, s->owner);
if (ret < 0)
return ret;
policy = s3policy;
return 0;
}
void RGWInitMultipart_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
for (auto &it : crypt_http_responses)
dump_header(s, it.first, it.second);
ceph::real_time abort_date;
string rule_id;
bool exist_multipart_abort = get_s3_multipart_abort_header(s, mtime, abort_date, rule_id);
if (exist_multipart_abort) {
dump_time_header(s, "x-amz-abort-date", abort_date);
dump_header_if_nonempty(s, "x-amz-abort-rule-id", rule_id);
}
end_header(s, this, to_mime_type(s->format));
if (op_ret == 0) {
dump_start(s);
s->formatter->open_object_section_in_ns("InitiateMultipartUploadResult", XMLNS_AWS_S3);
if (!s->bucket_tenant.empty())
s->formatter->dump_string("Tenant", s->bucket_tenant);
s->formatter->dump_string("Bucket", s->bucket_name);
s->formatter->dump_string("Key", s->object->get_name());
s->formatter->dump_string("UploadId", upload_id);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
int RGWInitMultipart_ObjStore_S3::prepare_encryption(map<string, bufferlist>& attrs)
{
int res = 0;
res = rgw_s3_prepare_encrypt(s, attrs, nullptr, crypt_http_responses);
return res;
}
int RGWCompleteMultipart_ObjStore_S3::get_params(optional_yield y)
{
int ret = RGWCompleteMultipart_ObjStore::get_params(y);
if (ret < 0) {
return ret;
}
map_qs_metadata(s, true);
return do_aws4_auth_completion();
}
void RGWCompleteMultipart_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
dump_header_if_nonempty(s, "x-amz-version-id", version_id);
end_header(s, this, to_mime_type(s->format));
if (op_ret == 0) {
dump_start(s);
s->formatter->open_object_section_in_ns("CompleteMultipartUploadResult", XMLNS_AWS_S3);
std::string base_uri = compute_domain_uri(s);
if (!s->bucket_tenant.empty()) {
s->formatter->dump_format("Location", "%s/%s:%s/%s",
base_uri.c_str(),
s->bucket_tenant.c_str(),
s->bucket_name.c_str(),
s->object->get_name().c_str()
);
s->formatter->dump_string("Tenant", s->bucket_tenant);
} else {
s->formatter->dump_format("Location", "%s/%s/%s",
base_uri.c_str(),
s->bucket_name.c_str(),
s->object->get_name().c_str()
);
}
s->formatter->dump_string("Bucket", s->bucket_name);
s->formatter->dump_string("Key", s->object->get_name());
s->formatter->dump_string("ETag", etag);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
void RGWAbortMultipart_ObjStore_S3::send_response()
{
int r = op_ret;
if (!r)
r = STATUS_NO_CONTENT;
set_req_state_err(s, r);
dump_errno(s);
end_header(s, this);
}
void RGWListMultipart_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
if (op_ret == 0) {
dump_start(s);
s->formatter->open_object_section_in_ns("ListPartsResult", XMLNS_AWS_S3);
map<uint32_t, std::unique_ptr<rgw::sal::MultipartPart>>::iterator iter;
map<uint32_t, std::unique_ptr<rgw::sal::MultipartPart>>::reverse_iterator test_iter;
int cur_max = 0;
iter = upload->get_parts().begin();
test_iter = upload->get_parts().rbegin();
if (test_iter != upload->get_parts().rend()) {
cur_max = test_iter->first;
}
if (!s->bucket_tenant.empty())
s->formatter->dump_string("Tenant", s->bucket_tenant);
s->formatter->dump_string("Bucket", s->bucket_name);
s->formatter->dump_string("Key", s->object->get_name());
s->formatter->dump_string("UploadId", upload_id);
s->formatter->dump_string("StorageClass", placement->get_storage_class());
s->formatter->dump_int("PartNumberMarker", marker);
s->formatter->dump_int("NextPartNumberMarker", cur_max);
s->formatter->dump_int("MaxParts", max_parts);
s->formatter->dump_string("IsTruncated", (truncated ? "true" : "false"));
ACLOwner& owner = policy.get_owner();
dump_owner(s, owner.get_id(), owner.get_display_name());
for (; iter != upload->get_parts().end(); ++iter) {
rgw::sal::MultipartPart* part = iter->second.get();
s->formatter->open_object_section("Part");
dump_time(s, "LastModified", part->get_mtime());
s->formatter->dump_unsigned("PartNumber", part->get_num());
s->formatter->dump_format("ETag", "\"%s\"", part->get_etag().c_str());
s->formatter->dump_unsigned("Size", part->get_size());
s->formatter->close_section();
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
void RGWListBucketMultiparts_ObjStore_S3::send_response()
{
if (op_ret < 0)
set_req_state_err(s, op_ret);
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
dump_start(s);
if (op_ret < 0)
return;
s->formatter->open_object_section_in_ns("ListMultipartUploadsResult", XMLNS_AWS_S3);
if (!s->bucket_tenant.empty())
s->formatter->dump_string("Tenant", s->bucket_tenant);
s->formatter->dump_string("Bucket", s->bucket_name);
if (!prefix.empty())
s->formatter->dump_string("Prefix", prefix);
if (!marker_key.empty())
s->formatter->dump_string("KeyMarker", marker_key);
if (!marker_upload_id.empty())
s->formatter->dump_string("UploadIdMarker", marker_upload_id);
if (!next_marker_key.empty())
s->formatter->dump_string("NextKeyMarker", next_marker_key);
if (!next_marker_upload_id.empty())
s->formatter->dump_string("NextUploadIdMarker", next_marker_upload_id);
s->formatter->dump_int("MaxUploads", max_uploads);
if (!delimiter.empty())
s->formatter->dump_string("Delimiter", delimiter);
s->formatter->dump_string("IsTruncated", (is_truncated ? "true" : "false"));
if (op_ret >= 0) {
vector<std::unique_ptr<rgw::sal::MultipartUpload>>::iterator iter;
for (iter = uploads.begin(); iter != uploads.end(); ++iter) {
rgw::sal::MultipartUpload* upload = iter->get();
s->formatter->open_array_section("Upload");
if (encode_url) {
s->formatter->dump_string("Key", url_encode(upload->get_key(), false));
} else {
s->formatter->dump_string("Key", upload->get_key());
}
s->formatter->dump_string("UploadId", upload->get_upload_id());
const ACLOwner& owner = upload->get_owner();
dump_owner(s, owner.get_id(), owner.get_display_name(), "Initiator");
dump_owner(s, owner.get_id(), owner.get_display_name()); // Owner
s->formatter->dump_string("StorageClass", "STANDARD");
dump_time(s, "Initiated", upload->get_mtime());
s->formatter->close_section();
}
if (!common_prefixes.empty()) {
s->formatter->open_array_section("CommonPrefixes");
for (const auto& kv : common_prefixes) {
if (encode_url) {
s->formatter->dump_string("Prefix", url_encode(kv.first, false));
} else {
s->formatter->dump_string("Prefix", kv.first);
}
}
s->formatter->close_section();
}
}
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
int RGWDeleteMultiObj_ObjStore_S3::get_params(optional_yield y)
{
int ret = RGWDeleteMultiObj_ObjStore::get_params(y);
if (ret < 0) {
return ret;
}
const char *bypass_gov_header = s->info.env->get("HTTP_X_AMZ_BYPASS_GOVERNANCE_RETENTION");
if (bypass_gov_header) {
std::string bypass_gov_decoded = url_decode(bypass_gov_header);
bypass_governance_mode = boost::algorithm::iequals(bypass_gov_decoded, "true");
}
return do_aws4_auth_completion();
}
void RGWDeleteMultiObj_ObjStore_S3::send_status()
{
if (! status_dumped) {
if (op_ret < 0)
set_req_state_err(s, op_ret);
dump_errno(s);
status_dumped = true;
}
}
void RGWDeleteMultiObj_ObjStore_S3::begin_response()
{
if (!status_dumped) {
send_status();
}
dump_start(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, to_mime_type(s->format), CHUNKED_TRANSFER_ENCODING);
s->formatter->open_object_section_in_ns("DeleteResult", XMLNS_AWS_S3);
rgw_flush_formatter(s, s->formatter);
}
void RGWDeleteMultiObj_ObjStore_S3::send_partial_response(const rgw_obj_key& key,
bool delete_marker,
const string& marker_version_id,
int ret,
boost::asio::deadline_timer *formatter_flush_cond)
{
if (!key.empty()) {
delete_multi_obj_entry ops_log_entry;
ops_log_entry.key = key.name;
ops_log_entry.version_id = key.instance;
if (ret == 0) {
ops_log_entry.error = false;
ops_log_entry.http_status = 200;
ops_log_entry.delete_marker = delete_marker;
if (delete_marker) {
ops_log_entry.marker_version_id = marker_version_id;
}
if (!quiet) {
s->formatter->open_object_section("Deleted");
s->formatter->dump_string("Key", key.name);
if (!key.instance.empty()) {
s->formatter->dump_string("VersionId", key.instance);
}
if (delete_marker) {
s->formatter->dump_bool("DeleteMarker", true);
s->formatter->dump_string("DeleteMarkerVersionId", marker_version_id);
}
s->formatter->close_section();
}
} else if (ret < 0) {
struct rgw_http_error r;
int err_no;
s->formatter->open_object_section("Error");
err_no = -ret;
rgw_get_errno_s3(&r, err_no);
ops_log_entry.error = true;
ops_log_entry.http_status = r.http_ret;
ops_log_entry.error_message = r.s3_code;
s->formatter->dump_string("Key", key.name);
s->formatter->dump_string("VersionId", key.instance);
s->formatter->dump_string("Code", r.s3_code);
s->formatter->dump_string("Message", r.s3_code);
s->formatter->close_section();
}
ops_log_entries.push_back(std::move(ops_log_entry));
if (formatter_flush_cond) {
formatter_flush_cond->cancel();
} else {
rgw_flush_formatter(s, s->formatter);
}
}
}
void RGWDeleteMultiObj_ObjStore_S3::end_response()
{
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWGetObjLayout_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, "application/json");
JSONFormatter f;
if (op_ret < 0) {
return;
}
f.open_object_section("result");
s->object->dump_obj_layout(this, s->yield, &f);
f.close_section();
rgw_flush_formatter(s, &f);
}
int RGWConfigBucketMetaSearch_ObjStore_S3::get_params(optional_yield y)
{
auto iter = s->info.x_meta_map.find("x-amz-meta-search");
if (iter == s->info.x_meta_map.end()) {
s->err.message = "X-Rgw-Meta-Search header not provided";
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
}
list<string> expressions;
get_str_list(iter->second, ",", expressions);
for (auto& expression : expressions) {
vector<string> args;
get_str_vec(expression, ";", args);
if (args.empty()) {
s->err.message = "invalid empty expression";
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
}
if (args.size() > 2) {
s->err.message = string("invalid expression: ") + expression;
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
}
string key = boost::algorithm::to_lower_copy(rgw_trim_whitespace(args[0]));
string val;
if (args.size() > 1) {
val = boost::algorithm::to_lower_copy(rgw_trim_whitespace(args[1]));
}
if (!boost::algorithm::starts_with(key, RGW_AMZ_META_PREFIX)) {
s->err.message = string("invalid expression, key must start with '" RGW_AMZ_META_PREFIX "' : ") + expression;
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
}
key = key.substr(sizeof(RGW_AMZ_META_PREFIX) - 1);
ESEntityTypeMap::EntityType entity_type;
if (val.empty() || val == "str" || val == "string") {
entity_type = ESEntityTypeMap::ES_ENTITY_STR;
} else if (val == "int" || val == "integer") {
entity_type = ESEntityTypeMap::ES_ENTITY_INT;
} else if (val == "date" || val == "datetime") {
entity_type = ESEntityTypeMap::ES_ENTITY_DATE;
} else {
s->err.message = string("invalid entity type: ") + val;
ldpp_dout(this, 5) << s->err.message << dendl;
return -EINVAL;
}
mdsearch_config[key] = entity_type;
}
return 0;
}
void RGWConfigBucketMetaSearch_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this);
}
void RGWGetBucketMetaSearch_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, NULL, to_mime_type(s->format));
Formatter *f = s->formatter;
f->open_array_section("GetBucketMetaSearchResult");
for (auto& e : s->bucket->get_info().mdsearch_config) {
f->open_object_section("Entry");
string k = string("x-amz-meta-") + e.first;
f->dump_string("Key", k.c_str());
const char *type;
switch (e.second) {
case ESEntityTypeMap::ES_ENTITY_INT:
type = "int";
break;
case ESEntityTypeMap::ES_ENTITY_DATE:
type = "date";
break;
default:
type = "str";
}
f->dump_string("Type", type);
f->close_section();
}
f->close_section();
rgw_flush_formatter(s, f);
}
void RGWDelBucketMetaSearch_ObjStore_S3::send_response()
{
if (op_ret)
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this);
}
void RGWPutBucketObjectLock_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
void RGWGetBucketObjectLock_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (op_ret) {
return;
}
encode_xml("ObjectLockConfiguration", s->bucket->get_info().obj_lock, s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
int RGWPutObjRetention_ObjStore_S3::get_params(optional_yield y)
{
const char *bypass_gov_header = s->info.env->get("HTTP_X_AMZ_BYPASS_GOVERNANCE_RETENTION");
if (bypass_gov_header) {
std::string bypass_gov_decoded = url_decode(bypass_gov_header);
bypass_governance_mode = boost::algorithm::iequals(bypass_gov_decoded, "true");
}
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 RGWPutObjRetention_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
void RGWGetObjRetention_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (op_ret) {
return;
}
encode_xml("Retention", obj_retention, s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWPutObjLegalHold_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
void RGWGetObjLegalHold_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
if (op_ret) {
return;
}
encode_xml("LegalHold", obj_legal_hold, s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWGetBucketPolicyStatus_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
s->formatter->open_object_section_in_ns("PolicyStatus", XMLNS_AWS_S3);
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETPolicyStatus.html
// mentions TRUE and FALSE, but boto/aws official clients seem to want lower
// case which is returned by AWS as well; so let's be bug to bug compatible
// with the API
s->formatter->dump_bool("IsPublic", isPublic);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWPutBucketPublicAccessBlock_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
void RGWGetBucketPublicAccessBlock_ObjStore_S3::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, to_mime_type(s->format));
dump_start(s);
access_conf.dump_xml(s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
RGWOp *RGWHandler_REST_Service_S3::op_get()
{
if (is_usage_op()) {
return new RGWGetUsage_ObjStore_S3;
} else {
return new RGWListBuckets_ObjStore_S3;
}
}
RGWOp *RGWHandler_REST_Service_S3::op_head()
{
return new RGWListBuckets_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Bucket_S3::get_obj_op(bool get_data) const
{
// Non-website mode
if (get_data) {
int list_type = 1;
s->info.args.get_int("list-type", &list_type, 1);
switch (list_type) {
case 1:
return new RGWListBucket_ObjStore_S3;
case 2:
return new RGWListBucket_ObjStore_S3v2;
default:
ldpp_dout(s, 5) << __func__ << ": unsupported list-type " << list_type << dendl;
return new RGWListBucket_ObjStore_S3;
}
} else {
return new RGWStatBucket_ObjStore_S3;
}
}
RGWOp *RGWHandler_REST_Bucket_S3::op_get()
{
if (s->info.args.sub_resource_exists("encryption"))
return nullptr;
if (s->info.args.sub_resource_exists("logging"))
return new RGWGetBucketLogging_ObjStore_S3;
if (s->info.args.sub_resource_exists("location"))
return new RGWGetBucketLocation_ObjStore_S3;
if (s->info.args.sub_resource_exists("versioning"))
return new RGWGetBucketVersioning_ObjStore_S3;
if (s->info.args.sub_resource_exists("website")) {
if (!s->cct->_conf->rgw_enable_static_website) {
return NULL;
}
return new RGWGetBucketWebsite_ObjStore_S3;
}
if (s->info.args.exists("mdsearch")) {
return new RGWGetBucketMetaSearch_ObjStore_S3;
}
if (is_acl_op()) {
return new RGWGetACLs_ObjStore_S3;
} else if (is_cors_op()) {
return new RGWGetCORS_ObjStore_S3;
} else if (is_request_payment_op()) {
return new RGWGetRequestPayment_ObjStore_S3;
} else if (s->info.args.exists("uploads")) {
return new RGWListBucketMultiparts_ObjStore_S3;
} else if(is_lc_op()) {
return new RGWGetLC_ObjStore_S3;
} else if(is_policy_op()) {
return new RGWGetBucketPolicy;
} else if (is_tagging_op()) {
return new RGWGetBucketTags_ObjStore_S3;
} else if (is_object_lock_op()) {
return new RGWGetBucketObjectLock_ObjStore_S3;
} else if (is_notification_op()) {
return RGWHandler_REST_PSNotifs_S3::create_get_op();
} else if (is_replication_op()) {
return new RGWGetBucketReplication_ObjStore_S3;
} else if (is_policy_status_op()) {
return new RGWGetBucketPolicyStatus_ObjStore_S3;
} else if (is_block_public_access_op()) {
return new RGWGetBucketPublicAccessBlock_ObjStore_S3;
} else if (is_bucket_encryption_op()) {
return new RGWGetBucketEncryption_ObjStore_S3;
}
return get_obj_op(true);
}
RGWOp *RGWHandler_REST_Bucket_S3::op_head()
{
if (is_acl_op()) {
return new RGWGetACLs_ObjStore_S3;
} else if (s->info.args.exists("uploads")) {
return new RGWListBucketMultiparts_ObjStore_S3;
}
return get_obj_op(false);
}
RGWOp *RGWHandler_REST_Bucket_S3::op_put()
{
if (s->info.args.sub_resource_exists("logging") ||
s->info.args.sub_resource_exists("encryption"))
return nullptr;
if (s->info.args.sub_resource_exists("versioning"))
return new RGWSetBucketVersioning_ObjStore_S3;
if (s->info.args.sub_resource_exists("website")) {
if (!s->cct->_conf->rgw_enable_static_website) {
return NULL;
}
return new RGWSetBucketWebsite_ObjStore_S3;
}
if (is_tagging_op()) {
return new RGWPutBucketTags_ObjStore_S3;
} else if (is_acl_op()) {
return new RGWPutACLs_ObjStore_S3;
} else if (is_cors_op()) {
return new RGWPutCORS_ObjStore_S3;
} else if (is_request_payment_op()) {
return new RGWSetRequestPayment_ObjStore_S3;
} else if(is_lc_op()) {
return new RGWPutLC_ObjStore_S3;
} else if(is_policy_op()) {
return new RGWPutBucketPolicy;
} else if (is_object_lock_op()) {
return new RGWPutBucketObjectLock_ObjStore_S3;
} else if (is_notification_op()) {
return RGWHandler_REST_PSNotifs_S3::create_put_op();
} else if (is_replication_op()) {
RGWBucketSyncPolicyHandlerRef sync_policy_handler;
int ret = driver->get_sync_policy_handler(s, nullopt, nullopt,
&sync_policy_handler, null_yield);
if (ret < 0 || !sync_policy_handler ||
sync_policy_handler->is_legacy_config()) {
return nullptr;
}
return new RGWPutBucketReplication_ObjStore_S3;
} else if (is_block_public_access_op()) {
return new RGWPutBucketPublicAccessBlock_ObjStore_S3;
} else if (is_bucket_encryption_op()) {
return new RGWPutBucketEncryption_ObjStore_S3;
}
return new RGWCreateBucket_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Bucket_S3::op_delete()
{
if (s->info.args.sub_resource_exists("logging") ||
s->info.args.sub_resource_exists("encryption"))
return nullptr;
if (is_tagging_op()) {
return new RGWDeleteBucketTags_ObjStore_S3;
} else if (is_cors_op()) {
return new RGWDeleteCORS_ObjStore_S3;
} else if(is_lc_op()) {
return new RGWDeleteLC_ObjStore_S3;
} else if(is_policy_op()) {
return new RGWDeleteBucketPolicy;
} else if (is_notification_op()) {
return RGWHandler_REST_PSNotifs_S3::create_delete_op();
} else if (is_replication_op()) {
return new RGWDeleteBucketReplication_ObjStore_S3;
} else if (is_block_public_access_op()) {
return new RGWDeleteBucketPublicAccessBlock;
} else if (is_bucket_encryption_op()) {
return new RGWDeleteBucketEncryption_ObjStore_S3;
}
if (s->info.args.sub_resource_exists("website")) {
if (!s->cct->_conf->rgw_enable_static_website) {
return NULL;
}
return new RGWDeleteBucketWebsite_ObjStore_S3;
}
if (s->info.args.exists("mdsearch")) {
return new RGWDelBucketMetaSearch_ObjStore_S3;
}
return new RGWDeleteBucket_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Bucket_S3::op_post()
{
if (s->info.args.exists("delete")) {
return new RGWDeleteMultiObj_ObjStore_S3;
}
if (s->info.args.exists("mdsearch")) {
return new RGWConfigBucketMetaSearch_ObjStore_S3;
}
return new RGWPostObj_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Bucket_S3::op_options()
{
return new RGWOptionsCORS_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Obj_S3::get_obj_op(bool get_data)
{
RGWGetObj_ObjStore_S3 *get_obj_op = new RGWGetObj_ObjStore_S3;
get_obj_op->set_get_data(get_data);
return get_obj_op;
}
RGWOp *RGWHandler_REST_Obj_S3::op_get()
{
if (is_acl_op()) {
return new RGWGetACLs_ObjStore_S3;
} else if (s->info.args.exists("uploadId")) {
return new RGWListMultipart_ObjStore_S3;
} else if (s->info.args.exists("layout")) {
return new RGWGetObjLayout_ObjStore_S3;
} else if (is_tagging_op()) {
return new RGWGetObjTags_ObjStore_S3;
} else if (is_obj_retention_op()) {
return new RGWGetObjRetention_ObjStore_S3;
} else if (is_obj_legal_hold_op()) {
return new RGWGetObjLegalHold_ObjStore_S3;
}
return get_obj_op(true);
}
RGWOp *RGWHandler_REST_Obj_S3::op_head()
{
if (is_acl_op()) {
return new RGWGetACLs_ObjStore_S3;
} else if (s->info.args.exists("uploadId")) {
return new RGWListMultipart_ObjStore_S3;
}
return get_obj_op(false);
}
RGWOp *RGWHandler_REST_Obj_S3::op_put()
{
if (is_acl_op()) {
return new RGWPutACLs_ObjStore_S3;
} else if (is_tagging_op()) {
return new RGWPutObjTags_ObjStore_S3;
} else if (is_obj_retention_op()) {
return new RGWPutObjRetention_ObjStore_S3;
} else if (is_obj_legal_hold_op()) {
return new RGWPutObjLegalHold_ObjStore_S3;
}
if (s->init_state.src_bucket.empty())
return new RGWPutObj_ObjStore_S3;
else
return new RGWCopyObj_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Obj_S3::op_delete()
{
if (is_tagging_op()) {
return new RGWDeleteObjTags_ObjStore_S3;
}
string upload_id = s->info.args.get("uploadId");
if (upload_id.empty())
return new RGWDeleteObj_ObjStore_S3;
else
return new RGWAbortMultipart_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Obj_S3::op_post()
{
if (s->info.args.exists("uploadId"))
return new RGWCompleteMultipart_ObjStore_S3;
if (s->info.args.exists("uploads"))
return new RGWInitMultipart_ObjStore_S3;
if (is_select_op())
return rgw::s3select::create_s3select_op();
return new RGWPostObj_ObjStore_S3;
}
RGWOp *RGWHandler_REST_Obj_S3::op_options()
{
return new RGWOptionsCORS_ObjStore_S3;
}
int RGWHandler_REST_S3::init_from_header(rgw::sal::Driver* driver,
req_state* s,
RGWFormat default_formatter,
bool configurable_format)
{
string req;
string first;
const char *req_name = s->relative_uri.c_str();
const char *p;
if (*req_name == '?') {
p = req_name;
} else {
p = s->info.request_params.c_str();
}
s->info.args.set(p);
s->info.args.parse(s);
/* must be called after the args parsing */
int ret = allocate_formatter(s, default_formatter, configurable_format);
if (ret < 0)
return ret;
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;
}
/*
* XXX The intent of the check for empty is apparently to let the bucket
* name from DNS to be set ahead. However, we currently take the DNS
* bucket and re-insert it into URL in rgw_rest.cc:RGWREST::preprocess().
* So, this check is meaningless.
*
* Rather than dropping this, the code needs to be changed into putting
* the bucket (and its tenant) from DNS and Host: header (HTTP_HOST)
* into req_status.bucket_name directly.
*/
if (s->init_state.url_bucket.empty()) {
// Save bucket to tide us over until token is parsed.
s->init_state.url_bucket = first;
string encoded_obj_str;
if (pos >= 0) {
encoded_obj_str = req.substr(pos+1);
}
/* dang: s->bucket is never set here, since it's created with permissions.
* These calls will always create an object with no bucket. */
if (!encoded_obj_str.empty()) {
if (s->bucket) {
s->object = s->bucket->get_object(rgw_obj_key(encoded_obj_str, s->info.args.get("versionId")));
} else {
s->object = driver->get_object(rgw_obj_key(encoded_obj_str, s->info.args.get("versionId")));
}
}
} else {
if (s->bucket) {
s->object = s->bucket->get_object(rgw_obj_key(req_name, s->info.args.get("versionId")));
} else {
s->object = driver->get_object(rgw_obj_key(req_name, s->info.args.get("versionId")));
}
}
return 0;
}
int RGWHandler_REST_S3::postauth_init(optional_yield y)
{
struct req_init_state *t = &s->init_state;
int ret = rgw_parse_url_bucket(t->url_bucket, s->user->get_tenant(),
s->bucket_tenant, s->bucket_name);
if (ret) {
return ret;
}
if (s->auth.identity->get_identity_type() == TYPE_ROLE) {
s->bucket_tenant = s->auth.identity->get_role_tenant();
}
ldpp_dout(s, 10) << "s->object=" << s->object
<< " s->bucket=" << rgw_make_bucket_entry_name(s->bucket_tenant, s->bucket_name) << dendl;
ret = rgw_validate_tenant_name(s->bucket_tenant);
if (ret)
return ret;
if (!s->bucket_name.empty() && !rgw::sal::Object::empty(s->object.get())) {
ret = validate_object_name(s->object->get_name());
if (ret)
return ret;
}
if (!t->src_bucket.empty()) {
string auth_tenant;
if (s->auth.identity->get_identity_type() == TYPE_ROLE) {
auth_tenant = s->auth.identity->get_role_tenant();
} else {
auth_tenant = s->user->get_tenant();
}
ret = rgw_parse_url_bucket(t->src_bucket, auth_tenant,
s->src_tenant_name, s->src_bucket_name);
if (ret) {
return ret;
}
ret = rgw_validate_tenant_name(s->src_tenant_name);
if (ret)
return ret;
}
const char *mfa = s->info.env->get("HTTP_X_AMZ_MFA");
if (mfa) {
ret = s->user->verify_mfa(string(mfa), &s->mfa_verified, s, y);
}
return 0;
}
int RGWHandler_REST_S3::init(rgw::sal::Driver* driver, req_state *s,
rgw::io::BasicClient *cio)
{
int ret;
s->dialect = "s3";
ret = rgw_validate_tenant_name(s->bucket_tenant);
if (ret)
return ret;
if (!s->bucket_name.empty()) {
ret = validate_object_name(s->object->get_name());
if (ret)
return ret;
}
const char *cacl = s->info.env->get("HTTP_X_AMZ_ACL");
if (cacl)
s->canned_acl = cacl;
s->has_acl_header = s->info.env->exists_prefix("HTTP_X_AMZ_GRANT");
const char *copy_source = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE");
if (copy_source &&
(! s->info.env->get("HTTP_X_AMZ_COPY_SOURCE_RANGE")) &&
(! s->info.args.exists("uploadId"))) {
rgw_obj_key key;
ret = RGWCopyObj::parse_copy_location(copy_source,
s->init_state.src_bucket,
key,
s);
if (!ret) {
ldpp_dout(s, 0) << "failed to parse copy location" << dendl;
return -EINVAL; // XXX why not -ERR_INVALID_BUCKET_NAME or -ERR_BAD_URL?
}
s->src_object = driver->get_object(key);
}
const char *sc = s->info.env->get("HTTP_X_AMZ_STORAGE_CLASS");
if (sc) {
s->info.storage_class = sc;
}
return RGWHandler_REST::init(driver, s, cio);
}
int RGWHandler_REST_S3::authorize(const DoutPrefixProvider *dpp, optional_yield y)
{
if (s->info.args.exists("Action") && s->info.args.get("Action") == "AssumeRoleWithWebIdentity") {
return RGW_Auth_STS::authorize(dpp, driver, auth_registry, s, y);
}
return RGW_Auth_S3::authorize(dpp, driver, auth_registry, s, y);
}
enum class AwsVersion {
UNKNOWN,
V2,
V4
};
enum class AwsRoute {
UNKNOWN,
QUERY_STRING,
HEADERS
};
static inline std::pair<AwsVersion, AwsRoute>
discover_aws_flavour(const req_info& info)
{
using rgw::auth::s3::AWS4_HMAC_SHA256_STR;
AwsVersion version = AwsVersion::UNKNOWN;
AwsRoute route = AwsRoute::UNKNOWN;
const char* http_auth = info.env->get("HTTP_AUTHORIZATION");
if (http_auth && http_auth[0]) {
/* Authorization in Header */
route = AwsRoute::HEADERS;
if (!strncmp(http_auth, AWS4_HMAC_SHA256_STR,
strlen(AWS4_HMAC_SHA256_STR))) {
/* AWS v4 */
version = AwsVersion::V4;
} else if (!strncmp(http_auth, "AWS ", 4)) {
/* AWS v2 */
version = AwsVersion::V2;
}
} else {
route = AwsRoute::QUERY_STRING;
if (info.args.get("x-amz-algorithm") == AWS4_HMAC_SHA256_STR) {
/* AWS v4 */
version = AwsVersion::V4;
} else if (!info.args.get("AWSAccessKeyId").empty()) {
/* AWS v2 */
version = AwsVersion::V2;
}
}
return std::make_pair(version, route);
}
/*
* verify that a signed request comes from the keyholder
* by checking the signature against our locally-computed version
*
* it tries AWS v4 before AWS v2
*/
int RGW_Auth_S3::authorize(const DoutPrefixProvider *dpp,
rgw::sal::Driver* const driver,
const rgw::auth::StrategyRegistry& auth_registry,
req_state* const s, optional_yield y)
{
/* neither keystone and rados enabled; warn and exit! */
if (!driver->ctx()->_conf->rgw_s3_auth_use_rados &&
!driver->ctx()->_conf->rgw_s3_auth_use_keystone &&
!driver->ctx()->_conf->rgw_s3_auth_use_ldap) {
ldpp_dout(dpp, 0) << "WARNING: no authorization backend enabled! Users will never authenticate." << dendl;
return -EPERM;
}
const auto ret = rgw::auth::Strategy::apply(dpp, auth_registry.get_s3_main(), s, y);
if (ret == 0) {
/* Populate the owner info. */
s->owner.set_id(s->user->get_id());
s->owner.set_name(s->user->get_display_name());
}
return ret;
}
int RGWHandler_Auth_S3::init(rgw::sal::Driver* driver, req_state *state,
rgw::io::BasicClient *cio)
{
int ret = RGWHandler_REST_S3::init_from_header(driver, state, RGWFormat::JSON, true);
if (ret < 0)
return ret;
return RGWHandler_REST::init(driver, state, cio);
}
namespace {
// utility classes and functions for handling parameters with the following format:
// Attributes.entry.{N}.{key|value}={VALUE}
// N - any unsigned number
// VALUE - url encoded string
// and Attribute is holding key and value
// ctor and set are done according to the "type" argument
// if type is not "key" or "value" its a no-op
class Attribute {
std::string key;
std::string value;
public:
Attribute(const std::string& type, const std::string& key_or_value) {
set(type, key_or_value);
}
void set(const std::string& type, const std::string& key_or_value) {
if (type == "key") {
key = key_or_value;
} else if (type == "value") {
value = key_or_value;
}
}
const std::string& get_key() const { return key; }
const std::string& get_value() const { return value; }
};
using AttributeMap = std::map<unsigned, Attribute>;
// aggregate the attributes into a map
// the key and value are associated by the index (N)
// no assumptions are made on the order in which these parameters are added
void update_attribute_map(const std::string& input, AttributeMap& map) {
const boost::char_separator<char> sep(".");
const boost::tokenizer tokens(input, sep);
auto token = tokens.begin();
if (*token != "Attributes") {
return;
}
++token;
if (*token != "entry") {
return;
}
++token;
unsigned idx;
try {
idx = std::stoul(*token);
} catch (const std::invalid_argument&) {
return;
}
++token;
std::string key_or_value = "";
// get the rest of the string regardless of dots
// this is to allow dots in the value
while (token != tokens.end()) {
key_or_value.append(*token+".");
++token;
}
// remove last separator
key_or_value.pop_back();
auto pos = key_or_value.find("=");
if (pos != std::string::npos) {
const auto key_or_value_lhs = key_or_value.substr(0, pos);
const auto key_or_value_rhs = url_decode(key_or_value.substr(pos + 1, key_or_value.size() - 1));
const auto map_it = map.find(idx);
if (map_it == map.end()) {
// new entry
map.emplace(std::make_pair(idx, Attribute(key_or_value_lhs, key_or_value_rhs)));
} else {
// existing entry
map_it->second.set(key_or_value_lhs, key_or_value_rhs);
}
}
}
}
void parse_post_action(const std::string& post_body, req_state* s)
{
if (post_body.size() > 0) {
ldpp_dout(s, 10) << "Content of POST: " << post_body << dendl;
if (post_body.find("Action") != string::npos) {
const boost::char_separator<char> sep("&");
const boost::tokenizer<boost::char_separator<char>> tokens(post_body, sep);
AttributeMap map;
for (const auto& t : tokens) {
const auto pos = t.find("=");
if (pos != string::npos) {
const auto key = t.substr(0, pos);
if (boost::starts_with(key, "Attributes.")) {
update_attribute_map(t, map);
} else {
s->info.args.append(t.substr(0, pos),
url_decode(t.substr(pos+1, t.size() -1)));
}
}
}
// update the regular args with the content of the attribute map
for (const auto& attr : map) {
s->info.args.append(attr.second.get_key(), attr.second.get_value());
}
}
}
const auto payload_hash = rgw::auth::s3::calc_v4_payload_hash(post_body);
s->info.args.append("PayloadHash", payload_hash);
}
RGWHandler_REST* RGWRESTMgr_S3::get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix)
{
bool is_s3website = enable_s3website && (s->prot_flags & RGW_REST_WEBSITE);
int ret =
RGWHandler_REST_S3::init_from_header(driver, s,
is_s3website ? RGWFormat::HTML :
RGWFormat::XML, true);
if (ret < 0) {
return nullptr;
}
if (is_s3website) {
if (s->init_state.url_bucket.empty()) {
return new RGWHandler_REST_Service_S3Website(auth_registry);
}
if (rgw::sal::Object::empty(s->object.get())) {
return new RGWHandler_REST_Bucket_S3Website(auth_registry);
}
return new RGWHandler_REST_Obj_S3Website(auth_registry);
}
if (s->init_state.url_bucket.empty()) {
// no bucket
if (s->op == OP_POST) {
// POST will be one of: IAM, STS or topic service
const auto max_size = s->cct->_conf->rgw_max_put_param_size;
int ret;
bufferlist data;
std::tie(ret, data) = rgw_rest_read_all_input(s, max_size, false);
if (ret < 0) {
return nullptr;
}
parse_post_action(data.to_str(), s);
if (enable_sts && RGWHandler_REST_STS::action_exists(s)) {
return new RGWHandler_REST_STS(auth_registry);
}
if (enable_iam && RGWHandler_REST_IAM::action_exists(s)) {
return new RGWHandler_REST_IAM(auth_registry, data);
}
if (enable_pubsub && RGWHandler_REST_PSTopic_AWS::action_exists(s)) {
return new RGWHandler_REST_PSTopic_AWS(auth_registry);
}
return nullptr;
}
// non-POST S3 service without a bucket
return new RGWHandler_REST_Service_S3(auth_registry);
}
if (!rgw::sal::Object::empty(s->object.get())) {
// has object
return new RGWHandler_REST_Obj_S3(auth_registry);
}
if (s->info.args.exist_obj_excl_sub_resource()) {
return nullptr;
}
// has bucket
return new RGWHandler_REST_Bucket_S3(auth_registry, enable_pubsub);
}
bool RGWHandler_REST_S3Website::web_dir() const {
std::string subdir_name;
if (!rgw::sal::Object::empty(s->object.get())) {
subdir_name = url_decode(s->object->get_name());
}
if (subdir_name.empty()) {
return false;
} else if (subdir_name.back() == '/' && subdir_name.size() > 1) {
subdir_name.pop_back();
}
std::unique_ptr<rgw::sal::Object> obj = s->bucket->get_object(rgw_obj_key(subdir_name));
obj->set_atomic();
obj->set_prefetch_data();
RGWObjState* state = nullptr;
if (obj->get_obj_state(s, &state, s->yield) < 0) {
return false;
}
if (! state->exists) {
return false;
}
return state->exists;
}
int RGWHandler_REST_S3Website::init(rgw::sal::Driver* driver, req_state *s,
rgw::io::BasicClient* cio)
{
// save the original object name before retarget() replaces it with the
// result of get_effective_key(). the error_handler() needs the original
// object name for redirect handling
if (!rgw::sal::Object::empty(s->object.get())) {
original_object_name = s->object->get_name();
} else {
original_object_name = "";
}
return RGWHandler_REST_S3::init(driver, s, cio);
}
int RGWHandler_REST_S3Website::retarget(RGWOp* op, RGWOp** new_op, optional_yield y) {
*new_op = op;
ldpp_dout(s, 10) << __func__ << " Starting retarget" << dendl;
if (!(s->prot_flags & RGW_REST_WEBSITE))
return 0;
if (rgw::sal::Bucket::empty(s->bucket.get())) {
// TODO-FUTURE: if the bucket does not exist, maybe expose it here?
return -ERR_NO_SUCH_BUCKET;
}
if (!s->bucket->get_info().has_website) {
// TODO-FUTURE: if the bucket has no WebsiteConfig, expose it here
return -ERR_NO_SUCH_WEBSITE_CONFIGURATION;
}
rgw_obj_key new_obj;
string key_name;
if (!rgw::sal::Object::empty(s->object.get())) {
key_name = s->object->get_name();
}
bool get_res = s->bucket->get_info().website_conf.get_effective_key(key_name, &new_obj.name, web_dir());
if (!get_res) {
s->err.message = "The IndexDocument Suffix is not configurated or not well formed!";
ldpp_dout(s, 5) << s->err.message << dendl;
return -EINVAL;
}
ldpp_dout(s, 10) << "retarget get_effective_key " << s->object << " -> "
<< new_obj << dendl;
RGWBWRoutingRule rrule;
bool should_redirect =
s->bucket->get_info().website_conf.should_redirect(new_obj.name, 0, &rrule);
if (should_redirect) {
const string& hostname = s->info.env->get("HTTP_HOST", "");
const string& protocol =
(s->info.env->get("SERVER_PORT_SECURE") ? "https" : "http");
int redirect_code = 0;
rrule.apply_rule(protocol, hostname, key_name, &s->redirect,
&redirect_code);
// APply a custom HTTP response code
if (redirect_code > 0)
s->err.http_ret = redirect_code; // Apply a custom HTTP response code
ldpp_dout(s, 10) << "retarget redirect code=" << redirect_code
<< " proto+host:" << protocol << "://" << hostname
<< " -> " << s->redirect << dendl;
return -ERR_WEBSITE_REDIRECT;
}
/*
* FIXME: if s->object != new_obj, drop op and create a new op to handle
* operation. Or remove this comment if it's not applicable anymore
* dang: This could be problematic, since we're not actually replacing op, but
* we are replacing s->object. Something might have a pointer to it.
*/
s->object = s->bucket->get_object(new_obj);
return 0;
}
RGWOp* RGWHandler_REST_S3Website::op_get()
{
return get_obj_op(true);
}
RGWOp* RGWHandler_REST_S3Website::op_head()
{
return get_obj_op(false);
}
int RGWHandler_REST_S3Website::serve_errordoc(const DoutPrefixProvider *dpp, int http_ret, const string& errordoc_key, optional_yield y) {
int ret = 0;
s->formatter->reset(); /* Try to throw it all away */
std::shared_ptr<RGWGetObj_ObjStore_S3Website> getop( static_cast<RGWGetObj_ObjStore_S3Website*>(op_get()));
if (getop.get() == NULL) {
return -1; // Trigger double error handler
}
getop->init(driver, s, this);
getop->range_str = NULL;
getop->if_mod = NULL;
getop->if_unmod = NULL;
getop->if_match = NULL;
getop->if_nomatch = NULL;
/* This is okay. It's an error, so nothing will run after this, and it can be
* called by abort_early(), which can be called before s->object or s->bucket
* are set up. Note, it won't have bucket. */
s->object = driver->get_object(errordoc_key);
ret = init_permissions(getop.get(), y);
if (ret < 0) {
ldpp_dout(s, 20) << "serve_errordoc failed, init_permissions ret=" << ret << dendl;
return -1; // Trigger double error handler
}
ret = read_permissions(getop.get(), y);
if (ret < 0) {
ldpp_dout(s, 20) << "serve_errordoc failed, read_permissions ret=" << ret << dendl;
return -1; // Trigger double error handler
}
if (http_ret) {
getop->set_custom_http_response(http_ret);
}
ret = getop->init_processing(y);
if (ret < 0) {
ldpp_dout(s, 20) << "serve_errordoc failed, init_processing ret=" << ret << dendl;
return -1; // Trigger double error handler
}
ret = getop->verify_op_mask();
if (ret < 0) {
ldpp_dout(s, 20) << "serve_errordoc failed, verify_op_mask ret=" << ret << dendl;
return -1; // Trigger double error handler
}
ret = getop->verify_permission(y);
if (ret < 0) {
ldpp_dout(s, 20) << "serve_errordoc failed, verify_permission ret=" << ret << dendl;
return -1; // Trigger double error handler
}
ret = getop->verify_params();
if (ret < 0) {
ldpp_dout(s, 20) << "serve_errordoc failed, verify_params ret=" << ret << dendl;
return -1; // Trigger double error handler
}
// No going back now
getop->pre_exec();
/*
* FIXME Missing headers:
* With a working errordoc, the s3 error fields are rendered as HTTP headers,
* x-amz-error-code: NoSuchKey
* x-amz-error-message: The specified key does not exist.
* x-amz-error-detail-Key: foo
*/
getop->execute(y);
getop->complete();
return 0;
}
int RGWHandler_REST_S3Website::error_handler(int err_no,
string* error_content,
optional_yield y) {
int new_err_no = -1;
rgw_http_errors::const_iterator r = rgw_http_s3_errors.find(err_no > 0 ? err_no : -err_no);
int http_error_code = -1;
if (r != rgw_http_s3_errors.end()) {
http_error_code = r->second.first;
}
ldpp_dout(s, 10) << "RGWHandler_REST_S3Website::error_handler err_no=" << err_no << " http_ret=" << http_error_code << dendl;
RGWBWRoutingRule rrule;
bool have_bucket = !rgw::sal::Bucket::empty(s->bucket.get());
bool should_redirect = false;
if (have_bucket) {
should_redirect =
s->bucket->get_info().website_conf.should_redirect(original_object_name,
http_error_code, &rrule);
}
if (should_redirect) {
const string& hostname = s->info.env->get("HTTP_HOST", "");
const string& protocol =
(s->info.env->get("SERVER_PORT_SECURE") ? "https" : "http");
int redirect_code = 0;
rrule.apply_rule(protocol, hostname, original_object_name,
&s->redirect, &redirect_code);
// Apply a custom HTTP response code
if (redirect_code > 0)
s->err.http_ret = redirect_code; // Apply a custom HTTP response code
ldpp_dout(s, 10) << "error handler redirect code=" << redirect_code
<< " proto+host:" << protocol << "://" << hostname
<< " -> " << s->redirect << dendl;
return -ERR_WEBSITE_REDIRECT;
} else if (err_no == -ERR_WEBSITE_REDIRECT) {
// Do nothing here, this redirect will be handled in abort_early's ERR_WEBSITE_REDIRECT block
// Do NOT fire the ErrorDoc handler
} else if (have_bucket && !s->bucket->get_info().website_conf.error_doc.empty()) {
/* This serves an entire page!
On success, it will return zero, and no further content should be sent to the socket
On failure, we need the double-error handler
*/
new_err_no = RGWHandler_REST_S3Website::serve_errordoc(s, http_error_code, s->bucket->get_info().website_conf.error_doc, y);
if (new_err_no != -1) {
err_no = new_err_no;
}
} else {
ldpp_dout(s, 20) << "No special error handling today!" << dendl;
}
return err_no;
}
RGWOp* RGWHandler_REST_Obj_S3Website::get_obj_op(bool get_data)
{
/** If we are in website mode, then it is explicitly impossible to run GET or
* HEAD on the actual directory. We must convert the request to run on the
* suffix object instead!
*/
RGWGetObj_ObjStore_S3Website* op = new RGWGetObj_ObjStore_S3Website;
op->set_get_data(get_data);
return op;
}
RGWOp* RGWHandler_REST_Bucket_S3Website::get_obj_op(bool get_data)
{
/** If we are in website mode, then it is explicitly impossible to run GET or
* HEAD on the actual directory. We must convert the request to run on the
* suffix object instead!
*/
RGWGetObj_ObjStore_S3Website* op = new RGWGetObj_ObjStore_S3Website;
op->set_get_data(get_data);
return op;
}
RGWOp* RGWHandler_REST_Service_S3Website::get_obj_op(bool get_data)
{
/** If we are in website mode, then it is explicitly impossible to run GET or
* HEAD on the actual directory. We must convert the request to run on the
* suffix object instead!
*/
RGWGetObj_ObjStore_S3Website* op = new RGWGetObj_ObjStore_S3Website;
op->set_get_data(get_data);
return op;
}
namespace rgw::auth::s3 {
static rgw::auth::Completer::cmplptr_t
null_completer_factory(const boost::optional<std::string>& secret_key)
{
return nullptr;
}
AWSEngine::VersionAbstractor::auth_data_t
AWSGeneralAbstractor::get_auth_data(const req_state* const s) const
{
AwsVersion version;
AwsRoute route;
std::tie(version, route) = discover_aws_flavour(s->info);
if (version == AwsVersion::V2) {
return get_auth_data_v2(s);
} else if (version == AwsVersion::V4) {
return get_auth_data_v4(s, route == AwsRoute::QUERY_STRING);
} else {
/* FIXME(rzarzynski): handle anon user. */
throw -EINVAL;
}
}
boost::optional<std::string>
AWSGeneralAbstractor::get_v4_canonical_headers(
const req_info& info,
const std::string_view& signedheaders,
const bool using_qs) const
{
return rgw::auth::s3::get_v4_canonical_headers(info, signedheaders,
using_qs, false);
}
AWSSignerV4::prepare_result_t
AWSSignerV4::prepare(const DoutPrefixProvider *dpp,
const std::string& access_key_id,
const string& region,
const string& service,
const req_info& info,
const bufferlist *opt_content,
bool s3_op)
{
std::string signed_hdrs;
ceph::real_time timestamp = ceph::real_clock::now();
map<string, string> extra_headers;
std::string date = ceph::to_iso_8601_no_separators(timestamp, ceph::iso_8601_format::YMDhms);
std::string credential_scope = gen_v4_scope(timestamp, region, service);
extra_headers["x-amz-date"] = date;
string content_hash;
if (opt_content) {
content_hash = rgw::auth::s3::calc_v4_payload_hash(opt_content->to_str());
extra_headers["x-amz-content-sha256"] = content_hash;
}
/* craft canonical headers */
std::string canonical_headers = \
gen_v4_canonical_headers(info, extra_headers, &signed_hdrs);
using sanitize = rgw::crypt_sanitize::log_content;
ldpp_dout(dpp, 10) << "canonical headers format = "
<< sanitize{canonical_headers} << dendl;
bool is_non_s3_op = !s3_op;
const char* exp_payload_hash = nullptr;
string payload_hash;
if (is_non_s3_op) {
//For non s3 ops, we need to calculate the payload hash
payload_hash = info.args.get("PayloadHash");
exp_payload_hash = payload_hash.c_str();
} else {
/* Get the expected hash. */
if (content_hash.empty()) {
exp_payload_hash = rgw::auth::s3::get_v4_exp_payload_hash(info);
} else {
exp_payload_hash = content_hash.c_str();
}
}
/* Craft canonical URI. Using std::move later so let it be non-const. */
auto canonical_uri = rgw::auth::s3::gen_v4_canonical_uri(info);
/* Craft canonical query string. std::moving later so non-const here. */
auto canonical_qs = rgw::auth::s3::gen_v4_canonical_qs(info, is_non_s3_op);
auto cct = dpp->get_cct();
/* Craft canonical request. */
auto canonical_req_hash = \
rgw::auth::s3::get_v4_canon_req_hash(cct,
info.method,
std::move(canonical_uri),
std::move(canonical_qs),
std::move(canonical_headers),
signed_hdrs,
exp_payload_hash,
dpp);
auto string_to_sign = \
rgw::auth::s3::get_v4_string_to_sign(cct,
AWS4_HMAC_SHA256_STR,
date,
credential_scope,
std::move(canonical_req_hash),
dpp);
const auto sig_factory = gen_v4_signature;
/* Requests authenticated with the Query Parameters are treated as unsigned.
* From "Authenticating Requests: Using Query Parameters (AWS Signature
* Version 4)":
*
* You don't include a payload hash in the Canonical Request, because
* when you create a presigned URL, you don't know the payload content
* because the URL is used to upload an arbitrary payload. Instead, you
* use a constant string UNSIGNED-PAYLOAD.
*
* This means we have absolutely no business in spawning completer. Both
* aws4_auth_needs_complete and aws4_auth_streaming_mode are set to false
* by default. We don't need to change that. */
return {
access_key_id,
date,
credential_scope,
std::move(signed_hdrs),
std::move(string_to_sign),
std::move(extra_headers),
sig_factory,
};
}
AWSSignerV4::signature_headers_t
gen_v4_signature(const DoutPrefixProvider *dpp,
const std::string_view& secret_key,
const AWSSignerV4::prepare_result_t& sig_info)
{
auto signature = rgw::auth::s3::get_v4_signature(sig_info.scope,
dpp->get_cct(),
secret_key,
sig_info.string_to_sign,
dpp);
AWSSignerV4::signature_headers_t result;
for (auto& entry : sig_info.extra_headers) {
result[entry.first] = entry.second;
}
auto& payload_hash = result["x-amz-content-sha256"];
if (payload_hash.empty()) {
payload_hash = AWS4_UNSIGNED_PAYLOAD_HASH;
}
string auth_header = string("AWS4-HMAC-SHA256 Credential=").append(sig_info.access_key_id) + "/";
auth_header.append(sig_info.scope + ",SignedHeaders=")
.append(sig_info.signed_headers + ",Signature=")
.append(signature);
result["Authorization"] = auth_header;
return result;
}
AWSEngine::VersionAbstractor::auth_data_t
AWSGeneralAbstractor::get_auth_data_v4(const req_state* const s,
const bool using_qs) const
{
std::string_view access_key_id;
std::string_view signed_hdrs;
std::string_view date;
std::string_view credential_scope;
std::string_view client_signature;
std::string_view session_token;
int ret = rgw::auth::s3::parse_v4_credentials(s->info,
access_key_id,
credential_scope,
signed_hdrs,
client_signature,
date,
session_token,
using_qs,
s);
if (ret < 0) {
throw ret;
}
/* craft canonical headers */
boost::optional<std::string> canonical_headers = \
get_v4_canonical_headers(s->info, signed_hdrs, using_qs);
if (canonical_headers) {
using sanitize = rgw::crypt_sanitize::log_content;
ldpp_dout(s, 10) << "canonical headers format = "
<< sanitize{*canonical_headers} << dendl;
} else {
throw -EPERM;
}
bool is_non_s3_op = rgw::auth::s3::is_non_s3_op(s->op_type);
const char* exp_payload_hash = nullptr;
string payload_hash;
if (is_non_s3_op) {
//For non s3 ops, we need to calculate the payload hash
payload_hash = s->info.args.get("PayloadHash");
exp_payload_hash = payload_hash.c_str();
} else {
/* Get the expected hash. */
exp_payload_hash = rgw::auth::s3::get_v4_exp_payload_hash(s->info);
}
/* Craft canonical URI. Using std::move later so let it be non-const. */
auto canonical_uri = rgw::auth::s3::get_v4_canonical_uri(s->info);
/* Craft canonical query string. std::moving later so non-const here. */
auto canonical_qs = rgw::auth::s3::get_v4_canonical_qs(s->info, using_qs);
/* Craft canonical request. */
auto canonical_req_hash = \
rgw::auth::s3::get_v4_canon_req_hash(s->cct,
s->info.method,
std::move(canonical_uri),
std::move(canonical_qs),
std::move(*canonical_headers),
signed_hdrs,
exp_payload_hash,
s);
auto string_to_sign = \
rgw::auth::s3::get_v4_string_to_sign(s->cct,
AWS4_HMAC_SHA256_STR,
date,
credential_scope,
std::move(canonical_req_hash),
s);
const auto sig_factory = std::bind(rgw::auth::s3::get_v4_signature,
credential_scope,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
s);
/* Requests authenticated with the Query Parameters are treated as unsigned.
* From "Authenticating Requests: Using Query Parameters (AWS Signature
* Version 4)":
*
* You don't include a payload hash in the Canonical Request, because
* when you create a presigned URL, you don't know the payload content
* because the URL is used to upload an arbitrary payload. Instead, you
* use a constant string UNSIGNED-PAYLOAD.
*
* This means we have absolutely no business in spawning completer. Both
* aws4_auth_needs_complete and aws4_auth_streaming_mode are set to false
* by default. We don't need to change that. */
if (is_v4_payload_unsigned(exp_payload_hash) || is_v4_payload_empty(s) || is_non_s3_op) {
return {
access_key_id,
client_signature,
session_token,
std::move(string_to_sign),
sig_factory,
null_completer_factory
};
} else {
/* We're going to handle a signed payload. Be aware that even empty HTTP
* body (no payload) requires verification:
*
* The x-amz-content-sha256 header is required for all AWS Signature
* Version 4 requests. It provides a hash of the request payload. If
* there is no payload, you must provide the hash of an empty string. */
if (!is_v4_payload_streamed(exp_payload_hash)) {
ldpp_dout(s, 10) << "delaying v4 auth" << dendl;
/* payload in a single chunk */
switch (s->op_type)
{
case RGW_OP_CREATE_BUCKET:
case RGW_OP_PUT_OBJ:
case RGW_OP_PUT_ACLS:
case RGW_OP_PUT_CORS:
case RGW_OP_PUT_BUCKET_ENCRYPTION:
case RGW_OP_GET_BUCKET_ENCRYPTION:
case RGW_OP_DELETE_BUCKET_ENCRYPTION:
case RGW_OP_INIT_MULTIPART: // in case that Init Multipart uses CHUNK encoding
case RGW_OP_COMPLETE_MULTIPART:
case RGW_OP_SET_BUCKET_VERSIONING:
case RGW_OP_DELETE_MULTI_OBJ:
case RGW_OP_ADMIN_SET_METADATA:
case RGW_OP_SYNC_DATALOG_NOTIFY:
case RGW_OP_SYNC_DATALOG_NOTIFY2:
case RGW_OP_SYNC_MDLOG_NOTIFY:
case RGW_OP_PERIOD_POST:
case RGW_OP_SET_BUCKET_WEBSITE:
case RGW_OP_PUT_BUCKET_POLICY:
case RGW_OP_PUT_OBJ_TAGGING:
case RGW_OP_PUT_BUCKET_TAGGING:
case RGW_OP_PUT_BUCKET_REPLICATION:
case RGW_OP_PUT_LC:
case RGW_OP_SET_REQUEST_PAYMENT:
case RGW_OP_PUBSUB_NOTIF_CREATE:
case RGW_OP_PUBSUB_NOTIF_DELETE:
case RGW_OP_PUBSUB_NOTIF_LIST:
case RGW_OP_PUT_BUCKET_OBJ_LOCK:
case RGW_OP_PUT_OBJ_RETENTION:
case RGW_OP_PUT_OBJ_LEGAL_HOLD:
case RGW_STS_GET_SESSION_TOKEN:
case RGW_STS_ASSUME_ROLE:
case RGW_OP_PUT_BUCKET_PUBLIC_ACCESS_BLOCK:
case RGW_OP_GET_BUCKET_PUBLIC_ACCESS_BLOCK:
case RGW_OP_DELETE_BUCKET_PUBLIC_ACCESS_BLOCK:
case RGW_OP_GET_OBJ://s3select its post-method(payload contain the query) , the request is get-object
break;
default:
ldpp_dout(s, 10) << "ERROR: AWS4 completion for operation: " << s->op_type << ", NOT IMPLEMENTED" << dendl;
throw -ERR_NOT_IMPLEMENTED;
}
const auto cmpl_factory = std::bind(AWSv4ComplSingle::create,
s,
std::placeholders::_1);
return {
access_key_id,
client_signature,
session_token,
std::move(string_to_sign),
sig_factory,
cmpl_factory
};
} else {
/* IMHO "streamed" doesn't fit too good here. I would prefer to call
* it "chunked" but let's be coherent with Amazon's terminology. */
ldpp_dout(s, 10) << "body content detected in multiple chunks" << dendl;
/* payload in multiple chunks */
switch(s->op_type)
{
case RGW_OP_PUT_OBJ:
break;
default:
ldpp_dout(s, 10) << "ERROR: AWS4 completion for this operation NOT IMPLEMENTED (streaming mode)" << dendl;
throw -ERR_NOT_IMPLEMENTED;
}
ldpp_dout(s, 10) << "aws4 seed signature ok... delaying v4 auth" << dendl;
/* In the case of streamed payload client sets the x-amz-content-sha256
* to "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" but uses "UNSIGNED-PAYLOAD"
* when constructing the Canonical Request. */
/* In the case of single-chunk upload client set the header's value is
* coherent with the one used for Canonical Request crafting. */
/* In the case of query string-based authentication there should be no
* x-amz-content-sha256 header and the value "UNSIGNED-PAYLOAD" is used
* for CanonReq. */
const auto cmpl_factory = std::bind(AWSv4ComplMulti::create,
s,
date,
credential_scope,
client_signature,
std::placeholders::_1);
return {
access_key_id,
client_signature,
session_token,
std::move(string_to_sign),
sig_factory,
cmpl_factory
};
}
}
}
boost::optional<std::string>
AWSGeneralBoto2Abstractor::get_v4_canonical_headers(
const req_info& info,
const std::string_view& signedheaders,
const bool using_qs) const
{
return rgw::auth::s3::get_v4_canonical_headers(info, signedheaders,
using_qs, true);
}
AWSEngine::VersionAbstractor::auth_data_t
AWSGeneralAbstractor::get_auth_data_v2(const req_state* const s) const
{
std::string_view access_key_id;
std::string_view signature;
std::string_view session_token;
bool qsr = false;
const char* http_auth = s->info.env->get("HTTP_AUTHORIZATION");
if (! http_auth || http_auth[0] == '\0') {
/* Credentials are provided in query string. We also need to verify
* the "Expires" parameter now. */
access_key_id = s->info.args.get("AWSAccessKeyId");
signature = s->info.args.get("Signature");
qsr = true;
std::string_view expires = s->info.args.get("Expires");
if (expires.empty()) {
throw -EPERM;
}
/* It looks we have the guarantee that expires is a null-terminated,
* and thus string_view::data() can be safely used. */
const time_t exp = atoll(expires.data());
time_t now;
time(&now);
if (now >= exp) {
throw -EPERM;
}
if (s->info.args.exists("x-amz-security-token")) {
session_token = s->info.args.get("x-amz-security-token");
if (session_token.size() == 0) {
throw -EPERM;
}
}
} else {
/* The "Authorization" HTTP header is being used. */
const std::string_view auth_str(http_auth + strlen("AWS "));
const size_t pos = auth_str.rfind(':');
if (pos != std::string_view::npos) {
access_key_id = auth_str.substr(0, pos);
signature = auth_str.substr(pos + 1);
}
auto token = s->info.env->get_optional("HTTP_X_AMZ_SECURITY_TOKEN");
if (token) {
session_token = *token;
if (session_token.size() == 0) {
throw -EPERM;
}
}
}
/* Let's canonize the HTTP headers that are covered by the AWS auth v2. */
std::string string_to_sign;
utime_t header_time;
if (! rgw_create_s3_canonical_header(s, s->info, &header_time, string_to_sign,
qsr)) {
ldpp_dout(s, 10) << "failed to create the canonized auth header\n"
<< rgw::crypt_sanitize::auth{s,string_to_sign} << dendl;
throw -EPERM;
}
ldpp_dout(s, 10) << "string_to_sign:\n"
<< rgw::crypt_sanitize::auth{s,string_to_sign} << dendl;
if (!qsr && !is_time_skew_ok(header_time)) {
throw -ERR_REQUEST_TIME_SKEWED;
}
return {
std::move(access_key_id),
std::move(signature),
std::move(session_token),
std::move(string_to_sign),
rgw::auth::s3::get_v2_signature,
null_completer_factory
};
}
AWSEngine::VersionAbstractor::auth_data_t
AWSBrowserUploadAbstractor::get_auth_data_v2(const req_state* const s) const
{
return {
s->auth.s3_postobj_creds.access_key,
s->auth.s3_postobj_creds.signature,
s->auth.s3_postobj_creds.x_amz_security_token,
s->auth.s3_postobj_creds.encoded_policy.to_str(),
rgw::auth::s3::get_v2_signature,
null_completer_factory
};
}
AWSEngine::VersionAbstractor::auth_data_t
AWSBrowserUploadAbstractor::get_auth_data_v4(const req_state* const s) const
{
const std::string_view credential = s->auth.s3_postobj_creds.x_amz_credential;
/* grab access key id */
const size_t pos = credential.find("/");
const std::string_view access_key_id = credential.substr(0, pos);
ldpp_dout(s, 10) << "access key id = " << access_key_id << dendl;
/* grab credential scope */
const std::string_view credential_scope = credential.substr(pos + 1);
ldpp_dout(s, 10) << "credential scope = " << credential_scope << dendl;
const auto sig_factory = std::bind(rgw::auth::s3::get_v4_signature,
credential_scope,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
s);
return {
access_key_id,
s->auth.s3_postobj_creds.signature,
s->auth.s3_postobj_creds.x_amz_security_token,
s->auth.s3_postobj_creds.encoded_policy.to_str(),
sig_factory,
null_completer_factory
};
}
AWSEngine::VersionAbstractor::auth_data_t
AWSBrowserUploadAbstractor::get_auth_data(const req_state* const s) const
{
if (s->auth.s3_postobj_creds.x_amz_algorithm == AWS4_HMAC_SHA256_STR) {
ldpp_dout(s, 0) << "Signature verification algorithm AWS v4"
<< " (AWS4-HMAC-SHA256)" << dendl;
return get_auth_data_v4(s);
} else {
ldpp_dout(s, 0) << "Signature verification algorithm AWS v2" << dendl;
return get_auth_data_v2(s);
}
}
AWSEngine::result_t
AWSEngine::authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const
{
/* Small reminder: an ver_abstractor is allowed to throw! */
const auto auth_data = ver_abstractor.get_auth_data(s);
if (auth_data.access_key_id.empty() || auth_data.client_signature.empty()) {
return result_t::deny(-EINVAL);
} else {
return authenticate(dpp,
auth_data.access_key_id,
auth_data.client_signature,
auth_data.session_token,
auth_data.string_to_sign,
auth_data.signature_factory,
auth_data.completer_factory,
s, y);
}
}
} // namespace rgw::auth::s3
rgw::LDAPHelper* rgw::auth::s3::LDAPEngine::ldh = nullptr;
std::mutex rgw::auth::s3::LDAPEngine::mtx;
void rgw::auth::s3::LDAPEngine::init(CephContext* const cct)
{
if (! cct->_conf->rgw_s3_auth_use_ldap ||
cct->_conf->rgw_ldap_uri.empty()) {
return;
}
if (! ldh) {
std::lock_guard<std::mutex> lck(mtx);
if (! ldh) {
const string& ldap_uri = cct->_conf->rgw_ldap_uri;
const string& ldap_binddn = cct->_conf->rgw_ldap_binddn;
const string& ldap_searchdn = cct->_conf->rgw_ldap_searchdn;
const string& ldap_searchfilter = cct->_conf->rgw_ldap_searchfilter;
const string& ldap_dnattr = cct->_conf->rgw_ldap_dnattr;
std::string ldap_bindpw = parse_rgw_ldap_bindpw(cct);
ldh = new rgw::LDAPHelper(ldap_uri, ldap_binddn, ldap_bindpw,
ldap_searchdn, ldap_searchfilter, ldap_dnattr);
ldh->init();
ldh->bind();
}
}
}
bool rgw::auth::s3::LDAPEngine::valid() {
std::lock_guard<std::mutex> lck(mtx);
return (!!ldh);
}
rgw::auth::RemoteApplier::acl_strategy_t
rgw::auth::s3::LDAPEngine::get_acl_strategy() const
{
//This is based on the assumption that the default acl strategy in
// get_perms_from_aclspec, will take care. Extra acl spec is not required.
return nullptr;
}
rgw::auth::RemoteApplier::AuthInfo
rgw::auth::s3::LDAPEngine::get_creds_info(const rgw::RGWToken& token) const noexcept
{
/* The short form of "using" can't be used here -- we're aliasing a class'
* member. */
using acct_privilege_t = \
rgw::auth::RemoteApplier::AuthInfo::acct_privilege_t;
return rgw::auth::RemoteApplier::AuthInfo {
rgw_user(token.id),
token.id,
RGW_PERM_FULL_CONTROL,
acct_privilege_t::IS_PLAIN_ACCT,
rgw::auth::RemoteApplier::AuthInfo::NO_ACCESS_KEY,
rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER,
TYPE_LDAP
};
}
rgw::auth::Engine::result_t
rgw::auth::s3::LDAPEngine::authenticate(
const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t&,
const completer_factory_t& completer_factory,
const req_state* const s,
optional_yield y) const
{
/* boost filters and/or string_ref may throw on invalid input */
rgw::RGWToken base64_token;
try {
base64_token = rgw::from_base64(access_key_id);
} catch (...) {
base64_token = std::string("");
}
if (! base64_token.valid()) {
return result_t::deny();
}
//TODO: Uncomment, when we have a migration plan in place.
//Check if a user of type other than 'ldap' is already present, if yes, then
//return error.
/*RGWUserInfo user_info;
user_info.user_id = base64_token.id;
if (rgw_get_user_info_by_uid(driver, user_info.user_id, user_info) >= 0) {
if (user_info.type != TYPE_LDAP) {
ldpp_dout(dpp, 10) << "ERROR: User id of type: " << user_info.type << " is already present" << dendl;
return nullptr;
}
}*/
if (ldh->auth(base64_token.id, base64_token.key) != 0) {
return result_t::deny(-ERR_INVALID_ACCESS_KEY);
}
auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(),
get_creds_info(base64_token));
return result_t::grant(std::move(apl), completer_factory(boost::none));
} /* rgw::auth::s3::LDAPEngine::authenticate */
void rgw::auth::s3::LDAPEngine::shutdown() {
if (ldh) {
delete ldh;
ldh = nullptr;
}
}
/* LocalEngine */
rgw::auth::Engine::result_t
rgw::auth::s3::LocalEngine::authenticate(
const DoutPrefixProvider* dpp,
const std::string_view& _access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
const req_state* const s,
optional_yield y) const
{
/* get the user info */
std::unique_ptr<rgw::sal::User> user;
const std::string access_key_id(_access_key_id);
/* TODO(rzarzynski): we need to have string-view taking variant. */
if (driver->get_user_by_access_key(dpp, access_key_id, y, &user) < 0) {
ldpp_dout(dpp, 5) << "error reading user info, uid=" << access_key_id
<< " can't authenticate" << dendl;
return result_t::deny(-ERR_INVALID_ACCESS_KEY);
}
//TODO: Uncomment, when we have a migration plan in place.
/*else {
if (s->user->type != TYPE_RGW) {
ldpp_dout(dpp, 10) << "ERROR: User id of type: " << s->user->type
<< " is present" << dendl;
throw -EPERM;
}
}*/
const auto iter = user->get_info().access_keys.find(access_key_id);
if (iter == std::end(user->get_info().access_keys)) {
ldpp_dout(dpp, 0) << "ERROR: access key not encoded in user info" << dendl;
return result_t::deny(-EPERM);
}
const RGWAccessKey& k = iter->second;
const VersionAbstractor::server_signature_t server_signature = \
signature_factory(cct, k.key, string_to_sign);
auto compare = signature.compare(server_signature);
ldpp_dout(dpp, 15) << "string_to_sign="
<< rgw::crypt_sanitize::log_content{string_to_sign}
<< dendl;
ldpp_dout(dpp, 15) << "server signature=" << server_signature << dendl;
ldpp_dout(dpp, 15) << "client signature=" << signature << dendl;
ldpp_dout(dpp, 15) << "compare=" << compare << dendl;
if (compare != 0) {
return result_t::deny(-ERR_SIGNATURE_NO_MATCH);
}
auto apl = apl_factory->create_apl_local(cct, s, user->get_info(),
k.subuser, std::nullopt, access_key_id);
return result_t::grant(std::move(apl), completer_factory(k.key));
}
rgw::auth::RemoteApplier::AuthInfo
rgw::auth::s3::STSEngine::get_creds_info(const STS::SessionToken& token) const noexcept
{
using acct_privilege_t = \
rgw::auth::RemoteApplier::AuthInfo::acct_privilege_t;
return rgw::auth::RemoteApplier::AuthInfo {
token.user,
token.acct_name,
token.perm_mask,
(token.is_admin) ? acct_privilege_t::IS_ADMIN_ACCT: acct_privilege_t::IS_PLAIN_ACCT,
token.access_key_id,
rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER,
token.acct_type
};
}
int
rgw::auth::s3::STSEngine::get_session_token(const DoutPrefixProvider* dpp, const std::string_view& session_token,
STS::SessionToken& token) const
{
string decodedSessionToken;
try {
decodedSessionToken = rgw::from_base64(session_token);
} catch (...) {
ldpp_dout(dpp, 0) << "ERROR: Invalid session token, not base64 encoded." << dendl;
return -EINVAL;
}
auto* cryptohandler = cct->get_crypto_handler(CEPH_CRYPTO_AES);
if (! cryptohandler) {
return -EINVAL;
}
string secret_s = cct->_conf->rgw_sts_key;
buffer::ptr secret(secret_s.c_str(), secret_s.length());
int ret = 0;
if (ret = cryptohandler->validate_secret(secret); ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: Invalid secret key" << dendl;
return -EINVAL;
}
string error;
std::unique_ptr<CryptoKeyHandler> keyhandler(cryptohandler->get_key_handler(secret, error));
if (! keyhandler) {
return -EINVAL;
}
error.clear();
string decrypted_str;
buffer::list en_input, dec_output;
en_input = buffer::list::static_from_string(decodedSessionToken);
ret = keyhandler->decrypt(en_input, dec_output, &error);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: Decryption failed: " << error << dendl;
return -EPERM;
} else {
try {
dec_output.append('\0');
auto iter = dec_output.cbegin();
decode(token, iter);
} catch (const buffer::error& e) {
ldpp_dout(dpp, 0) << "ERROR: decode SessionToken failed: " << error << dendl;
return -EINVAL;
}
}
return 0;
}
rgw::auth::Engine::result_t
rgw::auth::s3::STSEngine::authenticate(
const DoutPrefixProvider* dpp,
const std::string_view& _access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
const req_state* const s,
optional_yield y) const
{
if (! s->info.args.exists("x-amz-security-token") &&
! s->info.env->exists("HTTP_X_AMZ_SECURITY_TOKEN") &&
s->auth.s3_postobj_creds.x_amz_security_token.empty()) {
return result_t::deny();
}
STS::SessionToken token;
if (int ret = get_session_token(dpp, session_token, token); ret < 0) {
return result_t::reject(ret);
}
//Authentication
//Check if access key is not the same passed in by client
if (token.access_key_id != _access_key_id) {
ldpp_dout(dpp, 0) << "Invalid access key" << dendl;
return result_t::reject(-EPERM);
}
//Check if the token has expired
if (! token.expiration.empty()) {
std::string expiration = token.expiration;
if (! expiration.empty()) {
boost::optional<real_clock::time_point> exp = ceph::from_iso_8601(expiration, false);
if (exp) {
real_clock::time_point now = real_clock::now();
if (now >= *exp) {
ldpp_dout(dpp, 0) << "ERROR: Token expired" << dendl;
return result_t::reject(-EPERM);
}
} else {
ldpp_dout(dpp, 0) << "ERROR: Invalid expiration: " << expiration << dendl;
return result_t::reject(-EPERM);
}
}
}
//Check for signature mismatch
const VersionAbstractor::server_signature_t server_signature = \
signature_factory(cct, token.secret_access_key, string_to_sign);
auto compare = signature.compare(server_signature);
ldpp_dout(dpp, 15) << "string_to_sign="
<< rgw::crypt_sanitize::log_content{string_to_sign}
<< dendl;
ldpp_dout(dpp, 15) << "server signature=" << server_signature << dendl;
ldpp_dout(dpp, 15) << "client signature=" << signature << dendl;
ldpp_dout(dpp, 15) << "compare=" << compare << dendl;
if (compare != 0) {
return result_t::reject(-ERR_SIGNATURE_NO_MATCH);
}
// Get all the authorization info
std::unique_ptr<rgw::sal::User> user;
rgw_user user_id;
string role_id;
rgw::auth::RoleApplier::Role r;
rgw::auth::RoleApplier::TokenAttrs t_attrs;
if (! token.roleId.empty()) {
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(token.roleId);
if (role->get_by_id(dpp, y) < 0) {
return result_t::deny(-EPERM);
}
r.id = token.roleId;
r.name = role->get_name();
r.tenant = role->get_tenant();
vector<string> role_policy_names = role->get_role_policy_names();
for (auto& policy_name : role_policy_names) {
string perm_policy;
if (int ret = role->get_role_policy(dpp, policy_name, perm_policy); ret == 0) {
r.role_policies.push_back(std::move(perm_policy));
}
}
}
user = driver->get_user(token.user);
if (! token.user.empty() && token.acct_type != TYPE_ROLE) {
// get user info
int ret = user->load_user(dpp, y);
if (ret < 0) {
ldpp_dout(dpp, 5) << "ERROR: failed reading user info: uid=" << token.user << dendl;
return result_t::reject(-EPERM);
}
}
if (token.acct_type == TYPE_KEYSTONE || token.acct_type == TYPE_LDAP) {
auto apl = remote_apl_factory->create_apl_remote(cct, s, get_acl_strategy(),
get_creds_info(token));
return result_t::grant(std::move(apl), completer_factory(token.secret_access_key));
} else if (token.acct_type == TYPE_ROLE) {
t_attrs.user_id = std::move(token.user); // This is mostly needed to assign the owner of a bucket during its creation
t_attrs.token_policy = std::move(token.policy);
t_attrs.role_session_name = std::move(token.role_session);
t_attrs.token_claims = std::move(token.token_claims);
t_attrs.token_issued_at = std::move(token.issued_at);
t_attrs.principal_tags = std::move(token.principal_tags);
auto apl = role_apl_factory->create_apl_role(cct, s, r, t_attrs);
return result_t::grant(std::move(apl), completer_factory(token.secret_access_key));
} else { // This is for all local users of type TYPE_RGW or TYPE_NONE
string subuser;
auto apl = local_apl_factory->create_apl_local(cct, s, user->get_info(), subuser, token.perm_mask, std::string(_access_key_id));
return result_t::grant(std::move(apl), completer_factory(token.secret_access_key));
}
}
bool rgw::auth::s3::S3AnonymousEngine::is_applicable(
const req_state* s
) const noexcept {
if (s->op == OP_OPTIONS) {
return true;
}
AwsVersion version;
AwsRoute route;
std::tie(version, route) = discover_aws_flavour(s->info);
return route == AwsRoute::QUERY_STRING && version == AwsVersion::UNKNOWN;
}
| 199,123 | 29.943901 | 175 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_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
#define TIME_BUF_SIZE 128
#include <mutex>
#include <string_view>
#include <boost/container/static_vector.hpp>
#include <boost/crc.hpp>
#include "common/sstring.hh"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_http_errors.h"
#include "rgw_acl_s3.h"
#include "rgw_policy_s3.h"
#include "rgw_lc_s3.h"
#include "rgw_keystone.h"
#include "rgw_rest_conn.h"
#include "rgw_ldap.h"
#include "rgw_token.h"
#include "include/ceph_assert.h"
#include "rgw_auth.h"
#include "rgw_auth_filters.h"
#include "rgw_sts.h"
struct rgw_http_error {
int http_ret;
const char *s3_code;
};
void rgw_get_errno_s3(struct rgw_http_error *e, int err_no);
class RGWGetObj_ObjStore_S3 : public RGWGetObj_ObjStore
{
protected:
// Serving a custom error page from an object is really a 200 response with
// just the status line altered.
int custom_http_ret = 0;
std::map<std::string, std::string> crypt_http_responses;
int override_range_hdr(const rgw::auth::StrategyRegistry& auth_registry, optional_yield y);
public:
RGWGetObj_ObjStore_S3() {}
~RGWGetObj_ObjStore_S3() override {}
int verify_requester(const rgw::auth::StrategyRegistry& auth_registry, optional_yield y) override;
int get_params(optional_yield y) override;
int send_response_data_error(optional_yield y) override;
int send_response_data(bufferlist& bl, off_t ofs, off_t len) override;
void set_custom_http_response(int http_ret) { custom_http_ret = http_ret; }
int get_decrypt_filter(std::unique_ptr<RGWGetObj_Filter>* filter,
RGWGetObj_Filter* cb,
bufferlist* manifest_bl) override;
};
class RGWGetObjTags_ObjStore_S3 : public RGWGetObjTags_ObjStore
{
public:
RGWGetObjTags_ObjStore_S3() {}
~RGWGetObjTags_ObjStore_S3() {}
void send_response_data(bufferlist &bl) override;
};
class RGWPutObjTags_ObjStore_S3 : public RGWPutObjTags_ObjStore
{
public:
RGWPutObjTags_ObjStore_S3() {}
~RGWPutObjTags_ObjStore_S3() {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWDeleteObjTags_ObjStore_S3 : public RGWDeleteObjTags
{
public:
~RGWDeleteObjTags_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetBucketTags_ObjStore_S3 : public RGWGetBucketTags_ObjStore
{
bufferlist tags_bl;
public:
void send_response_data(bufferlist &bl) override;
};
class RGWPutBucketTags_ObjStore_S3 : public RGWPutBucketTags_ObjStore
{
public:
int get_params(const DoutPrefixProvider *dpp, optional_yield y) override;
void send_response() override;
};
class RGWDeleteBucketTags_ObjStore_S3 : public RGWDeleteBucketTags
{
public:
void send_response() override;
};
class RGWGetBucketReplication_ObjStore_S3 : public RGWGetBucketReplication_ObjStore
{
public:
void send_response_data() override;
};
class RGWPutBucketReplication_ObjStore_S3 : public RGWPutBucketReplication_ObjStore
{
public:
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWDeleteBucketReplication_ObjStore_S3 : public RGWDeleteBucketReplication_ObjStore
{
protected:
void update_sync_policy(rgw_sync_policy_info *policy) override;
public:
void send_response() override;
};
class RGWListBuckets_ObjStore_S3 : public RGWListBuckets_ObjStore {
public:
RGWListBuckets_ObjStore_S3() {}
~RGWListBuckets_ObjStore_S3() override {}
int get_params(optional_yield y) override {
limit = -1; /* no limit */
return 0;
}
void send_response_begin(bool has_buckets) override;
void send_response_data(rgw::sal::BucketList& buckets) override;
void send_response_end() override;
};
class RGWGetUsage_ObjStore_S3 : public RGWGetUsage_ObjStore {
public:
RGWGetUsage_ObjStore_S3() {}
~RGWGetUsage_ObjStore_S3() override {}
int get_params(optional_yield y) override ;
void send_response() override;
};
class RGWListBucket_ObjStore_S3 : public RGWListBucket_ObjStore {
protected:
bool objs_container;
bool encode_key {false};
int get_common_params();
void send_common_response();
void send_common_versioned_response();
public:
RGWListBucket_ObjStore_S3() : objs_container(false) {
default_max = 1000;
}
~RGWListBucket_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
void send_versioned_response();
};
class RGWListBucket_ObjStore_S3v2 : public RGWListBucket_ObjStore_S3 {
bool fetchOwner;
bool start_after_exist;
bool continuation_token_exist;
std::string startAfter;
std::string continuation_token;
public:
RGWListBucket_ObjStore_S3v2() : fetchOwner(false) {
}
~RGWListBucket_ObjStore_S3v2() override {}
int get_params(optional_yield y) override;
void send_response() override;
void send_versioned_response();
};
class RGWGetBucketLogging_ObjStore_S3 : public RGWGetBucketLogging {
public:
RGWGetBucketLogging_ObjStore_S3() {}
~RGWGetBucketLogging_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetBucketLocation_ObjStore_S3 : public RGWGetBucketLocation {
public:
RGWGetBucketLocation_ObjStore_S3() {}
~RGWGetBucketLocation_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetBucketVersioning_ObjStore_S3 : public RGWGetBucketVersioning {
public:
RGWGetBucketVersioning_ObjStore_S3() {}
~RGWGetBucketVersioning_ObjStore_S3() override {}
void send_response() override;
};
class RGWSetBucketVersioning_ObjStore_S3 : public RGWSetBucketVersioning {
public:
RGWSetBucketVersioning_ObjStore_S3() {}
~RGWSetBucketVersioning_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWGetBucketWebsite_ObjStore_S3 : public RGWGetBucketWebsite {
public:
RGWGetBucketWebsite_ObjStore_S3() {}
~RGWGetBucketWebsite_ObjStore_S3() override {}
void send_response() override;
};
class RGWSetBucketWebsite_ObjStore_S3 : public RGWSetBucketWebsite {
public:
RGWSetBucketWebsite_ObjStore_S3() {}
~RGWSetBucketWebsite_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWDeleteBucketWebsite_ObjStore_S3 : public RGWDeleteBucketWebsite {
public:
RGWDeleteBucketWebsite_ObjStore_S3() {}
~RGWDeleteBucketWebsite_ObjStore_S3() override {}
void send_response() override;
};
class RGWStatBucket_ObjStore_S3 : public RGWStatBucket_ObjStore {
public:
RGWStatBucket_ObjStore_S3() {}
~RGWStatBucket_ObjStore_S3() override {}
void send_response() override;
};
class RGWCreateBucket_ObjStore_S3 : public RGWCreateBucket_ObjStore {
public:
RGWCreateBucket_ObjStore_S3() {}
~RGWCreateBucket_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWDeleteBucket_ObjStore_S3 : public RGWDeleteBucket_ObjStore {
public:
RGWDeleteBucket_ObjStore_S3() {}
~RGWDeleteBucket_ObjStore_S3() override {}
void send_response() override;
};
class RGWPutObj_ObjStore_S3 : public RGWPutObj_ObjStore {
private:
std::map<std::string, std::string> crypt_http_responses;
public:
RGWPutObj_ObjStore_S3() {}
~RGWPutObj_ObjStore_S3() override {}
int get_params(optional_yield y) override;
int get_data(bufferlist& bl) override;
void send_response() override;
int get_encrypt_filter(std::unique_ptr<rgw::sal::DataProcessor> *filter,
rgw::sal::DataProcessor *cb) override;
int get_decrypt_filter(std::unique_ptr<RGWGetObj_Filter>* filter,
RGWGetObj_Filter* cb,
std::map<std::string, bufferlist>& attrs,
bufferlist* manifest_bl) override;
};
class RGWPostObj_ObjStore_S3 : public RGWPostObj_ObjStore {
parts_collection_t parts;
std::string filename;
std::string content_type;
RGWPolicyEnv env;
RGWPolicy post_policy;
std::map<std::string, std::string> crypt_http_responses;
const rgw::auth::StrategyRegistry* auth_registry_ptr = nullptr;
int get_policy(optional_yield y);
int get_tags();
void rebuild_key(rgw::sal::Object* obj);
std::string get_current_filename() const override;
std::string get_current_content_type() const override;
public:
RGWPostObj_ObjStore_S3() {}
~RGWPostObj_ObjStore_S3() override {}
int verify_requester(const rgw::auth::StrategyRegistry& auth_registry, optional_yield y) override {
auth_registry_ptr = &auth_registry;
return RGWPostObj_ObjStore::verify_requester(auth_registry, y);
}
int get_params(optional_yield y) override;
int complete_get_params();
void send_response() override;
int get_data(ceph::bufferlist& bl, bool& again) override;
int get_encrypt_filter(std::unique_ptr<rgw::sal::DataProcessor> *filter,
rgw::sal::DataProcessor *cb) override;
};
class RGWDeleteObj_ObjStore_S3 : public RGWDeleteObj_ObjStore {
public:
RGWDeleteObj_ObjStore_S3() {}
~RGWDeleteObj_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWCopyObj_ObjStore_S3 : public RGWCopyObj_ObjStore {
bool sent_header;
public:
RGWCopyObj_ObjStore_S3() : sent_header(false) {}
~RGWCopyObj_ObjStore_S3() override {}
int init_dest_policy() override;
int get_params(optional_yield y) override;
int check_storage_class(const rgw_placement_rule& src_placement) override;
void send_partial_response(off_t ofs) override;
void send_response() override;
};
class RGWGetACLs_ObjStore_S3 : public RGWGetACLs_ObjStore {
public:
RGWGetACLs_ObjStore_S3() {}
~RGWGetACLs_ObjStore_S3() override {}
void send_response() override;
};
class RGWPutACLs_ObjStore_S3 : public RGWPutACLs_ObjStore {
public:
RGWPutACLs_ObjStore_S3() {}
~RGWPutACLs_ObjStore_S3() override {}
int get_policy_from_state(rgw::sal::Driver* driver, req_state *s, std::stringstream& ss) override;
void send_response() override;
int get_params(optional_yield y) override;
};
class RGWGetLC_ObjStore_S3 : public RGWGetLC_ObjStore {
protected:
RGWLifecycleConfiguration_S3 config;
public:
RGWGetLC_ObjStore_S3() {}
~RGWGetLC_ObjStore_S3() override {}
void execute(optional_yield y) override;
void send_response() override;
};
class RGWPutLC_ObjStore_S3 : public RGWPutLC_ObjStore {
public:
RGWPutLC_ObjStore_S3() {}
~RGWPutLC_ObjStore_S3() override {}
void send_response() override;
};
class RGWDeleteLC_ObjStore_S3 : public RGWDeleteLC_ObjStore {
public:
RGWDeleteLC_ObjStore_S3() {}
~RGWDeleteLC_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetCORS_ObjStore_S3 : public RGWGetCORS_ObjStore {
public:
RGWGetCORS_ObjStore_S3() {}
~RGWGetCORS_ObjStore_S3() override {}
void send_response() override;
};
class RGWPutCORS_ObjStore_S3 : public RGWPutCORS_ObjStore {
public:
RGWPutCORS_ObjStore_S3() {}
~RGWPutCORS_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWDeleteCORS_ObjStore_S3 : public RGWDeleteCORS_ObjStore {
public:
RGWDeleteCORS_ObjStore_S3() {}
~RGWDeleteCORS_ObjStore_S3() override {}
void send_response() override;
};
class RGWOptionsCORS_ObjStore_S3 : public RGWOptionsCORS_ObjStore {
public:
RGWOptionsCORS_ObjStore_S3() {}
~RGWOptionsCORS_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetBucketEncryption_ObjStore_S3 : public RGWGetBucketEncryption_ObjStore {
public:
RGWGetBucketEncryption_ObjStore_S3() {}
~RGWGetBucketEncryption_ObjStore_S3() override {}
void send_response() override;
};
class RGWPutBucketEncryption_ObjStore_S3 : public RGWPutBucketEncryption_ObjStore {
public:
RGWPutBucketEncryption_ObjStore_S3() {}
~RGWPutBucketEncryption_ObjStore_S3() override {}
void send_response() override;
};
class RGWDeleteBucketEncryption_ObjStore_S3 : public RGWDeleteBucketEncryption_ObjStore {
public:
RGWDeleteBucketEncryption_ObjStore_S3() {}
~RGWDeleteBucketEncryption_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetRequestPayment_ObjStore_S3 : public RGWGetRequestPayment {
public:
RGWGetRequestPayment_ObjStore_S3() {}
~RGWGetRequestPayment_ObjStore_S3() override {}
void send_response() override;
};
class RGWSetRequestPayment_ObjStore_S3 : public RGWSetRequestPayment {
public:
RGWSetRequestPayment_ObjStore_S3() {}
~RGWSetRequestPayment_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWInitMultipart_ObjStore_S3 : public RGWInitMultipart_ObjStore {
private:
std::map<std::string, std::string> crypt_http_responses;
public:
RGWInitMultipart_ObjStore_S3() {}
~RGWInitMultipart_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
int prepare_encryption(std::map<std::string, bufferlist>& attrs) override;
};
class RGWCompleteMultipart_ObjStore_S3 : public RGWCompleteMultipart_ObjStore {
public:
RGWCompleteMultipart_ObjStore_S3() {}
~RGWCompleteMultipart_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWAbortMultipart_ObjStore_S3 : public RGWAbortMultipart_ObjStore {
public:
RGWAbortMultipart_ObjStore_S3() {}
~RGWAbortMultipart_ObjStore_S3() override {}
void send_response() override;
};
class RGWListMultipart_ObjStore_S3 : public RGWListMultipart_ObjStore {
public:
RGWListMultipart_ObjStore_S3() {}
~RGWListMultipart_ObjStore_S3() override {}
void send_response() override;
};
class RGWListBucketMultiparts_ObjStore_S3 : public RGWListBucketMultiparts_ObjStore {
public:
RGWListBucketMultiparts_ObjStore_S3() {
default_max = 1000;
}
~RGWListBucketMultiparts_ObjStore_S3() override {}
void send_response() override;
};
class RGWDeleteMultiObj_ObjStore_S3 : public RGWDeleteMultiObj_ObjStore {
public:
RGWDeleteMultiObj_ObjStore_S3() {}
~RGWDeleteMultiObj_ObjStore_S3() override {}
int get_params(optional_yield y) override;
void send_status() override;
void begin_response() override;
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) override;
void end_response() override;
};
class RGWPutBucketObjectLock_ObjStore_S3 : public RGWPutBucketObjectLock_ObjStore {
public:
RGWPutBucketObjectLock_ObjStore_S3() {}
~RGWPutBucketObjectLock_ObjStore_S3() override {}
void send_response() override;
};
class RGWGetBucketObjectLock_ObjStore_S3 : public RGWGetBucketObjectLock_ObjStore {
public:
RGWGetBucketObjectLock_ObjStore_S3() {}
~RGWGetBucketObjectLock_ObjStore_S3() {}
void send_response() override;
};
class RGWPutObjRetention_ObjStore_S3 : public RGWPutObjRetention_ObjStore {
public:
RGWPutObjRetention_ObjStore_S3() {}
~RGWPutObjRetention_ObjStore_S3() {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWGetObjRetention_ObjStore_S3 : public RGWGetObjRetention_ObjStore {
public:
RGWGetObjRetention_ObjStore_S3() {}
~RGWGetObjRetention_ObjStore_S3() {}
void send_response() override;
};
class RGWPutObjLegalHold_ObjStore_S3 : public RGWPutObjLegalHold_ObjStore {
public:
RGWPutObjLegalHold_ObjStore_S3() {}
~RGWPutObjLegalHold_ObjStore_S3() {}
void send_response() override;
};
class RGWGetObjLegalHold_ObjStore_S3 : public RGWGetObjLegalHold_ObjStore {
public:
RGWGetObjLegalHold_ObjStore_S3() {}
~RGWGetObjLegalHold_ObjStore_S3() {}
void send_response() override;
};
class RGWGetObjLayout_ObjStore_S3 : public RGWGetObjLayout {
public:
RGWGetObjLayout_ObjStore_S3() {}
~RGWGetObjLayout_ObjStore_S3() {}
void send_response() override;
};
class RGWConfigBucketMetaSearch_ObjStore_S3 : public RGWConfigBucketMetaSearch {
public:
RGWConfigBucketMetaSearch_ObjStore_S3() {}
~RGWConfigBucketMetaSearch_ObjStore_S3() {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWGetBucketMetaSearch_ObjStore_S3 : public RGWGetBucketMetaSearch {
public:
RGWGetBucketMetaSearch_ObjStore_S3() {}
~RGWGetBucketMetaSearch_ObjStore_S3() {}
void send_response() override;
};
class RGWDelBucketMetaSearch_ObjStore_S3 : public RGWDelBucketMetaSearch {
public:
RGWDelBucketMetaSearch_ObjStore_S3() {}
~RGWDelBucketMetaSearch_ObjStore_S3() {}
void send_response() override;
};
class RGWGetBucketPolicyStatus_ObjStore_S3 : public RGWGetBucketPolicyStatus {
public:
void send_response() override;
};
class RGWPutBucketPublicAccessBlock_ObjStore_S3 : public RGWPutBucketPublicAccessBlock {
public:
void send_response() override;
};
class RGWGetBucketPublicAccessBlock_ObjStore_S3 : public RGWGetBucketPublicAccessBlock {
public:
void send_response() override;
};
class RGW_Auth_S3 {
public:
static int authorize(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw::auth::StrategyRegistry& auth_registry,
req_state *s, optional_yield y);
};
class RGWHandler_Auth_S3 : public RGWHandler_REST {
friend class RGWRESTMgr_S3;
const rgw::auth::StrategyRegistry& auth_registry;
public:
explicit RGWHandler_Auth_S3(const rgw::auth::StrategyRegistry& auth_registry)
: RGWHandler_REST(),
auth_registry(auth_registry) {
}
~RGWHandler_Auth_S3() override = default;
static int validate_bucket_name(const std::string& bucket);
static int validate_object_name(const std::string& bucket);
int init(rgw::sal::Driver* driver,
req_state *s,
rgw::io::BasicClient *cio) override;
int authorize(const DoutPrefixProvider *dpp, optional_yield y) override {
return RGW_Auth_S3::authorize(dpp, driver, auth_registry, s, y);
}
int postauth_init(optional_yield) override { return 0; }
};
class RGWHandler_REST_S3 : public RGWHandler_REST {
friend class RGWRESTMgr_S3;
protected:
const rgw::auth::StrategyRegistry& auth_registry;
public:
static int init_from_header(rgw::sal::Driver* driver, req_state *s, RGWFormat default_formatter,
bool configurable_format);
explicit RGWHandler_REST_S3(const rgw::auth::StrategyRegistry& auth_registry)
: RGWHandler_REST(),
auth_registry(auth_registry) {
}
~RGWHandler_REST_S3() override = default;
int init(rgw::sal::Driver* driver,
req_state *s,
rgw::io::BasicClient *cio) override;
int authorize(const DoutPrefixProvider *dpp, optional_yield y) override;
int postauth_init(optional_yield y) override;
};
class RGWHandler_REST_Service_S3 : public RGWHandler_REST_S3 {
protected:
bool is_usage_op() const {
return s->info.args.exists("usage");
}
RGWOp *op_get() override;
RGWOp *op_head() override;
public:
RGWHandler_REST_Service_S3(const rgw::auth::StrategyRegistry& auth_registry) :
RGWHandler_REST_S3(auth_registry) {}
~RGWHandler_REST_Service_S3() override = default;
};
class RGWHandler_REST_Bucket_S3 : public RGWHandler_REST_S3 {
const bool enable_pubsub;
protected:
bool is_acl_op() const {
return s->info.args.exists("acl");
}
bool is_cors_op() const {
return s->info.args.exists("cors");
}
bool is_lc_op() const {
return s->info.args.exists("lifecycle");
}
bool is_obj_update_op() const override {
return is_acl_op() || is_cors_op();
}
bool is_tagging_op() const {
return s->info.args.exists("tagging");
}
bool is_request_payment_op() const {
return s->info.args.exists("requestPayment");
}
bool is_policy_op() const {
return s->info.args.exists("policy");
}
bool is_object_lock_op() const {
return s->info.args.exists("object-lock");
}
bool is_notification_op() const {
if (enable_pubsub) {
return s->info.args.exists("notification");
}
return false;
}
bool is_replication_op() const {
return s->info.args.exists("replication");
}
bool is_policy_status_op() {
return s->info.args.exists("policyStatus");
}
bool is_block_public_access_op() {
return s->info.args.exists("publicAccessBlock");
}
bool is_bucket_encryption_op() {
return s->info.args.exists("encryption");
}
RGWOp *get_obj_op(bool get_data) const;
RGWOp *op_get() override;
RGWOp *op_head() override;
RGWOp *op_put() override;
RGWOp *op_delete() override;
RGWOp *op_post() override;
RGWOp *op_options() override;
public:
RGWHandler_REST_Bucket_S3(const rgw::auth::StrategyRegistry& auth_registry, bool _enable_pubsub) :
RGWHandler_REST_S3(auth_registry), enable_pubsub(_enable_pubsub) {}
~RGWHandler_REST_Bucket_S3() override = default;
};
class RGWHandler_REST_Obj_S3 : public RGWHandler_REST_S3 {
protected:
bool is_acl_op() const {
return s->info.args.exists("acl");
}
bool is_tagging_op() const {
return s->info.args.exists("tagging");
}
bool is_obj_retention_op() const {
return s->info.args.exists("retention");
}
bool is_obj_legal_hold_op() const {
return s->info.args.exists("legal-hold");
}
bool is_select_op() const {
return s->info.args.exists("select-type");
}
bool is_obj_update_op() const override {
return is_acl_op() || is_tagging_op() || is_obj_retention_op() || is_obj_legal_hold_op() || is_select_op();
}
RGWOp *get_obj_op(bool get_data);
RGWOp *op_get() override;
RGWOp *op_head() override;
RGWOp *op_put() override;
RGWOp *op_delete() override;
RGWOp *op_post() override;
RGWOp *op_options() override;
public:
using RGWHandler_REST_S3::RGWHandler_REST_S3;
~RGWHandler_REST_Obj_S3() override = default;
};
class RGWRESTMgr_S3 : public RGWRESTMgr {
private:
const bool enable_s3website;
const bool enable_sts;
const bool enable_iam;
const bool enable_pubsub;
public:
explicit RGWRESTMgr_S3(bool _enable_s3website=false, bool _enable_sts=false, bool _enable_iam=false, bool _enable_pubsub=false)
: enable_s3website(_enable_s3website),
enable_sts(_enable_sts),
enable_iam(_enable_iam),
enable_pubsub(_enable_pubsub) {
}
~RGWRESTMgr_S3() override = default;
RGWHandler_REST *get_handler(rgw::sal::Driver* driver,
req_state* s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix) override;
};
class RGWHandler_REST_Obj_S3Website;
static inline bool looks_like_ip_address(const char *bucket)
{
struct in6_addr a;
if (inet_pton(AF_INET6, bucket, static_cast<void*>(&a)) == 1) {
return true;
}
int num_periods = 0;
bool expect_period = false;
for (const char *b = bucket; *b; ++b) {
if (*b == '.') {
if (!expect_period)
return false;
++num_periods;
if (num_periods > 3)
return false;
expect_period = false;
}
else if (isdigit(*b)) {
expect_period = true;
}
else {
return false;
}
}
return (num_periods == 3);
}
inline int valid_s3_object_name(const std::string& name) {
if (name.size() > 1024) {
return -ERR_INVALID_OBJECT_NAME;
}
if (check_utf8(name.c_str(), name.size())) {
return -ERR_INVALID_OBJECT_NAME;
}
return 0;
}
inline int valid_s3_bucket_name(const std::string& name, bool relaxed=false)
{
// This function enforces Amazon's spec for bucket names.
// (The requirements, not the recommendations.)
int len = name.size();
int max = (relaxed ? 255 : 63);
if (len < 3) {
// Name too short
return -ERR_INVALID_BUCKET_NAME;
} else if (len > max) {
// Name too long
return -ERR_INVALID_BUCKET_NAME;
}
// bucket names must start with a number or letter
if (!(isalpha(name[0]) || isdigit(name[0]))) {
if (!relaxed)
return -ERR_INVALID_BUCKET_NAME;
else if (!(name[0] == '_' || name[0] == '.' || name[0] == '-'))
return -ERR_INVALID_BUCKET_NAME;
}
// bucket names must end with a number or letter
if (!(isalpha(name[len-1]) || isdigit(name[len-1])))
if (!relaxed)
return -ERR_INVALID_BUCKET_NAME;
for (const char *s = name.c_str(); *s; ++s) {
char c = *s;
if (isdigit(c))
continue;
if (isalpha(c)) {
// name cannot contain uppercase letters
if (relaxed || islower(c))
continue;
}
if (c == '_')
// name cannot contain underscore
if (relaxed)
continue;
if (c == '-')
continue;
if (c == '.') {
if (!relaxed && s && *s) {
// name cannot have consecutive periods or dashes
// adjacent to periods
// ensure s is neither the first nor the last character
char p = *(s-1);
char n = *(s+1);
if ((p != '-') && (n != '.') && (n != '-'))
continue;
} else {
continue;
}
}
// Invalid character
return -ERR_INVALID_BUCKET_NAME;
}
if (looks_like_ip_address(name.c_str()))
return -ERR_INVALID_BUCKET_NAME;
return 0;
}
namespace rgw::auth::s3 {
class AWSEngine : public rgw::auth::Engine {
public:
class VersionAbstractor {
static constexpr size_t DIGEST_SIZE_V2 = CEPH_CRYPTO_HMACSHA1_DIGESTSIZE;
static constexpr size_t DIGEST_SIZE_V4 = CEPH_CRYPTO_HMACSHA256_DIGESTSIZE;
/* Knowing the signature max size allows us to employ the sstring, and thus
* avoid dynamic allocations. The multiplier comes from representing digest
* in the base64-encoded form. */
static constexpr size_t SIGNATURE_MAX_SIZE = \
std::max(DIGEST_SIZE_V2, DIGEST_SIZE_V4) * 2 + sizeof('\0');
public:
virtual ~VersionAbstractor() {};
using access_key_id_t = std::string_view;
using client_signature_t = std::string_view;
using session_token_t = std::string_view;
using server_signature_t = basic_sstring<char, uint16_t, SIGNATURE_MAX_SIZE>;
using string_to_sign_t = std::string;
/* Transformation for crafting the AWS signature at server side which is
* used later to compare with the user-provided one. The methodology for
* doing that depends on AWS auth version. */
using signature_factory_t = \
std::function<server_signature_t(CephContext* cct,
const std::string& secret_key,
const string_to_sign_t& string_to_sign)>;
/* Return an instance of Completer for verifying the payload's fingerprint
* if necessary. Otherwise caller gets nullptr. Caller may provide secret
* key */
using completer_factory_t = \
std::function<rgw::auth::Completer::cmplptr_t(
const boost::optional<std::string>& secret_key)>;
struct auth_data_t {
access_key_id_t access_key_id;
client_signature_t client_signature;
session_token_t session_token;
string_to_sign_t string_to_sign;
signature_factory_t signature_factory;
completer_factory_t completer_factory;
};
virtual auth_data_t get_auth_data(const req_state* s) const = 0;
};
protected:
CephContext* cct;
const VersionAbstractor& ver_abstractor;
AWSEngine(CephContext* const cct, const VersionAbstractor& ver_abstractor)
: cct(cct),
ver_abstractor(ver_abstractor) {
}
using result_t = rgw::auth::Engine::result_t;
using string_to_sign_t = VersionAbstractor::string_to_sign_t;
using signature_factory_t = VersionAbstractor::signature_factory_t;
using completer_factory_t = VersionAbstractor::completer_factory_t;
/* TODO(rzarzynski): clean up. We've too many input parameter hee. Also
* the signature get_auth_data() of VersionAbstractor is too complicated.
* Replace these thing with a simple, dedicated structure. */
virtual result_t authenticate(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
const req_state* s,
optional_yield y) const = 0;
public:
result_t authenticate(const DoutPrefixProvider* dpp, const req_state* const s,
optional_yield y) const final;
};
class AWSGeneralAbstractor : public AWSEngine::VersionAbstractor {
CephContext* const cct;
virtual boost::optional<std::string>
get_v4_canonical_headers(const req_info& info,
const std::string_view& signedheaders,
const bool using_qs) const;
auth_data_t get_auth_data_v2(const req_state* s) const;
auth_data_t get_auth_data_v4(const req_state* s, const bool using_qs) const;
public:
explicit AWSGeneralAbstractor(CephContext* const cct)
: cct(cct) {
}
auth_data_t get_auth_data(const req_state* s) const override;
};
class AWSGeneralBoto2Abstractor : public AWSGeneralAbstractor {
boost::optional<std::string>
get_v4_canonical_headers(const req_info& info,
const std::string_view& signedheaders,
const bool using_qs) const override;
public:
using AWSGeneralAbstractor::AWSGeneralAbstractor;
};
class AWSBrowserUploadAbstractor : public AWSEngine::VersionAbstractor {
static std::string to_string(ceph::bufferlist bl) {
return std::string(bl.c_str(),
static_cast<std::string::size_type>(bl.length()));
}
auth_data_t get_auth_data_v2(const req_state* s) const;
auth_data_t get_auth_data_v4(const req_state* s) const;
public:
explicit AWSBrowserUploadAbstractor(CephContext*) {
}
auth_data_t get_auth_data(const req_state* s) const override;
};
class AWSSignerV4 {
const DoutPrefixProvider *dpp;
CephContext *cct;
public:
AWSSignerV4(const DoutPrefixProvider *_dpp) : dpp(_dpp),
cct(_dpp->get_cct()) {}
using access_key_id_t = std::string_view;
using string_to_sign_t = AWSEngine::VersionAbstractor::string_to_sign_t;
using signature_headers_t = std::map<std::string, std::string>;
struct prepare_result_t;
using signature_factory_t = \
std::function<signature_headers_t(const DoutPrefixProvider* dpp,
const std::string& secret_key,
const prepare_result_t&)>;
struct prepare_result_t {
access_key_id_t access_key_id;
std::string date;
std::string scope;
std::string signed_headers;
string_to_sign_t string_to_sign;
std::map<std::string, std::string> extra_headers;
signature_factory_t signature_factory;
};
static prepare_result_t prepare(const DoutPrefixProvider *dpp,
const std::string& access_key_id,
const string& region,
const string& service,
const req_info& info,
const bufferlist *opt_content,
bool s3_op);
};
extern AWSSignerV4::signature_headers_t
gen_v4_signature(const DoutPrefixProvider *dpp,
const std::string_view& secret_key,
const AWSSignerV4::prepare_result_t& sig_info);
class LDAPEngine : public AWSEngine {
static rgw::LDAPHelper* ldh;
static std::mutex mtx;
static void init(CephContext* const cct);
using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t;
using auth_info_t = rgw::auth::RemoteApplier::AuthInfo;
using result_t = rgw::auth::Engine::result_t;
protected:
rgw::sal::Driver* driver;
const rgw::auth::RemoteApplier::Factory* const apl_factory;
acl_strategy_t get_acl_strategy() const;
auth_info_t get_creds_info(const rgw::RGWToken& token) const noexcept;
result_t authenticate(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t&,
const completer_factory_t& completer_factory,
const req_state* s,
optional_yield y) const override;
public:
LDAPEngine(CephContext* const cct,
rgw::sal::Driver* driver,
const VersionAbstractor& ver_abstractor,
const rgw::auth::RemoteApplier::Factory* const apl_factory)
: AWSEngine(cct, ver_abstractor),
driver(driver),
apl_factory(apl_factory) {
init(cct);
}
using AWSEngine::authenticate;
const char* get_name() const noexcept override {
return "rgw::auth::s3::LDAPEngine";
}
static bool valid();
static void shutdown();
};
class LocalEngine : public AWSEngine {
rgw::sal::Driver* driver;
const rgw::auth::LocalApplier::Factory* const apl_factory;
result_t authenticate(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
const req_state* s,
optional_yield y) const override;
public:
LocalEngine(CephContext* const cct,
rgw::sal::Driver* driver,
const VersionAbstractor& ver_abstractor,
const rgw::auth::LocalApplier::Factory* const apl_factory)
: AWSEngine(cct, ver_abstractor),
driver(driver),
apl_factory(apl_factory) {
}
using AWSEngine::authenticate;
const char* get_name() const noexcept override {
return "rgw::auth::s3::LocalEngine";
}
};
class STSEngine : public AWSEngine {
rgw::sal::Driver* driver;
const rgw::auth::LocalApplier::Factory* const local_apl_factory;
const rgw::auth::RemoteApplier::Factory* const remote_apl_factory;
const rgw::auth::RoleApplier::Factory* const role_apl_factory;
using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t;
using auth_info_t = rgw::auth::RemoteApplier::AuthInfo;
acl_strategy_t get_acl_strategy() const { return nullptr; };
auth_info_t get_creds_info(const STS::SessionToken& token) const noexcept;
int get_session_token(const DoutPrefixProvider* dpp, const std::string_view& session_token,
STS::SessionToken& token) const;
result_t authenticate(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
const req_state* s,
optional_yield y) const override;
public:
STSEngine(CephContext* const cct,
rgw::sal::Driver* driver,
const VersionAbstractor& ver_abstractor,
const rgw::auth::LocalApplier::Factory* const local_apl_factory,
const rgw::auth::RemoteApplier::Factory* const remote_apl_factory,
const rgw::auth::RoleApplier::Factory* const role_apl_factory)
: AWSEngine(cct, ver_abstractor),
driver(driver),
local_apl_factory(local_apl_factory),
remote_apl_factory(remote_apl_factory),
role_apl_factory(role_apl_factory) {
}
using AWSEngine::authenticate;
const char* get_name() const noexcept override {
return "rgw::auth::s3::STSEngine";
}
};
class S3AnonymousEngine : public rgw::auth::AnonymousEngine {
bool is_applicable(const req_state* s) const noexcept override;
public:
/* Let's reuse the parent class' constructor. */
using rgw::auth::AnonymousEngine::AnonymousEngine;
const char* get_name() const noexcept override {
return "rgw::auth::s3::S3AnonymousEngine";
}
};
} // namespace rgw::auth::s3
| 36,332 | 28.879112 | 129 |
h
|
null |
ceph-main/src/rgw/rgw_rest_s3website.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 Robin H. Johnson <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "rgw_rest_s3.h"
class RGWHandler_REST_S3Website : public RGWHandler_REST_S3 {
std::string original_object_name; // object name before retarget()
bool web_dir() const;
protected:
int retarget(RGWOp *op, RGWOp **new_op, optional_yield y) override;
// TODO: this should be virtual I think, and ensure that it's always
// overridden, but that conflates that op_get/op_head are defined in this
// class and call this; and don't need to be overridden later.
virtual RGWOp *get_obj_op(bool get_data) { return NULL; }
RGWOp *op_get() override;
RGWOp *op_head() override;
// Only allowed to use GET+HEAD
RGWOp *op_put() override { return NULL; }
RGWOp *op_delete() override { return NULL; }
RGWOp *op_post() override { return NULL; }
RGWOp *op_copy() override { return NULL; }
RGWOp *op_options() override { return NULL; }
int serve_errordoc(const DoutPrefixProvider *dpp, int http_ret, const std::string &errordoc_key, optional_yield y);
public:
using RGWHandler_REST_S3::RGWHandler_REST_S3;
~RGWHandler_REST_S3Website() override = default;
int init(rgw::sal::Driver* driver, req_state *s, rgw::io::BasicClient* cio) override;
int error_handler(int err_no, std::string *error_content, optional_yield y) override;
};
class RGWHandler_REST_Service_S3Website : public RGWHandler_REST_S3Website {
protected:
RGWOp *get_obj_op(bool get_data) override;
public:
using RGWHandler_REST_S3Website::RGWHandler_REST_S3Website;
~RGWHandler_REST_Service_S3Website() override = default;
};
class RGWHandler_REST_Obj_S3Website : public RGWHandler_REST_S3Website {
protected:
RGWOp *get_obj_op(bool get_data) override;
public:
using RGWHandler_REST_S3Website::RGWHandler_REST_S3Website;
~RGWHandler_REST_Obj_S3Website() override = default;
};
/* The cross-inheritance from Obj to Bucket is deliberate!
* S3Websites do NOT support any bucket operations
*/
class RGWHandler_REST_Bucket_S3Website : public RGWHandler_REST_S3Website {
protected:
RGWOp *get_obj_op(bool get_data) override;
public:
using RGWHandler_REST_S3Website::RGWHandler_REST_S3Website;
~RGWHandler_REST_Bucket_S3Website() override = default;
};
// TODO: do we actually need this?
class RGWGetObj_ObjStore_S3Website : public RGWGetObj_ObjStore_S3
{
friend class RGWHandler_REST_S3Website;
private:
bool is_errordoc_request;
public:
RGWGetObj_ObjStore_S3Website() : is_errordoc_request(false) {}
explicit RGWGetObj_ObjStore_S3Website(bool is_errordoc_request) : is_errordoc_request(false) { this->is_errordoc_request = is_errordoc_request; }
~RGWGetObj_ObjStore_S3Website() override {}
int send_response_data_error(optional_yield y) override;
int send_response_data(bufferlist& bl, off_t ofs, off_t len) override;
// We override RGWGetObj_ObjStore::get_params here, to allow ignoring all
// conditional params for error pages.
int get_params(optional_yield y) override {
if (is_errordoc_request) {
range_str = NULL;
if_mod = NULL;
if_unmod = NULL;
if_match = NULL;
if_nomatch = NULL;
return 0;
} else {
return RGWGetObj_ObjStore_S3::get_params(y);
}
}
};
| 3,629 | 34.940594 | 147 |
h
|
null |
ceph-main/src/rgw/rgw_rest_sts.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <vector>
#include <string>
#include <array>
#include <string_view>
#include <sstream>
#include <memory>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/format.hpp>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <boost/tokenizer.hpp>
#include "ceph_ver.h"
#include "common/Formatter.h"
#include "common/utf8.h"
#include "common/ceph_json.h"
#include "rgw_rest.h"
#include "rgw_auth.h"
#include "rgw_auth_registry.h"
#include "jwt-cpp/jwt.h"
#include "rgw_rest_sts.h"
#include "rgw_formats.h"
#include "rgw_client_io.h"
#include "rgw_request.h"
#include "rgw_process.h"
#include "rgw_iam_policy.h"
#include "rgw_iam_policy_keywords.h"
#include "rgw_sts.h"
#include "rgw_rest_oidc_provider.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw::auth::sts {
bool
WebTokenEngine::is_applicable(const std::string& token) const noexcept
{
return ! token.empty();
}
std::string
WebTokenEngine::get_role_tenant(const string& role_arn) const
{
string tenant;
auto r_arn = rgw::ARN::parse(role_arn);
if (r_arn) {
tenant = r_arn->account;
}
return tenant;
}
std::string
WebTokenEngine::get_role_name(const string& role_arn) const
{
string role_name;
auto r_arn = rgw::ARN::parse(role_arn);
if (r_arn) {
role_name = r_arn->resource;
}
if (!role_name.empty()) {
auto pos = role_name.find_last_of('/');
if(pos != string::npos) {
role_name = role_name.substr(pos + 1);
}
}
return role_name;
}
std::unique_ptr<rgw::sal::RGWOIDCProvider>
WebTokenEngine::get_provider(const DoutPrefixProvider *dpp, const string& role_arn, const string& iss, optional_yield y) const
{
string tenant = get_role_tenant(role_arn);
string idp_url = iss;
auto pos = idp_url.find("http://");
if (pos == std::string::npos) {
pos = idp_url.find("https://");
if (pos != std::string::npos) {
idp_url.erase(pos, 8);
} else {
pos = idp_url.find("www.");
if (pos != std::string::npos) {
idp_url.erase(pos, 4);
}
}
} else {
idp_url.erase(pos, 7);
}
auto provider_arn = rgw::ARN(idp_url, "oidc-provider", tenant);
string p_arn = provider_arn.to_string();
std::unique_ptr<rgw::sal::RGWOIDCProvider> provider = driver->get_oidc_provider();
provider->set_arn(p_arn);
provider->set_tenant(tenant);
auto ret = provider->get(dpp, y);
if (ret < 0) {
return nullptr;
}
return provider;
}
bool
WebTokenEngine::is_client_id_valid(vector<string>& client_ids, const string& client_id) const
{
for (auto it : client_ids) {
if (it == client_id) {
return true;
}
}
return false;
}
bool
WebTokenEngine::is_cert_valid(const vector<string>& thumbprints, const string& cert) const
{
//calculate thumbprint of cert
std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(BIO_new_mem_buf(cert.data(), cert.size()), BIO_free_all);
std::unique_ptr<BIO, decltype(&BIO_free_all)> keybio(BIO_new(BIO_s_mem()), BIO_free_all);
string pw="";
std::unique_ptr<X509, decltype(&X509_free)> x_509cert(PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast<char*>(pw.c_str())), X509_free);
const EVP_MD* fprint_type = EVP_sha1();
unsigned int fprint_size;
unsigned char fprint[EVP_MAX_MD_SIZE];
if (!X509_digest(x_509cert.get(), fprint_type, fprint, &fprint_size)) {
return false;
}
stringstream ss;
for (unsigned int i = 0; i < fprint_size; i++) {
ss << std::setfill('0') << std::setw(2) << std::hex << (0xFF & (unsigned int)fprint[i]);
}
std::string digest = ss.str();
for (auto& it : thumbprints) {
if (boost::iequals(it,digest)) {
return true;
}
}
return false;
}
template <typename T>
void
WebTokenEngine::recurse_and_insert(const string& key, const jwt::claim& c, T& t) const
{
string s_val;
jwt::claim::type c_type = c.get_type();
switch(c_type) {
case jwt::claim::type::null:
break;
case jwt::claim::type::boolean:
case jwt::claim::type::number:
case jwt::claim::type::int64:
{
s_val = c.to_json().serialize();
t.emplace(std::make_pair(key, s_val));
break;
}
case jwt::claim::type::string:
{
s_val = c.to_json().to_str();
t.emplace(std::make_pair(key, s_val));
break;
}
case jwt::claim::type::array:
{
const picojson::array& arr = c.as_array();
for (auto& a : arr) {
recurse_and_insert(key, jwt::claim(a), t);
}
break;
}
case jwt::claim::type::object:
{
const picojson::object& obj = c.as_object();
for (auto& m : obj) {
recurse_and_insert(m.first, jwt::claim(m.second), t);
}
break;
}
}
return;
}
//Extract all token claims so that they can be later used in the Condition element of Role's trust policy
WebTokenEngine::token_t
WebTokenEngine::get_token_claims(const jwt::decoded_jwt& decoded) const
{
WebTokenEngine::token_t token;
const auto& claims = decoded.get_payload_claims();
for (auto& c : claims) {
if (c.first == string(princTagsNamespace)) {
continue;
}
recurse_and_insert(c.first, c.second, token);
}
return token;
}
//Offline validation of incoming Web Token which is a signed JWT (JSON Web Token)
std::tuple<boost::optional<WebTokenEngine::token_t>, boost::optional<WebTokenEngine::principal_tags_t>>
WebTokenEngine::get_from_jwt(const DoutPrefixProvider* dpp, const std::string& token, const req_state* const s,
optional_yield y) const
{
WebTokenEngine::token_t t;
WebTokenEngine::principal_tags_t principal_tags;
try {
const auto& decoded = jwt::decode(token);
auto& payload = decoded.get_payload();
ldpp_dout(dpp, 20) << " payload = " << payload << dendl;
t = get_token_claims(decoded);
string iss;
if (decoded.has_issuer()) {
iss = decoded.get_issuer();
}
set<string> aud;
if (decoded.has_audience()) {
aud = decoded.get_audience();
}
string client_id;
if (decoded.has_payload_claim("client_id")) {
client_id = decoded.get_payload_claim("client_id").as_string();
}
if (client_id.empty() && decoded.has_payload_claim("clientId")) {
client_id = decoded.get_payload_claim("clientId").as_string();
}
string azp;
if (decoded.has_payload_claim("azp")) {
azp = decoded.get_payload_claim("azp").as_string();
}
string role_arn = s->info.args.get("RoleArn");
auto provider = get_provider(dpp, role_arn, iss, y);
if (! provider) {
ldpp_dout(dpp, 0) << "Couldn't get oidc provider info using input iss" << iss << dendl;
throw -EACCES;
}
if (decoded.has_payload_claim(string(princTagsNamespace))) {
auto& cl = decoded.get_payload_claim(string(princTagsNamespace));
if (cl.get_type() == jwt::claim::type::object || cl.get_type() == jwt::claim::type::array) {
recurse_and_insert("dummy", cl, principal_tags);
for (auto it : principal_tags) {
ldpp_dout(dpp, 5) << "Key: " << it.first << " Value: " << it.second << dendl;
}
} else {
ldpp_dout(dpp, 0) << "Malformed principal tags" << cl.as_string() << dendl;
throw -EINVAL;
}
}
vector<string> client_ids = provider->get_client_ids();
vector<string> thumbprints = provider->get_thumbprints();
if (! client_ids.empty()) {
bool found = false;
for (auto& it : aud) {
if (is_client_id_valid(client_ids, it)) {
found = true;
break;
}
}
if (! found && ! is_client_id_valid(client_ids, client_id) && ! is_client_id_valid(client_ids, azp)) {
ldpp_dout(dpp, 0) << "Client id in token doesn't match with that registered with oidc provider" << dendl;
throw -EACCES;
}
}
//Validate signature
if (decoded.has_algorithm()) {
auto& algorithm = decoded.get_algorithm();
try {
validate_signature(dpp, decoded, algorithm, iss, thumbprints, y);
} catch (...) {
throw -EACCES;
}
} else {
return {boost::none, boost::none};
}
} catch (int error) {
if (error == -EACCES) {
throw -EACCES;
}
ldpp_dout(dpp, 5) << "Invalid JWT token" << dendl;
return {boost::none, boost::none};
}
catch (...) {
ldpp_dout(dpp, 5) << "Invalid JWT token" << dendl;
return {boost::none, boost::none};
}
return {t, principal_tags};
}
std::string
WebTokenEngine::get_cert_url(const string& iss, const DoutPrefixProvider *dpp, optional_yield y) const
{
string cert_url;
string openidc_wellknown_url = iss;
bufferlist openidc_resp;
if (openidc_wellknown_url.back() == '/') {
openidc_wellknown_url.pop_back();
}
openidc_wellknown_url.append("/.well-known/openid-configuration");
RGWHTTPTransceiver openidc_req(cct, "GET", openidc_wellknown_url, &openidc_resp);
//Headers
openidc_req.append_header("Content-Type", "application/x-www-form-urlencoded");
int res = openidc_req.process(y);
if (res < 0) {
ldpp_dout(dpp, 10) << "HTTP request res: " << res << dendl;
throw -EINVAL;
}
//Debug only
ldpp_dout(dpp, 20) << "HTTP status: " << openidc_req.get_http_status() << dendl;
ldpp_dout(dpp, 20) << "JSON Response is: " << openidc_resp.c_str() << dendl;
JSONParser parser;
if (parser.parse(openidc_resp.c_str(), openidc_resp.length())) {
JSONObj::data_val val;
if (parser.get_data("jwks_uri", &val)) {
cert_url = val.str.c_str();
ldpp_dout(dpp, 20) << "Cert URL is: " << cert_url.c_str() << dendl;
} else {
ldpp_dout(dpp, 0) << "Malformed json returned while fetching openidc url" << dendl;
}
}
return cert_url;
}
void
WebTokenEngine::validate_signature(const DoutPrefixProvider* dpp, const jwt::decoded_jwt& decoded, const string& algorithm, const string& iss, const vector<string>& thumbprints, optional_yield y) const
{
if (algorithm != "HS256" && algorithm != "HS384" && algorithm != "HS512") {
string cert_url = get_cert_url(iss, dpp, y);
if (cert_url.empty()) {
throw -EINVAL;
}
// Get certificate
bufferlist cert_resp;
RGWHTTPTransceiver cert_req(cct, "GET", cert_url, &cert_resp);
//Headers
cert_req.append_header("Content-Type", "application/x-www-form-urlencoded");
int res = cert_req.process(y);
if (res < 0) {
ldpp_dout(dpp, 10) << "HTTP request res: " << res << dendl;
throw -EINVAL;
}
//Debug only
ldpp_dout(dpp, 20) << "HTTP status: " << cert_req.get_http_status() << dendl;
ldpp_dout(dpp, 20) << "JSON Response is: " << cert_resp.c_str() << dendl;
JSONParser parser;
if (parser.parse(cert_resp.c_str(), cert_resp.length())) {
JSONObj::data_val val;
if (parser.get_data("keys", &val)) {
if (val.str[0] == '[') {
val.str.erase(0, 1);
}
if (val.str[val.str.size() - 1] == ']') {
val.str = val.str.erase(val.str.size() - 1, 1);
}
if (parser.parse(val.str.c_str(), val.str.size())) {
vector<string> x5c;
if (JSONDecoder::decode_json("x5c", x5c, &parser)) {
string cert;
bool found_valid_cert = false;
for (auto& it : x5c) {
cert = "-----BEGIN CERTIFICATE-----\n" + it + "\n-----END CERTIFICATE-----";
ldpp_dout(dpp, 20) << "Certificate is: " << cert.c_str() << dendl;
if (is_cert_valid(thumbprints, cert)) {
found_valid_cert = true;
break;
}
found_valid_cert = true;
}
if (! found_valid_cert) {
ldpp_dout(dpp, 0) << "Cert doesn't match that with the thumbprints registered with oidc provider: " << cert.c_str() << dendl;
throw -EINVAL;
}
try {
//verify method takes care of expired tokens also
if (algorithm == "RS256") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::rs256{cert});
verifier.verify(decoded);
} else if (algorithm == "RS384") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::rs384{cert});
verifier.verify(decoded);
} else if (algorithm == "RS512") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::rs512{cert});
verifier.verify(decoded);
} else if (algorithm == "ES256") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::es256{cert});
verifier.verify(decoded);
} else if (algorithm == "ES384") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::es384{cert});
verifier.verify(decoded);
} else if (algorithm == "ES512") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::es512{cert});
verifier.verify(decoded);
} else if (algorithm == "PS256") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::ps256{cert});
verifier.verify(decoded);
} else if (algorithm == "PS384") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::ps384{cert});
verifier.verify(decoded);
} else if (algorithm == "PS512") {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::ps512{cert});
verifier.verify(decoded);
}
} catch (std::runtime_error& e) {
ldpp_dout(dpp, 0) << "Signature validation failed: " << e.what() << dendl;
throw;
}
catch (...) {
ldpp_dout(dpp, 0) << "Signature validation failed" << dendl;
throw;
}
} else {
ldpp_dout(dpp, 0) << "x5c not present" << dendl;
throw -EINVAL;
}
} else {
ldpp_dout(dpp, 0) << "Malformed JSON object for keys" << dendl;
throw -EINVAL;
}
} else {
ldpp_dout(dpp, 0) << "keys not present in JSON" << dendl;
throw -EINVAL;
} //if-else get-data
} else {
ldpp_dout(dpp, 0) << "Malformed json returned while fetching cert" << dendl;
throw -EINVAL;
} //if-else parser cert_resp
} else {
ldpp_dout(dpp, 0) << "JWT signed by HMAC algos are currently not supported" << dendl;
throw -EINVAL;
}
}
WebTokenEngine::result_t
WebTokenEngine::authenticate( const DoutPrefixProvider* dpp,
const std::string& token,
const req_state* const s,
optional_yield y) const
{
if (! is_applicable(token)) {
return result_t::deny();
}
try {
auto [t, princ_tags] = get_from_jwt(dpp, token, s, y);
if (t) {
string role_session = s->info.args.get("RoleSessionName");
if (role_session.empty()) {
ldout(s->cct, 0) << "Role Session Name is empty " << dendl;
return result_t::deny(-EACCES);
}
string role_arn = s->info.args.get("RoleArn");
string role_tenant = get_role_tenant(role_arn);
string role_name = get_role_name(role_arn);
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, role_tenant);
int ret = role->get(dpp, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "Role not found: name:" << role_name << " tenant: " << role_tenant << dendl;
return result_t::deny(-EACCES);
}
boost::optional<multimap<string,string>> role_tags = role->get_tags();
auto apl = apl_factory->create_apl_web_identity(cct, s, role_session, role_tenant, *t, role_tags, princ_tags);
return result_t::grant(std::move(apl));
}
return result_t::deny(-EACCES);
}
catch (...) {
return result_t::deny(-EACCES);
}
}
} // namespace rgw::auth::sts
int RGWREST_STS::verify_permission(optional_yield y)
{
STS::STSService _sts(s->cct, driver, s->user->get_id(), s->auth.identity.get());
sts = std::move(_sts);
string rArn = s->info.args.get("RoleArn");
const auto& [ret, role] = sts.getRoleInfo(s, rArn, y);
if (ret < 0) {
ldpp_dout(this, 0) << "failed to get role info using role arn: " << rArn << dendl;
return ret;
}
string policy = role->get_assume_role_policy();
buffer::list bl = buffer::list::static_from_string(policy);
//Parse the policy
//TODO - This step should be part of Role Creation
try {
const rgw::IAM::Policy p(s->cct, s->user->get_tenant(), bl, false);
if (!s->principal_tags.empty()) {
auto res = p.eval(s->env, *s->auth.identity, rgw::IAM::stsTagSession, boost::none);
if (res != rgw::IAM::Effect::Allow) {
ldout(s->cct, 0) << "evaluating policy for stsTagSession returned deny/pass" << dendl;
return -EPERM;
}
}
uint64_t op;
if (get_type() == RGW_STS_ASSUME_ROLE_WEB_IDENTITY) {
op = rgw::IAM::stsAssumeRoleWithWebIdentity;
} else {
op = rgw::IAM::stsAssumeRole;
}
auto res = p.eval(s->env, *s->auth.identity, op, boost::none);
if (res != rgw::IAM::Effect::Allow) {
ldout(s->cct, 0) << "evaluating policy for op: " << op << " returned deny/pass" << dendl;
return -EPERM;
}
} catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 0) << "failed to parse policy: " << e.what() << dendl;
return -EPERM;
}
return 0;
}
void RGWREST_STS::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
int RGWSTSGetSessionToken::verify_permission(optional_yield y)
{
rgw::Partition partition = rgw::Partition::aws;
rgw::Service service = rgw::Service::s3;
if (!verify_user_permission(this,
s,
rgw::ARN(partition, service, "", s->user->get_tenant(), ""),
rgw::IAM::stsGetSessionToken)) {
ldpp_dout(this, 0) << "User does not have permssion to perform GetSessionToken" << dendl;
return -EACCES;
}
return 0;
}
int RGWSTSGetSessionToken::get_params()
{
duration = s->info.args.get("DurationSeconds");
serialNumber = s->info.args.get("SerialNumber");
tokenCode = s->info.args.get("TokenCode");
if (! duration.empty()) {
string err;
uint64_t duration_in_secs = strict_strtoll(duration.c_str(), 10, &err);
if (!err.empty()) {
ldpp_dout(this, 0) << "Invalid value of input duration: " << duration << dendl;
return -EINVAL;
}
if (duration_in_secs < STS::GetSessionTokenRequest::getMinDuration() ||
duration_in_secs > s->cct->_conf->rgw_sts_max_session_duration) {
ldpp_dout(this, 0) << "Invalid duration in secs: " << duration_in_secs << dendl;
return -EINVAL;
}
}
return 0;
}
void RGWSTSGetSessionToken::execute(optional_yield y)
{
if (op_ret = get_params(); op_ret < 0) {
return;
}
STS::STSService sts(s->cct, driver, s->user->get_id(), s->auth.identity.get());
STS::GetSessionTokenRequest req(duration, serialNumber, tokenCode);
const auto& [ret, creds] = sts.getSessionToken(this, req);
op_ret = std::move(ret);
//Dump the output
if (op_ret == 0) {
s->formatter->open_object_section("GetSessionTokenResponse");
s->formatter->open_object_section("GetSessionTokenResult");
s->formatter->open_object_section("Credentials");
creds.dump(s->formatter);
s->formatter->close_section();
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWSTSAssumeRoleWithWebIdentity::get_params()
{
duration = s->info.args.get("DurationSeconds");
providerId = s->info.args.get("ProviderId");
policy = s->info.args.get("Policy");
roleArn = s->info.args.get("RoleArn");
roleSessionName = s->info.args.get("RoleSessionName");
iss = s->info.args.get("provider_id");
sub = s->info.args.get("sub");
aud = s->info.args.get("aud");
if (roleArn.empty() || roleSessionName.empty() || sub.empty() || aud.empty()) {
ldpp_dout(this, 0) << "ERROR: one of role arn or role session name or token is empty" << dendl;
return -EINVAL;
}
if (! policy.empty()) {
bufferlist bl = bufferlist::static_from_string(policy);
try {
const rgw::IAM::Policy p(
s->cct, s->user->get_tenant(), bl,
s->cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
}
catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 5) << "failed to parse policy: " << e.what() << "policy" << policy << dendl;
s->err.message = e.what();
return -ERR_MALFORMED_DOC;
}
}
return 0;
}
void RGWSTSAssumeRoleWithWebIdentity::execute(optional_yield y)
{
if (op_ret = get_params(); op_ret < 0) {
return;
}
STS::AssumeRoleWithWebIdentityRequest req(s->cct, duration, providerId, policy, roleArn,
roleSessionName, iss, sub, aud, s->principal_tags);
STS::AssumeRoleWithWebIdentityResponse response = sts.assumeRoleWithWebIdentity(this, req);
op_ret = std::move(response.assumeRoleResp.retCode);
//Dump the output
if (op_ret == 0) {
s->formatter->open_object_section("AssumeRoleWithWebIdentityResponse");
s->formatter->open_object_section("AssumeRoleWithWebIdentityResult");
encode_json("SubjectFromWebIdentityToken", response.sub , s->formatter);
encode_json("Audience", response.aud , s->formatter);
s->formatter->open_object_section("AssumedRoleUser");
response.assumeRoleResp.user.dump(s->formatter);
s->formatter->close_section();
s->formatter->open_object_section("Credentials");
response.assumeRoleResp.creds.dump(s->formatter);
s->formatter->close_section();
encode_json("Provider", response.providerId , s->formatter);
encode_json("PackedPolicySize", response.assumeRoleResp.packedPolicySize , s->formatter);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGWSTSAssumeRole::get_params()
{
duration = s->info.args.get("DurationSeconds");
externalId = s->info.args.get("ExternalId");
policy = s->info.args.get("Policy");
roleArn = s->info.args.get("RoleArn");
roleSessionName = s->info.args.get("RoleSessionName");
serialNumber = s->info.args.get("SerialNumber");
tokenCode = s->info.args.get("TokenCode");
if (roleArn.empty() || roleSessionName.empty()) {
ldpp_dout(this, 0) << "ERROR: one of role arn or role session name is empty" << dendl;
return -EINVAL;
}
if (! policy.empty()) {
bufferlist bl = bufferlist::static_from_string(policy);
try {
const rgw::IAM::Policy p(
s->cct, s->user->get_tenant(), bl,
s->cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
}
catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 0) << "failed to parse policy: " << e.what() << "policy" << policy << dendl;
s->err.message = e.what();
return -ERR_MALFORMED_DOC;
}
}
return 0;
}
void RGWSTSAssumeRole::execute(optional_yield y)
{
if (op_ret = get_params(); op_ret < 0) {
return;
}
STS::AssumeRoleRequest req(s->cct, duration, externalId, policy, roleArn,
roleSessionName, serialNumber, tokenCode);
STS::AssumeRoleResponse response = sts.assumeRole(s, req, y);
op_ret = std::move(response.retCode);
//Dump the output
if (op_ret == 0) {
s->formatter->open_object_section("AssumeRoleResponse");
s->formatter->open_object_section("AssumeRoleResult");
s->formatter->open_object_section("Credentials");
response.creds.dump(s->formatter);
s->formatter->close_section();
s->formatter->open_object_section("AssumedRoleUser");
response.user.dump(s->formatter);
s->formatter->close_section();
encode_json("PackedPolicySize", response.packedPolicySize , s->formatter);
s->formatter->close_section();
s->formatter->close_section();
}
}
int RGW_Auth_STS::authorize(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw::auth::StrategyRegistry& auth_registry,
req_state *s, optional_yield y)
{
return rgw::auth::Strategy::apply(dpp, auth_registry.get_sts(), s, y);
}
using op_generator = RGWOp*(*)();
static const std::unordered_map<std::string_view, op_generator> op_generators = {
{"AssumeRole", []() -> RGWOp* {return new RGWSTSAssumeRole;}},
{"GetSessionToken", []() -> RGWOp* {return new RGWSTSGetSessionToken;}},
{"AssumeRoleWithWebIdentity", []() -> RGWOp* {return new RGWSTSAssumeRoleWithWebIdentity;}}
};
bool RGWHandler_REST_STS::action_exists(const req_state* s)
{
if (s->info.args.exists("Action")) {
const std::string action_name = s->info.args.get("Action");
return op_generators.contains(action_name);
}
return false;
}
RGWOp *RGWHandler_REST_STS::op_post()
{
if (s->info.args.exists("Action")) {
const std::string action_name = s->info.args.get("Action");
const auto action_it = op_generators.find(action_name);
if (action_it != op_generators.end()) {
return action_it->second();
}
ldpp_dout(s, 10) << "unknown action '" << action_name << "' for STS handler" << dendl;
} else {
ldpp_dout(s, 10) << "missing action argument in STS handler" << dendl;
}
return nullptr;
}
int RGWHandler_REST_STS::init(rgw::sal::Driver* driver,
req_state *s,
rgw::io::BasicClient *cio)
{
s->dialect = "sts";
s->prot_flags = RGW_REST_STS;
return RGWHandler_REST::init(driver, s, cio);
}
int RGWHandler_REST_STS::authorize(const DoutPrefixProvider* dpp, optional_yield y)
{
if (s->info.args.exists("Action") && s->info.args.get("Action") == "AssumeRoleWithWebIdentity") {
return RGW_Auth_STS::authorize(dpp, driver, auth_registry, s, y);
}
return RGW_Auth_S3::authorize(dpp, driver, auth_registry, s, y);
}
RGWHandler_REST*
RGWRESTMgr_STS::get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix)
{
return new RGWHandler_REST_STS(auth_registry);
}
| 26,562 | 31.393902 | 201 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_sts.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_auth.h"
#include "rgw_auth_filters.h"
#include "rgw_rest.h"
#include "rgw_sts.h"
#include "rgw_web_idp.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#include "jwt-cpp/jwt.h"
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
#include "rgw_oidc_provider.h"
namespace rgw::auth::sts {
class WebTokenEngine : public rgw::auth::Engine {
static constexpr std::string_view princTagsNamespace = "https://aws.amazon.com/tags";
CephContext* const cct;
rgw::sal::Driver* driver;
using result_t = rgw::auth::Engine::result_t;
using Pair = std::pair<std::string, std::string>;
using token_t = std::unordered_multimap<string, string>;
using principal_tags_t = std::set<Pair>;
const rgw::auth::TokenExtractor* const extractor;
const rgw::auth::WebIdentityApplier::Factory* const apl_factory;
bool is_applicable(const std::string& token) const noexcept;
bool is_client_id_valid(std::vector<std::string>& client_ids, const std::string& client_id) const;
bool is_cert_valid(const std::vector<std::string>& thumbprints, const std::string& cert) const;
std::unique_ptr<rgw::sal::RGWOIDCProvider> get_provider(const DoutPrefixProvider *dpp, const std::string& role_arn, const std::string& iss, optional_yield y) const;
std::string get_role_tenant(const std::string& role_arn) const;
std::string get_role_name(const string& role_arn) const;
std::string get_cert_url(const std::string& iss, const DoutPrefixProvider *dpp,optional_yield y) const;
std::tuple<boost::optional<WebTokenEngine::token_t>, boost::optional<WebTokenEngine::principal_tags_t>>
get_from_jwt(const DoutPrefixProvider* dpp, const std::string& token, const req_state* const s, optional_yield y) const;
void validate_signature (const DoutPrefixProvider* dpp, const jwt::decoded_jwt& decoded, const std::string& algorithm, const std::string& iss, const std::vector<std::string>& thumbprints, optional_yield y) const;
result_t authenticate(const DoutPrefixProvider* dpp,
const std::string& token,
const req_state* s, optional_yield y) const;
template <typename T>
void recurse_and_insert(const string& key, const jwt::claim& c, T& t) const;
WebTokenEngine::token_t get_token_claims(const jwt::decoded_jwt& decoded) const;
public:
WebTokenEngine(CephContext* const cct,
rgw::sal::Driver* driver,
const rgw::auth::TokenExtractor* const extractor,
const rgw::auth::WebIdentityApplier::Factory* const apl_factory)
: cct(cct),
driver(driver),
extractor(extractor),
apl_factory(apl_factory) {
}
const char* get_name() const noexcept override {
return "rgw::auth::sts::WebTokenEngine";
}
result_t authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const override {
return authenticate(dpp, extractor->get_token(s), s, y);
}
}; /* class WebTokenEngine */
class DefaultStrategy : public rgw::auth::Strategy,
public rgw::auth::TokenExtractor,
public rgw::auth::WebIdentityApplier::Factory {
rgw::sal::Driver* driver;
const ImplicitTenants& implicit_tenant_context;
/* The engine. */
const WebTokenEngine web_token_engine;
using aplptr_t = rgw::auth::IdentityApplier::aplptr_t;
/* The method implements TokenExtractor for Web Token in req_state. */
std::string get_token(const req_state* const s) const override {
return s->info.args.get("WebIdentityToken");
}
aplptr_t create_apl_web_identity( CephContext* cct,
const req_state* s,
const std::string& role_session,
const std::string& role_tenant,
const std::unordered_multimap<std::string, std::string>& token,
boost::optional<std::multimap<std::string, std::string>> role_tags,
boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags) const override {
auto apl = rgw::auth::add_sysreq(cct, driver, s,
rgw::auth::WebIdentityApplier(cct, driver, role_session, role_tenant, token, role_tags, principal_tags));
return aplptr_t(new decltype(apl)(std::move(apl)));
}
public:
DefaultStrategy(CephContext* const cct,
const ImplicitTenants& implicit_tenant_context,
rgw::sal::Driver* driver)
: driver(driver),
implicit_tenant_context(implicit_tenant_context),
web_token_engine(cct, driver,
static_cast<rgw::auth::TokenExtractor*>(this),
static_cast<rgw::auth::WebIdentityApplier::Factory*>(this)) {
/* When the constructor's body is being executed, all member engines
* should be initialized. Thus, we can safely add them. */
using Control = rgw::auth::Strategy::Control;
add_engine(Control::SUFFICIENT, web_token_engine);
}
const char* get_name() const noexcept override {
return "rgw::auth::sts::DefaultStrategy";
}
};
} // namespace rgw::auth::sts
class RGWREST_STS : public RGWRESTOp {
protected:
STS::STSService sts;
public:
RGWREST_STS() = default;
int verify_permission(optional_yield y) override;
void send_response() override;
};
class RGWSTSAssumeRoleWithWebIdentity : public RGWREST_STS {
protected:
std::string duration;
std::string providerId;
std::string policy;
std::string roleArn;
std::string roleSessionName;
std::string sub;
std::string aud;
std::string iss;
public:
RGWSTSAssumeRoleWithWebIdentity() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "assume_role_web_identity"; }
RGWOpType get_type() override { return RGW_STS_ASSUME_ROLE_WEB_IDENTITY; }
};
class RGWSTSAssumeRole : public RGWREST_STS {
protected:
std::string duration;
std::string externalId;
std::string policy;
std::string roleArn;
std::string roleSessionName;
std::string serialNumber;
std::string tokenCode;
public:
RGWSTSAssumeRole() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "assume_role"; }
RGWOpType get_type() override { return RGW_STS_ASSUME_ROLE; }
};
class RGWSTSGetSessionToken : public RGWREST_STS {
protected:
std::string duration;
std::string serialNumber;
std::string tokenCode;
public:
RGWSTSGetSessionToken() = default;
void execute(optional_yield y) override;
int verify_permission(optional_yield y) override;
int get_params();
const char* name() const override { return "get_session_token"; }
RGWOpType get_type() override { return RGW_STS_GET_SESSION_TOKEN; }
};
class RGW_Auth_STS {
public:
static int authorize(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw::auth::StrategyRegistry& auth_registry,
req_state *s, optional_yield y);
};
class RGWHandler_REST_STS : public RGWHandler_REST {
const rgw::auth::StrategyRegistry& auth_registry;
RGWOp *op_post() override;
public:
static bool action_exists(const req_state* s);
RGWHandler_REST_STS(const rgw::auth::StrategyRegistry& auth_registry)
: RGWHandler_REST(),
auth_registry(auth_registry) {}
~RGWHandler_REST_STS() override = default;
int init(rgw::sal::Driver* driver,
req_state *s,
rgw::io::BasicClient *cio) override;
int authorize(const DoutPrefixProvider* dpp, optional_yield y) override;
int postauth_init(optional_yield y) override { return 0; }
};
class RGWRESTMgr_STS : public RGWRESTMgr {
public:
RGWRESTMgr_STS() = default;
~RGWRESTMgr_STS() override = default;
RGWRESTMgr *get_resource_mgr(req_state* const s,
const std::string& uri,
std::string* const out_uri) override {
return this;
}
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state*,
const rgw::auth::StrategyRegistry&,
const std::string&) override;
};
| 8,472 | 34.902542 | 214 |
h
|
null |
ceph-main/src/rgw/rgw_rest_swift.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <boost/algorithm/string/predicate.hpp>
#include <boost/format.hpp>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include "include/ceph_assert.h"
#include "ceph_ver.h"
#include "common/Formatter.h"
#include "common/utf8.h"
#include "common/ceph_json.h"
#include "rgw_rest_swift.h"
#include "rgw_acl_swift.h"
#include "rgw_cors_swift.h"
#include "rgw_formats.h"
#include "rgw_client_io.h"
#include "rgw_compression.h"
#include "rgw_auth.h"
#include "rgw_auth_registry.h"
#include "rgw_swift_auth.h"
#include "rgw_request.h"
#include "rgw_process.h"
#include "rgw_zone.h"
#include "rgw_sal.h"
#include "services/svc_zone.h"
#include <array>
#include <string_view>
#include <sstream>
#include <memory>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
int RGWListBuckets_ObjStore_SWIFT::get_params(optional_yield y)
{
prefix = s->info.args.get("prefix");
marker = s->info.args.get("marker");
end_marker = s->info.args.get("end_marker");
wants_reversed = s->info.args.exists("reverse");
if (wants_reversed) {
std::swap(marker, end_marker);
}
std::string limit_str = s->info.args.get("limit");
if (!limit_str.empty()) {
std::string err;
long l = strict_strtol(limit_str.c_str(), 10, &err);
if (!err.empty()) {
return -EINVAL;
}
if (l > (long)limit_max || l < 0) {
return -ERR_PRECONDITION_FAILED;
}
limit = (uint64_t)l;
}
if (s->cct->_conf->rgw_swift_need_stats) {
bool stats, exists;
int r = s->info.args.get_bool("stats", &stats, &exists);
if (r < 0) {
return r;
}
if (exists) {
need_stats = stats;
}
} else {
need_stats = false;
}
return 0;
}
static void dump_account_metadata(req_state * const s,
const RGWUsageStats& global_stats,
const std::map<std::string, RGWUsageStats> &policies_stats,
/* const */map<string, bufferlist>& attrs,
const RGWQuotaInfo& quota,
int32_t max_buckets,
const RGWAccessControlPolicy_SWIFTAcct &policy)
{
/* Adding X-Timestamp to keep align with Swift API */
dump_header(s, "X-Timestamp", ceph_clock_now());
dump_header(s, "X-Account-Container-Count", global_stats.buckets_count);
dump_header(s, "X-Account-Object-Count", global_stats.objects_count);
dump_header(s, "X-Account-Bytes-Used", global_stats.bytes_used);
dump_header(s, "X-Account-Bytes-Used-Actual", global_stats.bytes_used_rounded);
for (const auto& kv : policies_stats) {
const auto& policy_name = camelcase_dash_http_attr(kv.first);
const auto& policy_stats = kv.second;
dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
"-Container-Count", policy_stats.buckets_count);
dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
"-Object-Count", policy_stats.objects_count);
dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
"-Bytes-Used", policy_stats.bytes_used);
dump_header_infixed(s, "X-Account-Storage-Policy-", policy_name,
"-Bytes-Used-Actual", policy_stats.bytes_used_rounded);
}
/* Dump TempURL-related stuff */
if (s->perm_mask == RGW_PERM_FULL_CONTROL) {
auto iter = s->user->get_info().temp_url_keys.find(0);
if (iter != std::end(s->user->get_info().temp_url_keys) && ! iter->second.empty()) {
dump_header(s, "X-Account-Meta-Temp-Url-Key", iter->second);
}
iter = s->user->get_info().temp_url_keys.find(1);
if (iter != std::end(s->user->get_info().temp_url_keys) && ! iter->second.empty()) {
dump_header(s, "X-Account-Meta-Temp-Url-Key-2", iter->second);
}
}
/* Dump quota headers. */
if (quota.enabled) {
if (quota.max_size >= 0) {
dump_header(s, "X-Account-Meta-Quota-Bytes", quota.max_size);
}
/* Limit on the number of objects in a given account is a RadosGW's
* extension. Swift's account quota WSGI filter doesn't support it. */
if (quota.max_objects >= 0) {
dump_header(s, "X-Account-Meta-Quota-Count", quota.max_objects);
}
}
/* Limit on the number of containers in a given account is a RadosGW's
* extension. Swift's account quota WSGI filter doesn't support it. */
if (max_buckets >= 0) {
dump_header(s, "X-Account-Meta-Quota-Containers", max_buckets);
}
/* Dump user-defined metadata items and generic attrs. */
const size_t PREFIX_LEN = sizeof(RGW_ATTR_META_PREFIX) - 1;
map<string, bufferlist>::iterator iter;
for (iter = attrs.lower_bound(RGW_ATTR_PREFIX); iter != attrs.end(); ++iter) {
const char *name = iter->first.c_str();
map<string, string>::const_iterator geniter = rgw_to_http_attrs.find(name);
if (geniter != rgw_to_http_attrs.end()) {
dump_header(s, geniter->second, iter->second);
} else if (strncmp(name, RGW_ATTR_META_PREFIX, PREFIX_LEN) == 0) {
dump_header_prefixed(s, "X-Account-Meta-",
camelcase_dash_http_attr(name + PREFIX_LEN),
iter->second);
}
}
/* Dump account ACLs */
auto account_acls = policy.to_str();
if (account_acls) {
dump_header(s, "X-Account-Access-Control", std::move(*account_acls));
}
}
void RGWListBuckets_ObjStore_SWIFT::send_response_begin(bool has_buckets)
{
if (op_ret) {
set_req_state_err(s, op_ret);
} else if (!has_buckets && s->format == RGWFormat::PLAIN) {
op_ret = STATUS_NO_CONTENT;
set_req_state_err(s, op_ret);
}
if (! s->cct->_conf->rgw_swift_enforce_content_length) {
/* Adding account stats in the header to keep align with Swift API */
dump_account_metadata(s,
global_stats,
policies_stats,
s->user->get_attrs(),
s->user->get_info().quota.user_quota,
s->user->get_max_buckets(),
static_cast<RGWAccessControlPolicy_SWIFTAcct&>(*s->user_acl));
dump_errno(s);
dump_header(s, "Accept-Ranges", "bytes");
end_header(s, NULL, NULL, NO_CONTENT_LENGTH, true);
}
if (! op_ret) {
dump_start(s);
s->formatter->open_array_section_with_attrs("account",
FormatterAttrs("name", s->user->get_display_name().c_str(), NULL));
sent_data = true;
}
}
void RGWListBuckets_ObjStore_SWIFT::handle_listing_chunk(rgw::sal::BucketList&& buckets)
{
if (wants_reversed) {
/* Just store in the reversal buffer. Its content will be handled later,
* in send_response_end(). */
reverse_buffer.emplace(std::begin(reverse_buffer), std::move(buckets));
} else {
return send_response_data(buckets);
}
}
void RGWListBuckets_ObjStore_SWIFT::send_response_data(rgw::sal::BucketList& buckets)
{
if (! sent_data) {
return;
}
/* Take care of the prefix parameter of Swift API. There is no business
* in applying the filter earlier as we really need to go through all
* entries regardless of it (the headers like X-Account-Container-Count
* aren't affected by specifying prefix). */
const auto& m = buckets.get_buckets();
for (auto iter = m.lower_bound(prefix);
iter != m.end() && boost::algorithm::starts_with(iter->first, prefix);
++iter) {
dump_bucket_entry(*iter->second);
}
}
void RGWListBuckets_ObjStore_SWIFT::dump_bucket_entry(const rgw::sal::Bucket& bucket)
{
s->formatter->open_object_section("container");
s->formatter->dump_string("name", bucket.get_name());
if (need_stats) {
s->formatter->dump_int("count", bucket.get_count());
s->formatter->dump_int("bytes", bucket.get_size());
}
s->formatter->close_section();
if (! s->cct->_conf->rgw_swift_enforce_content_length) {
rgw_flush_formatter(s, s->formatter);
}
}
void RGWListBuckets_ObjStore_SWIFT::send_response_data_reversed(rgw::sal::BucketList& buckets)
{
if (! sent_data) {
return;
}
/* Take care of the prefix parameter of Swift API. There is no business
* in applying the filter earlier as we really need to go through all
* entries regardless of it (the headers like X-Account-Container-Count
* aren't affected by specifying prefix). */
auto& m = buckets.get_buckets();
auto iter = m.rbegin();
for (/* initialized above */;
iter != m.rend() && !boost::algorithm::starts_with(iter->first, prefix);
++iter) {
/* NOP */;
}
for (/* iter carried */;
iter != m.rend() && boost::algorithm::starts_with(iter->first, prefix);
++iter) {
dump_bucket_entry(*iter->second);
}
}
void RGWListBuckets_ObjStore_SWIFT::send_response_end()
{
if (wants_reversed) {
for (auto& buckets : reverse_buffer) {
send_response_data_reversed(buckets);
}
}
if (sent_data) {
s->formatter->close_section();
}
if (s->cct->_conf->rgw_swift_enforce_content_length) {
/* Adding account stats in the header to keep align with Swift API */
dump_account_metadata(s,
global_stats,
policies_stats,
s->user->get_attrs(),
s->user->get_info().quota.user_quota,
s->user->get_max_buckets(),
static_cast<RGWAccessControlPolicy_SWIFTAcct&>(*s->user_acl));
dump_errno(s);
end_header(s, nullptr, nullptr, s->formatter->get_len(), true);
}
if (sent_data || s->cct->_conf->rgw_swift_enforce_content_length) {
rgw_flush_formatter_and_reset(s, s->formatter);
}
}
int RGWListBucket_ObjStore_SWIFT::get_params(optional_yield y)
{
prefix = s->info.args.get("prefix");
marker = s->info.args.get("marker");
end_marker = s->info.args.get("end_marker");
max_keys = s->info.args.get("limit");
// non-standard
s->info.args.get_bool("allow_unordered", &allow_unordered, false);
delimiter = s->info.args.get("delimiter");
op_ret = parse_max_keys();
if (op_ret < 0) {
return op_ret;
}
// S3 behavior is to silently cap the max-keys.
// Swift behavior is to abort.
if (max > default_max)
return -ERR_PRECONDITION_FAILED;
string path_args;
if (s->info.args.exists("path")) { // should handle empty path
path_args = s->info.args.get("path");
if (!delimiter.empty() || !prefix.empty()) {
return -EINVAL;
}
prefix = path_args;
delimiter="/";
path = prefix;
if (path.size() && path[path.size() - 1] != '/')
path.append("/");
int len = prefix.size();
int delim_size = delimiter.size();
if (len >= delim_size) {
if (prefix.substr(len - delim_size).compare(delimiter) != 0)
prefix.append(delimiter);
}
}
return 0;
}
static void dump_container_metadata(req_state *,
const rgw::sal::Bucket*,
const RGWQuotaInfo&,
const RGWBucketWebsiteConf&);
void RGWListBucket_ObjStore_SWIFT::send_response()
{
vector<rgw_bucket_dir_entry>::iterator iter = objs.begin();
map<string, bool>::iterator pref_iter = common_prefixes.begin();
dump_start(s);
dump_container_metadata(s, s->bucket.get(), quota.bucket_quota,
s->bucket->get_info().website_conf);
s->formatter->open_array_section_with_attrs("container",
FormatterAttrs("name",
s->bucket->get_name().c_str(),
NULL));
while (iter != objs.end() || pref_iter != common_prefixes.end()) {
bool do_pref = false;
bool do_objs = false;
rgw_obj_key key;
if (iter != objs.end()) {
key = iter->key;
}
if (pref_iter == common_prefixes.end())
do_objs = true;
else if (iter == objs.end())
do_pref = true;
else if (!key.empty() && key.name.compare(pref_iter->first) == 0) {
do_objs = true;
++pref_iter;
} else if (!key.empty() && key.name.compare(pref_iter->first) <= 0)
do_objs = true;
else
do_pref = true;
if (do_objs && (allow_unordered || marker.empty() || marker < key)) {
if (key.name.compare(path) == 0)
goto next;
s->formatter->open_object_section("object");
s->formatter->dump_string("name", key.name);
s->formatter->dump_string("hash", iter->meta.etag);
s->formatter->dump_int("bytes", iter->meta.accounted_size);
if (!iter->meta.user_data.empty())
s->formatter->dump_string("user_custom_data", iter->meta.user_data);
string single_content_type = iter->meta.content_type;
if (iter->meta.content_type.size()) {
// content type might hold multiple values, just dump the last one
ssize_t pos = iter->meta.content_type.rfind(',');
if (pos > 0) {
++pos;
while (single_content_type[pos] == ' ')
++pos;
single_content_type = single_content_type.substr(pos);
}
s->formatter->dump_string("content_type", single_content_type);
}
dump_time(s, "last_modified", iter->meta.mtime);
s->formatter->close_section();
}
if (do_pref && (marker.empty() || pref_iter->first.compare(marker.name) > 0)) {
const string& name = pref_iter->first;
if (name.compare(delimiter) == 0)
goto next;
s->formatter->open_object_section_with_attrs("subdir", FormatterAttrs("name", name.c_str(), NULL));
/* swift is a bit inconsistent here */
switch (s->format) {
case RGWFormat::XML:
s->formatter->dump_string("name", name);
break;
default:
s->formatter->dump_string("subdir", name);
}
s->formatter->close_section();
}
next:
if (do_objs)
++iter;
else
++pref_iter;
}
s->formatter->close_section();
int64_t content_len = 0;
if (! op_ret) {
content_len = s->formatter->get_len();
if (content_len == 0) {
op_ret = STATUS_NO_CONTENT;
}
} else if (op_ret > 0) {
op_ret = 0;
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, NULL, content_len);
if (op_ret < 0) {
return;
}
rgw_flush_formatter_and_reset(s, s->formatter);
} // RGWListBucket_ObjStore_SWIFT::send_response
static void dump_container_metadata(req_state *s,
const rgw::sal::Bucket* bucket,
const RGWQuotaInfo& quota,
const RGWBucketWebsiteConf& ws_conf)
{
/* Adding X-Timestamp to keep align with Swift API */
dump_header(s, "X-Timestamp", utime_t(s->bucket->get_info().creation_time));
dump_header(s, "X-Container-Object-Count", bucket->get_count());
dump_header(s, "X-Container-Bytes-Used", bucket->get_size());
dump_header(s, "X-Container-Bytes-Used-Actual", bucket->get_size_rounded());
if (rgw::sal::Object::empty(s->object.get())) {
auto swift_policy = \
static_cast<RGWAccessControlPolicy_SWIFT*>(s->bucket_acl.get());
std::string read_acl, write_acl;
swift_policy->to_str(read_acl, write_acl);
if (read_acl.size()) {
dump_header(s, "X-Container-Read", read_acl);
}
if (write_acl.size()) {
dump_header(s, "X-Container-Write", write_acl);
}
if (!s->bucket->get_placement_rule().name.empty()) {
dump_header(s, "X-Storage-Policy", s->bucket->get_placement_rule().name);
}
dump_header(s, "X-Storage-Class", s->bucket->get_placement_rule().get_storage_class());
/* Dump user-defined metadata items and generic attrs. */
const size_t PREFIX_LEN = sizeof(RGW_ATTR_META_PREFIX) - 1;
map<string, bufferlist>::iterator iter;
for (iter = s->bucket_attrs.lower_bound(RGW_ATTR_PREFIX);
iter != s->bucket_attrs.end();
++iter) {
const char *name = iter->first.c_str();
map<string, string>::const_iterator geniter = rgw_to_http_attrs.find(name);
if (geniter != rgw_to_http_attrs.end()) {
dump_header(s, geniter->second, iter->second);
} else if (strncmp(name, RGW_ATTR_META_PREFIX, PREFIX_LEN) == 0) {
dump_header_prefixed(s, "X-Container-Meta-",
camelcase_dash_http_attr(name + PREFIX_LEN),
iter->second);
}
}
}
/* Dump container versioning info. */
if (! s->bucket->get_info().swift_ver_location.empty()) {
dump_header(s, "X-Versions-Location",
url_encode(s->bucket->get_info().swift_ver_location));
}
/* Dump quota headers. */
if (quota.enabled) {
if (quota.max_size >= 0) {
dump_header(s, "X-Container-Meta-Quota-Bytes", quota.max_size);
}
if (quota.max_objects >= 0) {
dump_header(s, "X-Container-Meta-Quota-Count", quota.max_objects);
}
}
/* Dump Static Website headers. */
if (! ws_conf.index_doc_suffix.empty()) {
dump_header(s, "X-Container-Meta-Web-Index", ws_conf.index_doc_suffix);
}
if (! ws_conf.error_doc.empty()) {
dump_header(s, "X-Container-Meta-Web-Error", ws_conf.error_doc);
}
if (! ws_conf.subdir_marker.empty()) {
dump_header(s, "X-Container-Meta-Web-Directory-Type",
ws_conf.subdir_marker);
}
if (! ws_conf.listing_css_doc.empty()) {
dump_header(s, "X-Container-Meta-Web-Listings-CSS",
ws_conf.listing_css_doc);
}
if (ws_conf.listing_enabled) {
dump_header(s, "X-Container-Meta-Web-Listings", "true");
}
/* Dump bucket's modification time. Compliance with the Swift API really
* needs that. */
dump_last_modified(s, s->bucket_mtime);
}
void RGWStatAccount_ObjStore_SWIFT::execute(optional_yield y)
{
RGWStatAccount_ObjStore::execute(y);
op_ret = s->user->read_attrs(s, s->yield);
attrs = s->user->get_attrs();
}
void RGWStatAccount_ObjStore_SWIFT::send_response()
{
if (op_ret >= 0) {
op_ret = STATUS_NO_CONTENT;
dump_account_metadata(s,
global_stats,
policies_stats,
attrs,
s->user->get_info().quota.user_quota,
s->user->get_max_buckets(),
static_cast<RGWAccessControlPolicy_SWIFTAcct&>(*s->user_acl));
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, NULL, NULL, 0, true);
dump_start(s);
}
void RGWStatBucket_ObjStore_SWIFT::send_response()
{
if (op_ret >= 0) {
op_ret = STATUS_NO_CONTENT;
dump_container_metadata(s, bucket.get(), quota.bucket_quota,
s->bucket->get_info().website_conf);
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, NULL, 0, true);
dump_start(s);
}
static int get_swift_container_settings(req_state * const s,
rgw::sal::Driver* const driver,
RGWAccessControlPolicy * const policy,
bool * const has_policy,
uint32_t * rw_mask,
RGWCORSConfiguration * const cors_config,
bool * const has_cors)
{
const char * const read_list = s->info.env->get("HTTP_X_CONTAINER_READ");
const char * const write_list = s->info.env->get("HTTP_X_CONTAINER_WRITE");
*has_policy = false;
if (read_list || write_list) {
RGWAccessControlPolicy_SWIFT swift_policy(s->cct);
const auto r = swift_policy.create(s, driver,
s->user->get_id(),
s->user->get_display_name(),
read_list,
write_list,
*rw_mask);
if (r < 0) {
return r;
}
*policy = swift_policy;
*has_policy = true;
}
*has_cors = false;
/*Check and update CORS configuration*/
const char *allow_origins = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_ALLOW_ORIGIN");
const char *allow_headers = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_ALLOW_HEADERS");
const char *expose_headers = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_EXPOSE_HEADERS");
const char *max_age = s->info.env->get("HTTP_X_CONTAINER_META_ACCESS_CONTROL_MAX_AGE");
if (allow_origins) {
RGWCORSConfiguration_SWIFT *swift_cors = new RGWCORSConfiguration_SWIFT;
int r = swift_cors->create_update(allow_origins, allow_headers, expose_headers, max_age);
if (r < 0) {
ldpp_dout(s, 0) << "Error creating/updating the cors configuration" << dendl;
delete swift_cors;
return r;
}
*has_cors = true;
*cors_config = *swift_cors;
cors_config->dump();
delete swift_cors;
}
return 0;
}
#define ACCT_REMOVE_ATTR_PREFIX "HTTP_X_REMOVE_ACCOUNT_META_"
#define ACCT_PUT_ATTR_PREFIX "HTTP_X_ACCOUNT_META_"
#define CONT_REMOVE_ATTR_PREFIX "HTTP_X_REMOVE_CONTAINER_META_"
#define CONT_PUT_ATTR_PREFIX "HTTP_X_CONTAINER_META_"
static void get_rmattrs_from_headers(const req_state * const s,
const char * const put_prefix,
const char * const del_prefix,
set<string>& rmattr_names)
{
const size_t put_prefix_len = strlen(put_prefix);
const size_t del_prefix_len = strlen(del_prefix);
for (const auto& kv : s->info.env->get_map()) {
size_t prefix_len = 0;
const char * const p = kv.first.c_str();
if (strncasecmp(p, del_prefix, del_prefix_len) == 0) {
/* Explicitly requested removal. */
prefix_len = del_prefix_len;
} else if ((strncasecmp(p, put_prefix, put_prefix_len) == 0)
&& kv.second.empty()) {
/* Removal requested by putting an empty value. */
prefix_len = put_prefix_len;
}
if (prefix_len > 0) {
string name(RGW_ATTR_META_PREFIX);
name.append(lowercase_dash_http_attr(p + prefix_len));
rmattr_names.insert(name);
}
}
}
static int get_swift_versioning_settings(
req_state * const s,
boost::optional<std::string>& swift_ver_location)
{
/* Removing the Swift's versions location has lower priority than setting
* a new one. That's the reason why we're handling it first. */
const std::string vlocdel =
s->info.env->get("HTTP_X_REMOVE_VERSIONS_LOCATION", "");
if (vlocdel.size()) {
swift_ver_location = boost::in_place(std::string());
}
if (s->info.env->exists("HTTP_X_VERSIONS_LOCATION")) {
/* If the Swift's versioning is globally disabled but someone wants to
* enable it for a given container, new version of Swift will generate
* the precondition failed error. */
if (! s->cct->_conf->rgw_swift_versioning_enabled) {
return -ERR_PRECONDITION_FAILED;
}
swift_ver_location = s->info.env->get("HTTP_X_VERSIONS_LOCATION", "");
}
return 0;
}
int RGWCreateBucket_ObjStore_SWIFT::get_params(optional_yield y)
{
bool has_policy;
uint32_t policy_rw_mask = 0;
int r = get_swift_container_settings(s, driver, &policy, &has_policy,
&policy_rw_mask, &cors_config, &has_cors);
if (r < 0) {
return r;
}
if (!has_policy) {
policy.create_default(s->user->get_id(), s->user->get_display_name());
}
location_constraint = driver->get_zone()->get_zonegroup().get_api_name();
get_rmattrs_from_headers(s, CONT_PUT_ATTR_PREFIX,
CONT_REMOVE_ATTR_PREFIX, rmattr_names);
placement_rule.init(s->info.env->get("HTTP_X_STORAGE_POLICY", ""), s->info.storage_class);
return get_swift_versioning_settings(s, swift_ver_location);
}
static inline int handle_metadata_errors(req_state* const s, const int op_ret)
{
if (op_ret == -EFBIG) {
/* Handle the custom error message of exceeding maximum custom attribute
* (stored as xattr) size. */
const auto error_message = boost::str(
boost::format("Metadata value longer than %lld")
% s->cct->_conf.get_val<Option::size_t>("rgw_max_attr_size"));
set_req_state_err(s, EINVAL, error_message);
return -EINVAL;
} else if (op_ret == -E2BIG) {
const auto error_message = boost::str(
boost::format("Too many metadata items; max %lld")
% s->cct->_conf.get_val<uint64_t>("rgw_max_attrs_num_in_req"));
set_req_state_err(s, EINVAL, error_message);
return -EINVAL;
}
return op_ret;
}
void RGWCreateBucket_ObjStore_SWIFT::send_response()
{
const auto meta_ret = handle_metadata_errors(s, op_ret);
if (meta_ret != op_ret) {
op_ret = meta_ret;
} else {
if (!op_ret) {
op_ret = STATUS_CREATED;
} else if (op_ret == -ERR_BUCKET_EXISTS) {
op_ret = STATUS_ACCEPTED;
}
set_req_state_err(s, op_ret);
}
dump_errno(s);
/* Propose ending HTTP header with 0 Content-Length header. */
end_header(s, NULL, NULL, 0);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWDeleteBucket_ObjStore_SWIFT::send_response()
{
int r = op_ret;
if (!r)
r = STATUS_NO_CONTENT;
set_req_state_err(s, r);
dump_errno(s);
end_header(s, this, NULL, 0);
rgw_flush_formatter_and_reset(s, s->formatter);
}
static int get_delete_at_param(req_state *s, boost::optional<real_time> &delete_at)
{
/* Handle Swift object expiration. */
real_time delat_proposal;
string x_delete = s->info.env->get("HTTP_X_DELETE_AFTER", "");
if (x_delete.empty()) {
x_delete = s->info.env->get("HTTP_X_DELETE_AT", "");
} else {
/* X-Delete-After HTTP is present. It means we need add its value
* to the current time. */
delat_proposal = real_clock::now();
}
if (x_delete.empty()) {
delete_at = boost::none;
if (s->info.env->exists("HTTP_X_REMOVE_DELETE_AT")) {
delete_at = boost::in_place(real_time());
}
return 0;
}
string err;
long ts = strict_strtoll(x_delete.c_str(), 10, &err);
if (!err.empty()) {
return -EINVAL;
}
delat_proposal += make_timespan(ts);
if (delat_proposal < real_clock::now()) {
return -EINVAL;
}
delete_at = delat_proposal;
return 0;
}
int RGWPutObj_ObjStore_SWIFT::verify_permission(optional_yield y)
{
op_ret = RGWPutObj_ObjStore::verify_permission(y);
/* We have to differentiate error codes depending on whether user is
* anonymous (401 Unauthorized) or he doesn't have necessary permissions
* (403 Forbidden). */
if (s->auth.identity->is_anonymous() && op_ret == -EACCES) {
return -EPERM;
} else {
return op_ret;
}
}
int RGWPutObj_ObjStore_SWIFT::update_slo_segment_size(rgw_slo_entry& entry) {
int r = 0;
const string& path = entry.path;
/* If the path starts with slashes, strip them all. */
const size_t pos_init = path.find_first_not_of('/');
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);
std::unique_ptr<rgw::sal::Bucket> bucket;
if (bucket_name.compare(s->bucket->get_name()) != 0) {
r = driver->get_bucket(s, s->user.get(), s->user->get_id().tenant, bucket_name, &bucket, s->yield);
if (r < 0) {
ldpp_dout(this, 0) << "could not get bucket info for bucket="
<< bucket_name << dendl;
return r;
}
} else {
bucket = s->bucket->clone();
}
/* fetch the stored size of the seg (or error if not valid) */
std::unique_ptr<rgw::sal::Object> slo_seg = bucket->get_object(rgw_obj_key(obj_name));
/* no prefetch */
slo_seg->set_atomic();
bool compressed;
RGWCompressionInfo cs_info;
uint64_t size_bytes{0};
r = slo_seg->get_obj_attrs(s->yield, s);
if (r < 0) {
return r;
}
size_bytes = slo_seg->get_obj_size();
r = rgw_compression_info_from_attrset(slo_seg->get_attrs(), compressed, cs_info);
if (r < 0) {
return -EIO;
}
if (compressed) {
size_bytes = cs_info.orig_size;
}
/* "When the PUT operation sees the multipart-manifest=put query
* parameter, it reads the request body and verifies that each
* segment object exists and that the sizes and ETags match. If
* there is a mismatch, the PUT operation fails."
*/
if (entry.size_bytes &&
(entry.size_bytes != size_bytes)) {
return -EINVAL;
}
entry.size_bytes = size_bytes;
return 0;
} /* RGWPutObj_ObjStore_SWIFT::update_slo_segment_sizes */
int RGWPutObj_ObjStore_SWIFT::get_params(optional_yield y)
{
if (s->has_bad_meta) {
return -EINVAL;
}
if (!s->length) {
const char *encoding = s->info.env->get("HTTP_TRANSFER_ENCODING");
if (!encoding || strcmp(encoding, "chunked") != 0) {
ldpp_dout(this, 20) << "neither length nor chunked encoding" << dendl;
return -ERR_LENGTH_REQUIRED;
}
chunked_upload = true;
}
supplied_etag = s->info.env->get("HTTP_ETAG");
if (!s->generic_attrs.count(RGW_ATTR_CONTENT_TYPE)) {
ldpp_dout(this, 5) << "content type wasn't provided, trying to guess" << dendl;
const char *suffix = strrchr(s->object->get_name().c_str(), '.');
if (suffix) {
suffix++;
if (*suffix) {
string suffix_str(suffix);
const char *mime = rgw_find_mime_by_ext(suffix_str);
if (mime) {
s->generic_attrs[RGW_ATTR_CONTENT_TYPE] = mime;
}
}
}
}
policy.create_default(s->user->get_id(), s->user->get_display_name());
int r = get_delete_at_param(s, delete_at);
if (r < 0) {
ldpp_dout(this, 5) << "ERROR: failed to get Delete-At param" << dendl;
return r;
}
if (!s->cct->_conf->rgw_swift_custom_header.empty()) {
string custom_header = s->cct->_conf->rgw_swift_custom_header;
auto data = s->info.env->get_optional(custom_header);
if (data) {
user_data = *data;
}
}
dlo_manifest = s->info.env->get("HTTP_X_OBJECT_MANIFEST");
bool exists;
string multipart_manifest = s->info.args.get("multipart-manifest", &exists);
if (exists) {
if (multipart_manifest != "put") {
ldpp_dout(this, 5) << "invalid multipart-manifest http param: " << multipart_manifest << dendl;
return -EINVAL;
}
#define MAX_SLO_ENTRY_SIZE (1024 + 128) // 1024 - max obj name, 128 - enough extra for other info
uint64_t max_len = s->cct->_conf->rgw_max_slo_entries * MAX_SLO_ENTRY_SIZE;
slo_info = new RGWSLOInfo;
int r = 0;
std::tie(r, slo_info->raw_data) = rgw_rest_get_json_input_keep_data(s->cct, s, slo_info->entries, max_len);
if (r < 0) {
ldpp_dout(this, 5) << "failed to read input for slo r=" << r << dendl;
return r;
}
if ((int64_t)slo_info->entries.size() > s->cct->_conf->rgw_max_slo_entries) {
ldpp_dout(this, 5) << "too many entries in slo request: " << slo_info->entries.size() << dendl;
return -EINVAL;
}
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);
uint64_t total_size = 0;
for (auto& entry : slo_info->entries) {
etag_sum.Update((const unsigned char *)entry.etag.c_str(),
entry.etag.length());
/* if size_bytes == 0, it should be replaced with the
* real segment size (which could be 0); this follows from the
* fact that Swift requires all segments to exist, but permits
* the size_bytes element to be omitted from the SLO manifest, see
* https://docs.openstack.org/swift/latest/api/large_objects.html
*/
r = update_slo_segment_size(entry);
if (r < 0) {
return r;
}
total_size += entry.size_bytes;
ldpp_dout(this, 20) << "slo_part: " << entry.path
<< " size=" << entry.size_bytes
<< " etag=" << entry.etag
<< dendl;
}
complete_etag(etag_sum, &lo_etag);
slo_info->total_size = total_size;
ofs = slo_info->raw_data.length();
}
return RGWPutObj_ObjStore::get_params(y);
}
void RGWPutObj_ObjStore_SWIFT::send_response()
{
const auto meta_ret = handle_metadata_errors(s, op_ret);
if (meta_ret) {
op_ret = meta_ret;
} else {
if (!op_ret) {
op_ret = STATUS_CREATED;
}
set_req_state_err(s, op_ret);
}
if (! lo_etag.empty()) {
/* Static Large Object of Swift API has two etags represented by
* following members:
* - etag - for the manifest itself (it will be stored in xattrs),
* - lo_etag - for the content composited from SLO's segments.
* The value is calculated basing on segments' etags.
* In response for PUT request we have to expose the second one.
* The first one may be obtained by GET with "multipart-manifest=get"
* in query string on a given SLO. */
dump_etag(s, lo_etag, true /* quoted */);
} else {
dump_etag(s, etag);
}
dump_last_modified(s, mtime);
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this);
rgw_flush_formatter_and_reset(s, s->formatter);
}
static int get_swift_account_settings(req_state * const s,
rgw::sal::Driver* const driver,
RGWAccessControlPolicy_SWIFTAcct* const policy,
bool * const has_policy)
{
*has_policy = false;
const char * const acl_attr = s->info.env->get("HTTP_X_ACCOUNT_ACCESS_CONTROL");
if (acl_attr) {
RGWAccessControlPolicy_SWIFTAcct swift_acct_policy(s->cct);
const bool r = swift_acct_policy.create(s, driver,
s->user->get_id(),
s->user->get_display_name(),
string(acl_attr));
if (r != true) {
return -EINVAL;
}
*policy = swift_acct_policy;
*has_policy = true;
}
return 0;
}
int RGWPutMetadataAccount_ObjStore_SWIFT::get_params(optional_yield y)
{
if (s->has_bad_meta) {
return -EINVAL;
}
int ret = get_swift_account_settings(s,
driver,
// FIXME: we need to carry unique_ptr in generic class
// and allocate appropriate ACL class in the ctor
static_cast<RGWAccessControlPolicy_SWIFTAcct *>(&policy),
&has_policy);
if (ret < 0) {
return ret;
}
get_rmattrs_from_headers(s, ACCT_PUT_ATTR_PREFIX, ACCT_REMOVE_ATTR_PREFIX,
rmattr_names);
return 0;
}
void RGWPutMetadataAccount_ObjStore_SWIFT::send_response()
{
const auto meta_ret = handle_metadata_errors(s, op_ret);
if (meta_ret != op_ret) {
op_ret = meta_ret;
} else {
if (!op_ret) {
op_ret = STATUS_NO_CONTENT;
}
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this);
rgw_flush_formatter_and_reset(s, s->formatter);
}
int RGWPutMetadataBucket_ObjStore_SWIFT::get_params(optional_yield y)
{
if (s->has_bad_meta) {
return -EINVAL;
}
int r = get_swift_container_settings(s, driver, &policy, &has_policy,
&policy_rw_mask, &cors_config, &has_cors);
if (r < 0) {
return r;
}
get_rmattrs_from_headers(s, CONT_PUT_ATTR_PREFIX, CONT_REMOVE_ATTR_PREFIX,
rmattr_names);
placement_rule.init(s->info.env->get("HTTP_X_STORAGE_POLICY", ""), s->info.storage_class);
return get_swift_versioning_settings(s, swift_ver_location);
}
void RGWPutMetadataBucket_ObjStore_SWIFT::send_response()
{
const auto meta_ret = handle_metadata_errors(s, op_ret);
if (meta_ret != op_ret) {
op_ret = meta_ret;
} else {
if (!op_ret && (op_ret != -EINVAL)) {
op_ret = STATUS_NO_CONTENT;
}
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this);
rgw_flush_formatter_and_reset(s, s->formatter);
}
int RGWPutMetadataObject_ObjStore_SWIFT::get_params(optional_yield y)
{
if (s->has_bad_meta) {
return -EINVAL;
}
/* Handle Swift object expiration. */
int r = get_delete_at_param(s, delete_at);
if (r < 0) {
ldpp_dout(this, 5) << "ERROR: failed to get Delete-At param" << dendl;
return r;
}
dlo_manifest = s->info.env->get("HTTP_X_OBJECT_MANIFEST");
return 0;
}
void RGWPutMetadataObject_ObjStore_SWIFT::send_response()
{
const auto meta_ret = handle_metadata_errors(s, op_ret);
if (meta_ret != op_ret) {
op_ret = meta_ret;
} else {
if (!op_ret) {
op_ret = STATUS_ACCEPTED;
}
set_req_state_err(s, op_ret);
}
if (!s->is_err()) {
dump_content_length(s, 0);
}
dump_errno(s);
end_header(s, this);
rgw_flush_formatter_and_reset(s, s->formatter);
}
static void bulkdelete_respond(const unsigned num_deleted,
const unsigned int num_unfound,
const std::list<RGWBulkDelete::fail_desc_t>& failures,
const int prot_flags, /* in */
ceph::Formatter& formatter) /* out */
{
formatter.open_object_section("delete");
string resp_status;
string resp_body;
if (!failures.empty()) {
int reason = ERR_INVALID_REQUEST;
for (const auto& fail_desc : failures) {
if (-ENOENT != fail_desc.err && -EACCES != fail_desc.err) {
reason = fail_desc.err;
}
}
rgw_err err;
set_req_state_err(err, reason, prot_flags);
dump_errno(err, resp_status);
} else if (0 == num_deleted && 0 == num_unfound) {
/* 400 Bad Request */
dump_errno(400, resp_status);
resp_body = "Invalid bulk delete.";
} else {
/* 200 OK */
dump_errno(200, resp_status);
}
encode_json("Number Deleted", num_deleted, &formatter);
encode_json("Number Not Found", num_unfound, &formatter);
encode_json("Response Body", resp_body, &formatter);
encode_json("Response Status", resp_status, &formatter);
formatter.open_array_section("Errors");
for (const auto& fail_desc : failures) {
formatter.open_array_section("object");
stringstream ss_name;
ss_name << fail_desc.path;
encode_json("Name", ss_name.str(), &formatter);
rgw_err err;
set_req_state_err(err, fail_desc.err, prot_flags);
string status;
dump_errno(err, status);
encode_json("Status", status, &formatter);
formatter.close_section();
}
formatter.close_section();
formatter.close_section();
}
int RGWDeleteObj_ObjStore_SWIFT::verify_permission(optional_yield y)
{
op_ret = RGWDeleteObj_ObjStore::verify_permission(y);
/* We have to differentiate error codes depending on whether user is
* anonymous (401 Unauthorized) or he doesn't have necessary permissions
* (403 Forbidden). */
if (s->auth.identity->is_anonymous() && op_ret == -EACCES) {
return -EPERM;
} else {
return op_ret;
}
}
int RGWDeleteObj_ObjStore_SWIFT::get_params(optional_yield y)
{
const string& mm = s->info.args.get("multipart-manifest");
multipart_delete = (mm.compare("delete") == 0);
return RGWDeleteObj_ObjStore::get_params(y);
}
void RGWDeleteObj_ObjStore_SWIFT::send_response()
{
int r = op_ret;
if (multipart_delete) {
r = 0;
} else if(!r) {
r = STATUS_NO_CONTENT;
}
set_req_state_err(s, r);
dump_errno(s);
if (multipart_delete) {
end_header(s, this /* RGWOp */, nullptr /* contype */,
CHUNKED_TRANSFER_ENCODING);
if (deleter) {
bulkdelete_respond(deleter->get_num_deleted(),
deleter->get_num_unfound(),
deleter->get_failures(),
s->prot_flags,
*s->formatter);
} else if (-ENOENT == op_ret) {
bulkdelete_respond(0, 1, {}, s->prot_flags, *s->formatter);
} else {
RGWBulkDelete::acct_path_t path;
path.bucket_name = s->bucket_name;
path.obj_key = s->object->get_key();
RGWBulkDelete::fail_desc_t fail_desc;
fail_desc.err = op_ret;
fail_desc.path = path;
bulkdelete_respond(0, 0, { fail_desc }, s->prot_flags, *s->formatter);
}
} else {
end_header(s, this);
}
rgw_flush_formatter_and_reset(s, s->formatter);
}
static void get_contype_from_attrs(map<string, bufferlist>& attrs,
string& content_type)
{
map<string, bufferlist>::iterator iter = attrs.find(RGW_ATTR_CONTENT_TYPE);
if (iter != attrs.end()) {
content_type = rgw_bl_str(iter->second);
}
}
static void dump_object_metadata(const DoutPrefixProvider* dpp, req_state * const s,
const map<string, bufferlist>& attrs)
{
map<string, string> response_attrs;
for (auto kv : attrs) {
const char * name = kv.first.c_str();
const auto aiter = rgw_to_http_attrs.find(name);
if (aiter != std::end(rgw_to_http_attrs)) {
response_attrs[aiter->second] = rgw_bl_str(kv.second);
} else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {
// this attr has an extra length prefix from encode() in prior versions
dump_header(s, "X-Object-Meta-Static-Large-Object", "True");
} else if (strncmp(name, RGW_ATTR_META_PREFIX,
sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {
name += sizeof(RGW_ATTR_META_PREFIX) - 1;
dump_header_prefixed(s, "X-Object-Meta-",
camelcase_dash_http_attr(name), kv.second);
}
}
/* Handle override and fallback for Content-Disposition HTTP header.
* At the moment this will be used only by TempURL of the Swift API. */
const auto cditer = rgw_to_http_attrs.find(RGW_ATTR_CONTENT_DISP);
if (cditer != std::end(rgw_to_http_attrs)) {
const auto& name = cditer->second;
if (!s->content_disp.override.empty()) {
response_attrs[name] = s->content_disp.override;
} else if (!s->content_disp.fallback.empty()
&& response_attrs.find(name) == std::end(response_attrs)) {
response_attrs[name] = s->content_disp.fallback;
}
}
for (const auto& kv : response_attrs) {
dump_header(s, kv.first, kv.second);
}
const auto iter = attrs.find(RGW_ATTR_DELETE_AT);
if (iter != std::end(attrs)) {
utime_t delete_at;
try {
decode(delete_at, iter->second);
if (!delete_at.is_zero()) {
dump_header(s, "X-Delete-At", delete_at.sec());
}
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: cannot decode object's " RGW_ATTR_DELETE_AT
" attr, ignoring"
<< dendl;
}
}
}
int RGWCopyObj_ObjStore_SWIFT::init_dest_policy()
{
dest_policy.create_default(s->user->get_id(), s->user->get_display_name());
return 0;
}
int RGWCopyObj_ObjStore_SWIFT::get_params(optional_yield y)
{
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_COPY_IF_MATCH");
if_nomatch = s->info.env->get("HTTP_COPY_IF_NONE_MATCH");
const char * const fresh_meta = s->info.env->get("HTTP_X_FRESH_METADATA");
if (fresh_meta && strcasecmp(fresh_meta, "TRUE") == 0) {
attrs_mod = rgw::sal::ATTRSMOD_REPLACE;
} else {
attrs_mod = rgw::sal::ATTRSMOD_MERGE;
}
int r = get_delete_at_param(s, delete_at);
if (r < 0) {
ldpp_dout(this, 5) << "ERROR: failed to get Delete-At param" << dendl;
return r;
}
return 0;
}
void RGWCopyObj_ObjStore_SWIFT::send_partial_response(off_t ofs)
{
if (! sent_header) {
if (! op_ret)
op_ret = STATUS_CREATED;
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this);
/* Send progress information. Note that this diverge from the original swift
* spec. We do this in order to keep connection alive.
*/
if (op_ret == 0) {
s->formatter->open_array_section("progress");
}
sent_header = true;
} else {
s->formatter->dump_int("ofs", (uint64_t)ofs);
}
rgw_flush_formatter(s, s->formatter);
}
void RGWCopyObj_ObjStore_SWIFT::dump_copy_info()
{
/* Dump X-Copied-From. */
dump_header(s, "X-Copied-From", url_encode(src_bucket->get_name()) +
"/" + url_encode(s->src_object->get_name()));
/* Dump X-Copied-From-Account. */
/* XXX tenant */
dump_header(s, "X-Copied-From-Account", url_encode(s->user->get_id().id));
/* Dump X-Copied-From-Last-Modified. */
dump_time_header(s, "X-Copied-From-Last-Modified", src_mtime);
}
void RGWCopyObj_ObjStore_SWIFT::send_response()
{
if (! sent_header) {
string content_type;
if (! op_ret)
op_ret = STATUS_CREATED;
set_req_state_err(s, op_ret);
dump_errno(s);
dump_etag(s, etag);
dump_last_modified(s, mtime);
dump_copy_info();
get_contype_from_attrs(attrs, content_type);
dump_object_metadata(this, s, attrs);
end_header(s, this, !content_type.empty() ? content_type.c_str()
: "binary/octet-stream");
} else {
s->formatter->close_section();
rgw_flush_formatter(s, s->formatter);
}
}
int RGWGetObj_ObjStore_SWIFT::verify_permission(optional_yield y)
{
op_ret = RGWGetObj_ObjStore::verify_permission(y);
/* We have to differentiate error codes depending on whether user is
* anonymous (401 Unauthorized) or he doesn't have necessary permissions
* (403 Forbidden). */
if (s->auth.identity->is_anonymous() && op_ret == -EACCES) {
return -EPERM;
} else {
return op_ret;
}
}
int RGWGetObj_ObjStore_SWIFT::get_params(optional_yield y)
{
const string& mm = s->info.args.get("multipart-manifest");
skip_manifest = (mm.compare("get") == 0);
return RGWGetObj_ObjStore::get_params(y);
}
int RGWGetObj_ObjStore_SWIFT::send_response_data_error(optional_yield y)
{
std::string error_content;
op_ret = error_handler(op_ret, &error_content, y);
if (! op_ret) {
/* The error handler has taken care of the error. */
return 0;
}
bufferlist error_bl;
error_bl.append(error_content);
return send_response_data(error_bl, 0, error_bl.length());
}
int RGWGetObj_ObjStore_SWIFT::send_response_data(bufferlist& bl,
const off_t bl_ofs,
const off_t bl_len)
{
string content_type;
if (sent_header) {
goto send_data;
}
if (custom_http_ret) {
set_req_state_err(s, 0);
dump_errno(s, custom_http_ret);
} else {
set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT
: op_ret);
dump_errno(s);
if (s->is_err()) {
end_header(s, NULL);
return 0;
}
}
if (range_str) {
dump_range(s, ofs, end, s->obj_size);
}
if (s->is_err()) {
end_header(s, NULL);
return 0;
}
dump_content_length(s, total_len);
dump_last_modified(s, lastmod);
dump_header(s, "X-Timestamp", utime_t(lastmod));
if (is_slo) {
dump_header(s, "X-Static-Large-Object", "True");
}
if (! op_ret) {
if (! lo_etag.empty()) {
dump_etag(s, lo_etag, true /* quoted */);
} else {
auto iter = attrs.find(RGW_ATTR_ETAG);
if (iter != attrs.end()) {
dump_etag(s, iter->second.to_str());
}
}
get_contype_from_attrs(attrs, content_type);
dump_object_metadata(this, s, attrs);
}
end_header(s, this, !content_type.empty() ? content_type.c_str()
: "binary/octet-stream");
sent_header = true;
send_data:
if (get_data && !op_ret) {
const auto r = dump_body(s, bl.c_str() + bl_ofs, bl_len);
if (r < 0) {
return r;
}
}
rgw_flush_formatter_and_reset(s, s->formatter);
return 0;
}
void RGWOptionsCORS_ObjStore_SWIFT::send_response()
{
string hdrs, exp_hdrs;
uint32_t max_age = CORS_MAX_AGE_INVALID;
/*EACCES means, there is no CORS registered yet for the bucket
*ENOENT means, there is no match of the Origin in the list of CORSRule
*/
if (op_ret == -ENOENT)
op_ret = -EACCES;
if (op_ret < 0) {
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, NULL);
return;
}
get_response_params(hdrs, exp_hdrs, &max_age);
dump_errno(s);
dump_access_control(s, origin, req_meth, hdrs.c_str(), exp_hdrs.c_str(),
max_age);
end_header(s, NULL);
}
int RGWBulkDelete_ObjStore_SWIFT::get_data(
list<RGWBulkDelete::acct_path_t>& items, bool * const is_truncated)
{
constexpr size_t MAX_LINE_SIZE = 2048;
RGWClientIOStreamBuf ciosb(static_cast<RGWRestfulIO&>(*(s->cio)),
size_t(s->cct->_conf->rgw_max_chunk_size));
istream cioin(&ciosb);
char buf[MAX_LINE_SIZE];
while (cioin.getline(buf, sizeof(buf))) {
string path_str(buf);
ldpp_dout(this, 20) << "extracted Bulk Delete entry: " << path_str << dendl;
RGWBulkDelete::acct_path_t path;
/* We need to skip all slashes at the beginning in order to preserve
* compliance with Swift. */
const size_t start_pos = path_str.find_first_not_of('/');
if (string::npos != start_pos) {
/* Seperator is the first slash after the leading ones. */
const size_t sep_pos = path_str.find('/', start_pos);
if (string::npos != sep_pos) {
path.bucket_name = url_decode(path_str.substr(start_pos,
sep_pos - start_pos));
path.obj_key = url_decode(path_str.substr(sep_pos + 1));
} else {
/* It's guaranteed here that bucket name is at least one character
* long and is different than slash. */
path.bucket_name = url_decode(path_str.substr(start_pos));
}
items.push_back(path);
}
if (items.size() == MAX_CHUNK_ENTRIES) {
*is_truncated = true;
return 0;
}
}
*is_truncated = false;
return 0;
}
void RGWBulkDelete_ObjStore_SWIFT::send_response()
{
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this /* RGWOp */, nullptr /* contype */,
CHUNKED_TRANSFER_ENCODING);
bulkdelete_respond(deleter->get_num_deleted(),
deleter->get_num_unfound(),
deleter->get_failures(),
s->prot_flags,
*s->formatter);
rgw_flush_formatter_and_reset(s, s->formatter);
}
std::unique_ptr<RGWBulkUploadOp::StreamGetter>
RGWBulkUploadOp_ObjStore_SWIFT::create_stream()
{
class SwiftStreamGetter : public StreamGetter {
const DoutPrefixProvider* dpp;
const size_t conlen;
size_t curpos;
req_state* const s;
public:
SwiftStreamGetter(const DoutPrefixProvider* dpp, req_state* const s, const size_t conlen)
: dpp(dpp),
conlen(conlen),
curpos(0),
s(s) {
}
ssize_t get_at_most(size_t want, ceph::bufferlist& dst) override {
/* maximum requested by a caller */
/* data provided by client */
/* RadosGW's limit. */
const size_t max_chunk_size = \
static_cast<size_t>(s->cct->_conf->rgw_max_chunk_size);
const size_t max_to_read = std::min({ want, conlen - curpos, max_chunk_size });
ldpp_dout(dpp, 20) << "bulk_upload: get_at_most max_to_read="
<< max_to_read
<< ", dst.c_str()=" << reinterpret_cast<intptr_t>(dst.c_str()) << dendl;
bufferptr bp(max_to_read);
const auto read_len = recv_body(s, bp.c_str(), max_to_read);
dst.append(bp, 0, read_len);
//const auto read_len = recv_body(s, dst.c_str(), max_to_read);
if (read_len < 0) {
return read_len;
}
curpos += read_len;
return curpos > s->cct->_conf->rgw_max_put_size ? -ERR_TOO_LARGE
: read_len;
}
ssize_t get_exactly(size_t want, ceph::bufferlist& dst) override {
ldpp_dout(dpp, 20) << "bulk_upload: get_exactly want=" << want << dendl;
/* FIXME: do this in a loop. */
const auto ret = get_at_most(want, dst);
ldpp_dout(dpp, 20) << "bulk_upload: get_exactly ret=" << ret << dendl;
if (ret < 0) {
return ret;
} else if (static_cast<size_t>(ret) != want) {
return -EINVAL;
} else {
return want;
}
}
};
if (! s->length) {
op_ret = -EINVAL;
return nullptr;
} else {
ldpp_dout(this, 20) << "bulk upload: create_stream for length="
<< s->length << dendl;
const size_t conlen = atoll(s->length);
return std::unique_ptr<SwiftStreamGetter>(new SwiftStreamGetter(this, s, conlen));
}
}
void RGWBulkUploadOp_ObjStore_SWIFT::send_response()
{
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this /* RGWOp */, nullptr /* contype */,
CHUNKED_TRANSFER_ENCODING);
rgw_flush_formatter_and_reset(s, s->formatter);
s->formatter->open_object_section("delete");
std::string resp_status;
std::string resp_body;
if (! failures.empty()) {
rgw_err err;
const auto last_err = { failures.back().err };
if (boost::algorithm::contains(last_err, terminal_errors)) {
/* The terminal errors are affecting the status of the whole upload. */
set_req_state_err(err, failures.back().err, s->prot_flags);
} else {
set_req_state_err(err, ERR_INVALID_REQUEST, s->prot_flags);
}
dump_errno(err, resp_status);
} else if (0 == num_created && failures.empty()) {
/* Nothing created, nothing failed. This means the archive contained no
* entity we could understand (regular file or directory). We need to
* send 400 Bad Request to an HTTP client in the internal status field. */
dump_errno(400, resp_status);
resp_body = "Invalid Tar File: No Valid Files";
} else {
/* 200 OK */
dump_errno(201, resp_status);
}
encode_json("Number Files Created", num_created, s->formatter);
encode_json("Response Body", resp_body, s->formatter);
encode_json("Response Status", resp_status, s->formatter);
s->formatter->open_array_section("Errors");
for (const auto& fail_desc : failures) {
s->formatter->open_array_section("object");
encode_json("Name", fail_desc.path, s->formatter);
rgw_err err;
set_req_state_err(err, fail_desc.err, s->prot_flags);
std::string status;
dump_errno(err, status);
encode_json("Status", status, s->formatter);
s->formatter->close_section();
}
s->formatter->close_section();
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWGetCrossDomainPolicy_ObjStore_SWIFT::send_response()
{
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, "application/xml");
std::stringstream ss;
ss << R"(<?xml version="1.0"?>)" << "\n"
<< R"(<!DOCTYPE cross-domain-policy SYSTEM )"
<< R"("http://www.adobe.com/xml/dtds/cross-domain-policy.dtd" >)" << "\n"
<< R"(<cross-domain-policy>)" << "\n"
<< g_conf()->rgw_cross_domain_policy << "\n"
<< R"(</cross-domain-policy>)";
dump_body(s, ss.str());
}
void RGWGetHealthCheck_ObjStore_SWIFT::send_response()
{
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this, "application/xml");
if (op_ret) {
static constexpr char DISABLED[] = "DISABLED BY FILE";
dump_body(s, DISABLED, strlen(DISABLED));
}
}
const vector<pair<string, RGWInfo_ObjStore_SWIFT::info>> RGWInfo_ObjStore_SWIFT::swift_info =
{
{"bulk_delete", {false, nullptr}},
{"container_quotas", {false, nullptr}},
{"swift", {false, RGWInfo_ObjStore_SWIFT::list_swift_data}},
{"tempurl", { false, RGWInfo_ObjStore_SWIFT::list_tempurl_data}},
{"slo", {false, RGWInfo_ObjStore_SWIFT::list_slo_data}},
{"account_quotas", {false, nullptr}},
{"staticweb", {false, nullptr}},
{"tempauth", {false, RGWInfo_ObjStore_SWIFT::list_tempauth_data}},
};
void RGWInfo_ObjStore_SWIFT::execute(optional_yield y)
{
bool is_admin_info_enabled = false;
const string& swiftinfo_sig = s->info.args.get("swiftinfo_sig");
const string& swiftinfo_expires = s->info.args.get("swiftinfo_expires");
if (!swiftinfo_sig.empty() &&
!swiftinfo_expires.empty() &&
!is_expired(swiftinfo_expires, this)) {
is_admin_info_enabled = true;
}
s->formatter->open_object_section("info");
for (const auto& pair : swift_info) {
if(!is_admin_info_enabled && pair.second.is_admin_info)
continue;
if (!pair.second.list_data) {
s->formatter->open_object_section((pair.first).c_str());
s->formatter->close_section();
}
else {
pair.second.list_data(*(s->formatter), s->cct->_conf, driver);
}
}
s->formatter->close_section();
}
void RGWInfo_ObjStore_SWIFT::send_response()
{
if (op_ret < 0) {
op_ret = STATUS_NO_CONTENT;
}
set_req_state_err(s, op_ret);
dump_errno(s);
end_header(s, this);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void RGWInfo_ObjStore_SWIFT::list_swift_data(Formatter& formatter,
const ConfigProxy& config,
rgw::sal::Driver* driver)
{
formatter.open_object_section("swift");
formatter.dump_int("max_file_size", config->rgw_max_put_size);
formatter.dump_int("container_listing_limit", RGW_LIST_BUCKETS_LIMIT_MAX);
string ceph_version(CEPH_GIT_NICE_VER);
formatter.dump_string("version", ceph_version);
const size_t max_attr_name_len = \
g_conf().get_val<Option::size_t>("rgw_max_attr_name_len");
if (max_attr_name_len) {
const size_t meta_name_limit = \
max_attr_name_len - strlen(RGW_ATTR_PREFIX RGW_AMZ_META_PREFIX);
formatter.dump_int("max_meta_name_length", meta_name_limit);
}
const size_t meta_value_limit = g_conf().get_val<Option::size_t>("rgw_max_attr_size");
if (meta_value_limit) {
formatter.dump_int("max_meta_value_length", meta_value_limit);
}
const size_t meta_num_limit = \
g_conf().get_val<uint64_t>("rgw_max_attrs_num_in_req");
if (meta_num_limit) {
formatter.dump_int("max_meta_count", meta_num_limit);
}
formatter.open_array_section("policies");
const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup();
std::set<std::string> targets;
if (zonegroup.get_placement_target_names(targets)) {
for (const auto& placement_targets : targets) {
formatter.open_object_section("policy");
if (placement_targets.compare(zonegroup.get_default_placement_name()) == 0)
formatter.dump_bool("default", true);
formatter.dump_string("name", placement_targets.c_str());
formatter.close_section();
}
}
formatter.close_section();
formatter.dump_int("max_object_name_size", RGWHandler_REST::MAX_OBJ_NAME_LEN);
formatter.dump_bool("strict_cors_mode", true);
formatter.dump_int("max_container_name_length", RGWHandler_REST::MAX_BUCKET_NAME_LEN);
formatter.close_section();
}
void RGWInfo_ObjStore_SWIFT::list_tempauth_data(Formatter& formatter,
const ConfigProxy& config,
rgw::sal::Driver* driver)
{
formatter.open_object_section("tempauth");
formatter.dump_bool("account_acls", true);
formatter.close_section();
}
void RGWInfo_ObjStore_SWIFT::list_tempurl_data(Formatter& formatter,
const ConfigProxy& config,
rgw::sal::Driver* driver)
{
formatter.open_object_section("tempurl");
formatter.open_array_section("methods");
formatter.dump_string("methodname", "GET");
formatter.dump_string("methodname", "HEAD");
formatter.dump_string("methodname", "PUT");
formatter.dump_string("methodname", "POST");
formatter.dump_string("methodname", "DELETE");
formatter.close_section();
formatter.close_section();
}
void RGWInfo_ObjStore_SWIFT::list_slo_data(Formatter& formatter,
const ConfigProxy& config,
rgw::sal::Driver* driver)
{
formatter.open_object_section("slo");
formatter.dump_int("max_manifest_segments", config->rgw_max_slo_entries);
formatter.close_section();
}
bool RGWInfo_ObjStore_SWIFT::is_expired(const std::string& expires, const DoutPrefixProvider *dpp)
{
string err;
const utime_t now = ceph_clock_now();
const uint64_t expiration = (uint64_t)strict_strtoll(expires.c_str(),
10, &err);
if (!err.empty()) {
ldpp_dout(dpp, 5) << "failed to parse siginfo_expires: " << err << dendl;
return true;
}
if (expiration <= (uint64_t)now.sec()) {
ldpp_dout(dpp, 5) << "siginfo expired: " << expiration << " <= " << now.sec() << dendl;
return true;
}
return false;
}
void RGWFormPost::init(rgw::sal::Driver* const driver,
req_state* const s,
RGWHandler* const dialect_handler)
{
if (!rgw::sal::Object::empty(s->object)) {
prefix = std::move(s->object->get_name());
s->object->set_key(rgw_obj_key());
}
return RGWPostObj_ObjStore::init(driver, s, dialect_handler);
}
std::size_t RGWFormPost::get_max_file_size() /*const*/
{
std::string max_str = get_part_str(ctrl_parts, "max_file_size", "0");
std::string err;
const std::size_t max_file_size =
static_cast<uint64_t>(strict_strtoll(max_str.c_str(), 10, &err));
if (! err.empty()) {
ldpp_dout(this, 5) << "failed to parse FormPost's max_file_size: " << err
<< dendl;
return 0;
}
return max_file_size;
}
bool RGWFormPost::is_non_expired()
{
std::string expires = get_part_str(ctrl_parts, "expires", "0");
std::string err;
const uint64_t expires_timestamp =
static_cast<uint64_t>(strict_strtoll(expires.c_str(), 10, &err));
if (! err.empty()) {
ldpp_dout(this, 5) << "failed to parse FormPost's expires: " << err << dendl;
return false;
}
const utime_t now = ceph_clock_now();
if (std::cmp_less_equal(expires_timestamp, now.sec())) {
ldpp_dout(this, 5) << "FormPost form expired: "
<< expires_timestamp << " <= " << now.sec() << dendl;
return false;
}
return true;
}
bool RGWFormPost::is_integral()
{
const std::string form_signature = get_part_str(ctrl_parts, "signature");
try {
get_owner_info(s, s->user->get_info());
s->auth.identity = rgw::auth::transform_old_authinfo(s);
} catch (...) {
ldpp_dout(this, 5) << "cannot get user_info of account's owner" << dendl;
return false;
}
for (const auto& kv : s->user->get_info().temp_url_keys) {
const int temp_url_key_num = kv.first;
const string& temp_url_key = kv.second;
if (temp_url_key.empty()) {
continue;
}
SignatureHelper sig_helper;
sig_helper.calc(temp_url_key,
s->info.request_uri,
get_part_str(ctrl_parts, "redirect"),
get_part_str(ctrl_parts, "max_file_size", "0"),
get_part_str(ctrl_parts, "max_file_count", "0"),
get_part_str(ctrl_parts, "expires", "0"));
const auto local_sig = sig_helper.get_signature();
ldpp_dout(this, 20) << "FormPost signature [" << temp_url_key_num << "]"
<< " (calculated): " << local_sig << dendl;
if (sig_helper.is_equal_to(form_signature)) {
return true;
} else {
ldpp_dout(this, 5) << "FormPost's signature mismatch: "
<< local_sig << " != " << form_signature << dendl;
}
}
return false;
}
void RGWFormPost::get_owner_info(const req_state* const s,
RGWUserInfo& owner_info) const
{
/* We cannot use req_state::bucket_name because it isn't available
* now. It will be initialized in RGWHandler_REST_SWIFT::postauth_init(). */
const string& bucket_name = s->init_state.url_bucket;
std::unique_ptr<rgw::sal::User> user;
/* TempURL in Formpost only requires that bucket name is specified. */
if (bucket_name.empty()) {
throw -EPERM;
}
if (!s->account_name.empty()) {
RGWUserInfo uinfo;
bool found = false;
const rgw_user uid(s->account_name);
if (uid.tenant.empty()) {
const rgw_user tenanted_uid(uid.id, uid.id);
user = driver->get_user(tenanted_uid);
if (user->load_user(s, s->yield) >= 0) {
/* Succeeded. */
found = true;
}
}
if (!found) {
user = driver->get_user(uid);
if (user->load_user(s, s->yield) < 0) {
throw -EPERM;
}
}
}
/* Need to get user info of bucket owner. */
std::unique_ptr<rgw::sal::Bucket> bucket;
int ret = driver->get_bucket(s, user.get(), user->get_tenant(), bucket_name, &bucket, s->yield);
if (ret < 0) {
throw ret;
}
ldpp_dout(this, 20) << "temp url user (bucket owner): " << bucket->get_info().owner
<< dendl;
user = driver->get_user(bucket->get_info().owner);
if (user->load_user(s, s->yield) < 0) {
throw -EPERM;
}
owner_info = user->get_info();
}
int RGWFormPost::get_params(optional_yield y)
{
/* The parentt class extracts boundary info from the Content-Type. */
int ret = RGWPostObj_ObjStore::get_params(y);
if (ret < 0) {
return ret;
}
policy.create_default(s->user->get_id(), s->user->get_display_name());
/* Let's start parsing the HTTP body by parsing each form part step-
* by-step till encountering the first part with file data. */
do {
struct post_form_part part;
ret = read_form_part_header(&part, stream_done);
if (ret < 0) {
return ret;
}
if (s->cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
ldpp_dout(this, 20) << "read part header -- part.name="
<< part.name << dendl;
for (const auto& pair : part.fields) {
ldpp_dout(this, 20) << "field.name=" << pair.first << dendl;
ldpp_dout(this, 20) << "field.val=" << pair.second.val << dendl;
ldpp_dout(this, 20) << "field.params:" << dendl;
for (const auto& param_pair : pair.second.params) {
ldpp_dout(this, 20) << " " << param_pair.first
<< " -> " << param_pair.second << dendl;
}
}
}
if (stream_done) {
/* Unexpected here. */
err_msg = "Malformed request";
return -EINVAL;
}
const auto field_iter = part.fields.find("Content-Disposition");
if (std::end(part.fields) != field_iter &&
std::end(field_iter->second.params) != field_iter->second.params.find("filename")) {
/* First data part ahead. */
current_data_part = std::move(part);
/* Stop the iteration. We can assume that all control parts have been
* already parsed. The rest of HTTP body should contain data parts
* only. They will be picked up by ::get_data(). */
break;
} else {
/* Control part ahead. Receive, parse and driver for later usage. */
bool boundary;
ret = read_data(part.data, s->cct->_conf->rgw_max_chunk_size,
boundary, stream_done);
if (ret < 0) {
return ret;
} else if (! boundary) {
err_msg = "Couldn't find boundary";
return -EINVAL;
}
ctrl_parts[part.name] = std::move(part);
}
} while (! stream_done);
min_len = 0;
max_len = get_max_file_size();
if (! current_data_part) {
err_msg = "FormPost: no files to process";
return -EINVAL;
}
if (! is_non_expired()) {
err_msg = "FormPost: Form Expired";
return -EPERM;
}
if (! is_integral()) {
err_msg = "FormPost: Invalid Signature";
return -EPERM;
}
return 0;
}
std::string RGWFormPost::get_current_filename() const
{
try {
const auto& field = current_data_part->fields.at("Content-Disposition");
const auto iter = field.params.find("filename");
if (std::end(field.params) != iter) {
return prefix + iter->second;
}
} catch (std::out_of_range&) {
/* NOP */;
}
return prefix;
}
std::string RGWFormPost::get_current_content_type() const
{
try {
const auto& field = current_data_part->fields.at("Content-Type");
return field.val;
} catch (std::out_of_range&) {
/* NOP */;
}
return std::string();
}
bool RGWFormPost::is_next_file_to_upload()
{
if (! stream_done) {
/* We have at least one additional part in the body. */
struct post_form_part part;
int r = read_form_part_header(&part, stream_done);
if (r < 0) {
return false;
}
const auto field_iter = part.fields.find("Content-Disposition");
if (std::end(part.fields) != field_iter) {
const auto& params = field_iter->second.params;
const auto& filename_iter = params.find("filename");
if (std::end(params) != filename_iter && ! filename_iter->second.empty()) {
current_data_part = std::move(part);
return true;
}
}
}
return false;
}
int RGWFormPost::get_data(ceph::bufferlist& bl, bool& again)
{
bool boundary;
int r = read_data(bl, s->cct->_conf->rgw_max_chunk_size,
boundary, stream_done);
if (r < 0) {
return r;
}
/* Tell RGWPostObj::execute(optional_yield y) that it has some data to put. */
again = !boundary;
return bl.length();
}
void RGWFormPost::send_response()
{
std::string redirect = get_part_str(ctrl_parts, "redirect");
if (! redirect.empty()) {
op_ret = STATUS_REDIRECT;
}
set_req_state_err(s, op_ret);
s->err.err_code = err_msg;
dump_errno(s);
if (! redirect.empty()) {
dump_redirect(s, redirect);
}
end_header(s, this);
}
bool RGWFormPost::is_formpost_req(req_state* const s)
{
std::string content_type;
std::map<std::string, std::string> params;
parse_boundary_params(s->info.env->get("CONTENT_TYPE", ""),
content_type, params);
return boost::algorithm::iequals(content_type, "multipart/form-data") &&
params.count("boundary") > 0;
}
RGWOp *RGWHandler_REST_Service_SWIFT::op_get()
{
return new RGWListBuckets_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Service_SWIFT::op_head()
{
return new RGWStatAccount_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Service_SWIFT::op_put()
{
if (s->info.args.exists("extract-archive")) {
return new RGWBulkUploadOp_ObjStore_SWIFT;
}
return nullptr;
}
RGWOp *RGWHandler_REST_Service_SWIFT::op_post()
{
if (s->info.args.exists("bulk-delete")) {
return new RGWBulkDelete_ObjStore_SWIFT;
}
return new RGWPutMetadataAccount_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Service_SWIFT::op_delete()
{
if (s->info.args.exists("bulk-delete")) {
return new RGWBulkDelete_ObjStore_SWIFT;
}
return NULL;
}
int RGWSwiftWebsiteHandler::serve_errordoc(const int http_ret,
const std::string error_doc,
optional_yield y)
{
/* Try to throw it all away. */
s->formatter->reset();
class RGWGetErrorPage : public RGWGetObj_ObjStore_SWIFT {
public:
RGWGetErrorPage(rgw::sal::Driver* const driver,
RGWHandler_REST* const handler,
req_state* const s,
const int http_ret) {
/* Calling a virtual from the base class is safe as the subobject should
* be properly initialized and we haven't overridden the init method. */
init(driver, s, handler);
set_get_data(true);
set_custom_http_response(http_ret);
}
int error_handler(const int err_no,
std::string* const error_content, optional_yield y) override {
/* Enforce that any error generated while getting the error page will
* not be send to a client. This allows us to recover from the double
* fault situation by sending the original message. */
return 0;
}
} get_errpage_op(driver, handler, s, http_ret);
/* This is okay. It's an error, so nothing will run after this, and it can be
* called by abort_early(), which can be called before s->object or s->bucket
* are set up. */
if (!rgw::sal::Bucket::empty(s->bucket.get())) {
s->object = s->bucket->get_object(rgw_obj_key(std::to_string(http_ret) + error_doc));
} else {
s->object = driver->get_object(rgw_obj_key(std::to_string(http_ret) + error_doc));
}
RGWOp* newop = &get_errpage_op;
RGWRequest req(0);
return rgw_process_authenticated(handler, newop, &req, s, y, driver, true);
}
int RGWSwiftWebsiteHandler::error_handler(const int err_no,
std::string* const error_content,
optional_yield y)
{
if (!s->bucket.get()) {
/* No bucket, default no-op handler */
return err_no;
}
const auto& ws_conf = s->bucket->get_info().website_conf;
if (can_be_website_req() && ! ws_conf.error_doc.empty()) {
set_req_state_err(s, err_no);
return serve_errordoc(s->err.http_ret, ws_conf.error_doc, y);
}
/* Let's go to the default, no-op handler. */
return err_no;
}
bool RGWSwiftWebsiteHandler::is_web_mode() const
{
const std::string_view webmode = s->info.env->get("HTTP_X_WEB_MODE", "");
return boost::algorithm::iequals(webmode, "true");
}
bool RGWSwiftWebsiteHandler::can_be_website_req() const
{
/* Static website works only with the GET or HEAD method. Nothing more. */
static const std::set<std::string_view> ws_methods = { "GET", "HEAD" };
if (ws_methods.count(s->info.method) == 0) {
return false;
}
/* We also need to handle early failures from the auth system. In such cases
* req_state::auth.identity may be empty. Let's treat that the same way as
* the anonymous access. */
if (! s->auth.identity) {
return true;
}
/* Swift serves websites only for anonymous requests unless client explicitly
* requested this behaviour by supplying X-Web-Mode HTTP header set to true. */
if (s->auth.identity->is_anonymous() || is_web_mode()) {
return true;
}
return false;
}
RGWOp* RGWSwiftWebsiteHandler::get_ws_redirect_op()
{
class RGWMovedPermanently: public RGWOp {
const std::string location;
public:
explicit RGWMovedPermanently(const std::string& location)
: location(location) {
}
int verify_permission(optional_yield) override {
return 0;
}
void execute(optional_yield) override {
op_ret = -ERR_PERMANENT_REDIRECT;
return;
}
void send_response() override {
set_req_state_err(s, op_ret);
dump_errno(s);
dump_content_length(s, 0);
dump_redirect(s, location);
end_header(s, this);
}
const char* name() const override {
return "RGWMovedPermanently";
}
};
return new RGWMovedPermanently(s->info.request_uri + '/');
}
RGWOp* RGWSwiftWebsiteHandler::get_ws_index_op()
{
/* Retarget to get obj on requested index file. */
if (! s->object->empty()) {
s->object->set_name(s->object->get_name() +
s->bucket->get_info().website_conf.get_index_doc());
} else {
s->object->set_name(s->bucket->get_info().website_conf.get_index_doc());
}
auto getop = new RGWGetObj_ObjStore_SWIFT;
getop->set_get_data(boost::algorithm::equals("GET", s->info.method));
return getop;
}
RGWOp* RGWSwiftWebsiteHandler::get_ws_listing_op()
{
class RGWWebsiteListing : public RGWListBucket_ObjStore_SWIFT {
const std::string prefix_override;
int get_params(optional_yield) override {
prefix = prefix_override;
max = default_max;
delimiter = "/";
return 0;
}
void send_response() override {
/* Generate the header now. */
set_req_state_err(s, op_ret);
dump_errno(s);
dump_container_metadata(s, s->bucket.get(), quota.bucket_quota,
s->bucket->get_info().website_conf);
end_header(s, this, "text/html");
if (op_ret < 0) {
return;
}
/* Now it's the time to start generating HTML bucket listing.
* All the crazy stuff with crafting tags will be delegated to
* RGWSwiftWebsiteListingFormatter. */
std::stringstream ss;
RGWSwiftWebsiteListingFormatter htmler(ss, prefix);
const auto& ws_conf = s->bucket->get_info().website_conf;
htmler.generate_header(s->decoded_uri,
ws_conf.listing_css_doc);
for (const auto& pair : common_prefixes) {
std::string subdir_name = pair.first;
if (! subdir_name.empty()) {
/* To be compliant with Swift we need to remove the trailing
* slash. */
subdir_name.pop_back();
}
htmler.dump_subdir(subdir_name);
}
for (const rgw_bucket_dir_entry& obj : objs) {
if (! common_prefixes.count(obj.key.name + '/')) {
htmler.dump_object(obj);
}
}
htmler.generate_footer();
dump_body(s, ss.str());
}
public:
/* Taking prefix_override by value to leverage std::string r-value ref
* ctor and thus avoid extra memory copying/increasing ref counter. */
explicit RGWWebsiteListing(std::string prefix_override)
: prefix_override(std::move(prefix_override)) {
}
};
std::string prefix = std::move(s->object->get_name());
s->object->set_key(rgw_obj_key());
return new RGWWebsiteListing(std::move(prefix));
}
bool RGWSwiftWebsiteHandler::is_web_dir() const
{
std::string subdir_name = url_decode(s->object->get_name());
/* Remove character from the subdir name if it is "/". */
if (subdir_name.empty()) {
return false;
} else if (subdir_name.back() == '/') {
subdir_name.pop_back();
if (subdir_name.empty()) {
return false;
}
}
std::unique_ptr<rgw::sal::Object> obj = s->bucket->get_object(rgw_obj_key(std::move(subdir_name)));
/* First, get attrset of the object we'll try to retrieve. */
obj->set_atomic();
obj->set_prefetch_data();
RGWObjState* state = nullptr;
if (obj->get_obj_state(s, &state, s->yield, false)) {
return false;
}
/* A nonexistent object cannot be a considered as a marker representing
* the emulation of catalog in FS hierarchy. */
if (! state->exists) {
return false;
}
/* Decode the content type. */
std::string content_type;
get_contype_from_attrs(state->attrset, content_type);
const auto& ws_conf = s->bucket->get_info().website_conf;
const std::string subdir_marker = ws_conf.subdir_marker.empty()
? "application/directory"
: ws_conf.subdir_marker;
return subdir_marker == content_type && state->size <= 1;
}
bool RGWSwiftWebsiteHandler::is_index_present(const std::string& index) const
{
std::unique_ptr<rgw::sal::Object> obj = s->bucket->get_object(rgw_obj_key(index));
obj->set_atomic();
obj->set_prefetch_data();
RGWObjState* state = nullptr;
if (obj->get_obj_state(s, &state, s->yield, false)) {
return false;
}
/* A nonexistent object cannot be a considered as a viable index. We will
* try to list the bucket or - if this is impossible - return an error. */
return state->exists;
}
int RGWSwiftWebsiteHandler::retarget_bucket(RGWOp* op, RGWOp** new_op)
{
ldpp_dout(s, 10) << "Starting retarget" << dendl;
RGWOp* op_override = nullptr;
/* In Swift static web content is served if the request is anonymous or
* has X-Web-Mode HTTP header specified to true. */
if (can_be_website_req()) {
const auto& ws_conf = s->bucket->get_info().website_conf;
const auto& index = s->bucket->get_info().website_conf.get_index_doc();
if (s->decoded_uri.back() != '/') {
op_override = get_ws_redirect_op();
} else if (! index.empty() && is_index_present(index)) {
op_override = get_ws_index_op();
} else if (ws_conf.listing_enabled) {
op_override = get_ws_listing_op();
}
}
if (op_override) {
handler->put_op(op);
op_override->init(driver, s, handler);
*new_op = op_override;
} else {
*new_op = op;
}
/* Return 404 Not Found is the request has web mode enforced but we static web
* wasn't able to serve it accordingly. */
return ! op_override && is_web_mode() ? -ENOENT : 0;
}
int RGWSwiftWebsiteHandler::retarget_object(RGWOp* op, RGWOp** new_op)
{
ldpp_dout(s, 10) << "Starting object retarget" << dendl;
RGWOp* op_override = nullptr;
/* In Swift static web content is served if the request is anonymous or
* has X-Web-Mode HTTP header specified to true. */
if (can_be_website_req() && is_web_dir()) {
const auto& ws_conf = s->bucket->get_info().website_conf;
const auto& index = s->bucket->get_info().website_conf.get_index_doc();
if (s->decoded_uri.back() != '/') {
op_override = get_ws_redirect_op();
} else if (! index.empty() && is_index_present(index)) {
op_override = get_ws_index_op();
} else if (ws_conf.listing_enabled) {
op_override = get_ws_listing_op();
}
} else {
/* A regular request or the specified object isn't a subdirectory marker.
* We don't need any re-targeting. Error handling (like sending a custom
* error page) will be performed by error_handler of the actual RGWOp. */
return 0;
}
if (op_override) {
handler->put_op(op);
op_override->init(driver, s, handler);
*new_op = op_override;
} else {
*new_op = op;
}
/* Return 404 Not Found if we aren't able to re-target for subdir marker. */
return ! op_override ? -ENOENT : 0;
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::get_obj_op(bool get_data)
{
if (is_acl_op()) {
return new RGWGetACLs_ObjStore_SWIFT;
}
if (get_data)
return new RGWListBucket_ObjStore_SWIFT;
else
return new RGWStatBucket_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::op_get()
{
return get_obj_op(true);
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::op_head()
{
return get_obj_op(false);
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::op_put()
{
if (is_acl_op()) {
return new RGWPutACLs_ObjStore_SWIFT;
}
if(s->info.args.exists("extract-archive")) {
return new RGWBulkUploadOp_ObjStore_SWIFT;
}
return new RGWCreateBucket_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::op_delete()
{
return new RGWDeleteBucket_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::op_post()
{
if (RGWFormPost::is_formpost_req(s)) {
return new RGWFormPost;
} else {
return new RGWPutMetadataBucket_ObjStore_SWIFT;
}
}
RGWOp *RGWHandler_REST_Bucket_SWIFT::op_options()
{
return new RGWOptionsCORS_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Obj_SWIFT::get_obj_op(bool get_data)
{
if (is_acl_op()) {
return new RGWGetACLs_ObjStore_SWIFT;
}
RGWGetObj_ObjStore_SWIFT *get_obj_op = new RGWGetObj_ObjStore_SWIFT;
get_obj_op->set_get_data(get_data);
return get_obj_op;
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_get()
{
return get_obj_op(true);
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_head()
{
return get_obj_op(false);
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_put()
{
if (is_acl_op()) {
return new RGWPutACLs_ObjStore_SWIFT;
}
if(s->info.args.exists("extract-archive")) {
return new RGWBulkUploadOp_ObjStore_SWIFT;
}
if (s->init_state.src_bucket.empty())
return new RGWPutObj_ObjStore_SWIFT;
else
return new RGWCopyObj_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_delete()
{
return new RGWDeleteObj_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_post()
{
if (RGWFormPost::is_formpost_req(s)) {
return new RGWFormPost;
} else {
return new RGWPutMetadataObject_ObjStore_SWIFT;
}
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_copy()
{
return new RGWCopyObj_ObjStore_SWIFT;
}
RGWOp *RGWHandler_REST_Obj_SWIFT::op_options()
{
return new RGWOptionsCORS_ObjStore_SWIFT;
}
int RGWHandler_REST_SWIFT::authorize(const DoutPrefixProvider *dpp, optional_yield y)
{
return rgw::auth::Strategy::apply(dpp, auth_strategy, s, y);
}
int RGWHandler_REST_SWIFT::postauth_init(optional_yield y)
{
struct req_init_state* t = &s->init_state;
/* XXX Stub this until Swift Auth sets account into URL. */
if (g_conf()->rgw_swift_account_in_url
&& s->user->get_id().id == RGW_USER_ANON_ID) {
s->bucket_tenant = s->account_name;
} else {
s->bucket_tenant = s->user->get_tenant();
}
s->bucket_name = t->url_bucket;
if (!s->object) {
/* Need an object, even an empty one */
s->object = driver->get_object(rgw_obj_key());
}
ldpp_dout(s, 10) << "s->object=" <<
(!s->object->empty() ? s->object->get_key() : rgw_obj_key("<NULL>"))
<< " s->bucket="
<< rgw_make_bucket_entry_name(s->bucket_tenant, s->bucket_name)
<< dendl;
int ret;
ret = rgw_validate_tenant_name(s->bucket_tenant);
if (ret)
return ret;
ret = validate_bucket_name(s->bucket_name);
if (ret)
return ret;
ret = validate_object_name(s->object->get_name());
if (ret)
return ret;
if (!t->src_bucket.empty()) {
/*
* We don't allow cross-tenant copy at present. It requires account
* names in the URL for Swift.
*/
s->src_tenant_name = s->user->get_tenant();
s->src_bucket_name = t->src_bucket;
ret = validate_bucket_name(s->src_bucket_name);
if (ret < 0) {
return ret;
}
ret = validate_object_name(s->src_object->get_name());
if (ret < 0) {
return ret;
}
}
return 0;
}
int RGWHandler_REST_SWIFT::validate_bucket_name(const string& bucket)
{
const size_t len = bucket.size();
if (len > MAX_BUCKET_NAME_LEN) {
/* Bucket Name too long. Generate custom error message and bind it
* to an R-value reference. */
const auto msg = boost::str(
boost::format("Container name length of %lld longer than %lld")
% len % int(MAX_BUCKET_NAME_LEN));
set_req_state_err(s, ERR_INVALID_BUCKET_NAME, msg);
return -ERR_INVALID_BUCKET_NAME;
}
if (len == 0)
return 0;
if (bucket[0] == '.')
return -ERR_INVALID_BUCKET_NAME;
if (check_utf8(bucket.c_str(), len))
return -ERR_INVALID_UTF8;
const char *s = bucket.c_str();
for (size_t 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;
}
static void next_tok(string& str, string& tok, char delim)
{
if (str.size() == 0) {
tok = "";
return;
}
tok = str;
int pos = str.find(delim);
if (pos > 0) {
tok = str.substr(0, pos);
str = str.substr(pos + 1);
} else {
str = "";
}
}
int RGWHandler_REST_SWIFT::init_from_header(rgw::sal::Driver* driver,
req_state* const s,
const std::string& frontend_prefix)
{
string req;
string first;
s->prot_flags |= RGW_REST_SWIFT;
char reqbuf[frontend_prefix.length() + s->decoded_uri.length() + 1];
sprintf(reqbuf, "%s%s", frontend_prefix.c_str(), s->decoded_uri.c_str());
const char *req_name = reqbuf;
const char *p;
if (*req_name == '?') {
p = req_name;
} else {
p = s->info.request_params.c_str();
}
s->info.args.set(p);
s->info.args.parse(s);
/* Skip the leading slash of URL hierarchy. */
if (req_name[0] != '/') {
return 0;
} else {
req_name++;
}
if ('\0' == req_name[0]) {
return g_conf()->rgw_swift_url_prefix == "/" ? -ERR_BAD_URL : 0;
}
req = req_name;
size_t pos = req.find('/');
if (std::string::npos != pos && g_conf()->rgw_swift_url_prefix != "/") {
bool cut_url = g_conf()->rgw_swift_url_prefix.length();
first = req.substr(0, pos);
if (first.compare(g_conf()->rgw_swift_url_prefix) == 0) {
if (cut_url) {
/* Rewind to the "v1/..." part. */
next_tok(req, first, '/');
}
}
} else if (req.compare(g_conf()->rgw_swift_url_prefix) == 0) {
s->formatter = new RGWFormatter_Plain;
return -ERR_BAD_URL;
} else {
first = req;
}
std::string tenant_path;
if (! g_conf()->rgw_swift_tenant_name.empty()) {
tenant_path = "/AUTH_";
tenant_path.append(g_conf()->rgw_swift_tenant_name);
}
/* verify that the request_uri conforms with what's expected */
char buf[g_conf()->rgw_swift_url_prefix.length() + 16 + tenant_path.length()];
int blen;
if (g_conf()->rgw_swift_url_prefix == "/") {
blen = sprintf(buf, "/v1%s", tenant_path.c_str());
} else {
blen = sprintf(buf, "/%s/v1%s",
g_conf()->rgw_swift_url_prefix.c_str(), tenant_path.c_str());
}
if (strncmp(reqbuf, buf, blen) != 0) {
return -ENOENT;
}
int ret = allocate_formatter(s, RGWFormat::PLAIN, true);
if (ret < 0)
return ret;
string ver;
next_tok(req, ver, '/');
if (!tenant_path.empty() || g_conf()->rgw_swift_account_in_url) {
string account_name;
next_tok(req, account_name, '/');
/* Erase all pre-defined prefixes like "AUTH_" or "KEY_". */
const vector<string> skipped_prefixes = { "AUTH_", "KEY_" };
for (const auto& pfx : skipped_prefixes) {
const size_t comp_len = min(account_name.length(), pfx.length());
if (account_name.compare(0, comp_len, pfx) == 0) {
/* Prefix is present. Drop it. */
account_name = account_name.substr(comp_len);
break;
}
}
if (account_name.empty()) {
return -ERR_PRECONDITION_FAILED;
} else {
s->account_name = account_name;
}
}
next_tok(req, first, '/');
ldpp_dout(s, 10) << "ver=" << ver << " first=" << first << " req=" << req << dendl;
if (first.size() == 0)
return 0;
s->info.effective_uri = "/" + first;
// Save bucket to tide us over until token is parsed.
s->init_state.url_bucket = first;
if (req.size()) {
s->object = driver->get_object(
rgw_obj_key(req, s->info.env->get("HTTP_X_OBJECT_VERSION_ID", ""))); /* rgw swift extension */
s->info.effective_uri.append("/" + s->object->get_name());
}
return 0;
}
int RGWHandler_REST_SWIFT::init(rgw::sal::Driver* driver, req_state* s,
rgw::io::BasicClient *cio)
{
struct req_init_state *t = &s->init_state;
s->dialect = "swift";
std::string copy_source = s->info.env->get("HTTP_X_COPY_FROM", "");
if (! copy_source.empty()) {
rgw_obj_key key;
bool result = RGWCopyObj::parse_copy_location(copy_source, t->src_bucket, key, s);
if (!result)
return -ERR_BAD_URL;
s->src_object = driver->get_object(key);
if (!s->src_object)
return -ERR_BAD_URL;
}
if (s->op == OP_COPY) {
std::string req_dest = s->info.env->get("HTTP_DESTINATION", "");
if (req_dest.empty())
return -ERR_BAD_URL;
std::string dest_bucket_name;
rgw_obj_key dest_obj_key;
bool result =
RGWCopyObj::parse_copy_location(req_dest, dest_bucket_name,
dest_obj_key, s);
if (!result)
return -ERR_BAD_URL;
std::string dest_object_name = dest_obj_key.name;
/* convert COPY operation into PUT */
t->src_bucket = t->url_bucket;
s->src_object = s->object->clone();
t->url_bucket = dest_bucket_name;
s->object->set_name(dest_object_name);
s->op = OP_PUT;
}
s->info.storage_class = s->info.env->get("HTTP_X_OBJECT_STORAGE_CLASS", "");
return RGWHandler_REST::init(driver, s, cio);
}
RGWHandler_REST*
RGWRESTMgr_SWIFT::get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix)
{
int ret = RGWHandler_REST_SWIFT::init_from_header(driver, s, frontend_prefix);
if (ret < 0) {
ldpp_dout(s, 10) << "init_from_header returned err=" << ret << dendl;
return nullptr;
}
const auto& auth_strategy = auth_registry.get_swift();
if (s->init_state.url_bucket.empty()) {
return new RGWHandler_REST_Service_SWIFT(auth_strategy);
}
if (rgw::sal::Object::empty(s->object.get())) {
return new RGWHandler_REST_Bucket_SWIFT(auth_strategy);
}
return new RGWHandler_REST_Obj_SWIFT(auth_strategy);
}
RGWHandler_REST* RGWRESTMgr_SWIFT_Info::get_handler(
rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix)
{
s->prot_flags |= RGW_REST_SWIFT;
const auto& auth_strategy = auth_registry.get_swift();
return new RGWHandler_REST_SWIFT_Info(auth_strategy);
}
| 91,787 | 28.362764 | 111 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_swift.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/optional.hpp>
#include <boost/utility/typed_in_place_factory.hpp>
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_swift_auth.h"
#include "rgw_http_errors.h"
class RGWGetObj_ObjStore_SWIFT : public RGWGetObj_ObjStore {
int custom_http_ret = 0;
public:
RGWGetObj_ObjStore_SWIFT() {}
~RGWGetObj_ObjStore_SWIFT() override {}
int verify_permission(optional_yield y) override;
int get_params(optional_yield y) override;
int send_response_data_error(optional_yield y) override;
int send_response_data(bufferlist& bl, off_t ofs, off_t len) override;
void set_custom_http_response(const int http_ret) {
custom_http_ret = http_ret;
}
bool need_object_expiration() override {
return true;
}
};
class RGWListBuckets_ObjStore_SWIFT : public RGWListBuckets_ObjStore {
bool need_stats;
bool wants_reversed;
std::string prefix;
std::vector<rgw::sal::BucketList> reverse_buffer;
uint64_t get_default_max() const override {
return 0;
}
public:
RGWListBuckets_ObjStore_SWIFT()
: need_stats(true),
wants_reversed(false) {
}
~RGWListBuckets_ObjStore_SWIFT() override {}
int get_params(optional_yield y) override;
void handle_listing_chunk(rgw::sal::BucketList&& buckets) override;
void send_response_begin(bool has_buckets) override;
void send_response_data(rgw::sal::BucketList& buckets) override;
void send_response_data_reversed(rgw::sal::BucketList& buckets);
void dump_bucket_entry(const rgw::sal::Bucket& obj);
void send_response_end() override;
bool should_get_stats() override { return need_stats; }
bool supports_account_metadata() override { return true; }
};
class RGWListBucket_ObjStore_SWIFT : public RGWListBucket_ObjStore {
std::string path;
public:
RGWListBucket_ObjStore_SWIFT() {
default_max = 10000;
}
~RGWListBucket_ObjStore_SWIFT() override {}
int get_params(optional_yield y) override;
void send_response() override;
bool need_container_stats() override { return true; }
};
class RGWStatAccount_ObjStore_SWIFT : public RGWStatAccount_ObjStore {
std::map<std::string, bufferlist> attrs;
public:
RGWStatAccount_ObjStore_SWIFT() {
}
~RGWStatAccount_ObjStore_SWIFT() override {}
void execute(optional_yield y) override;
void send_response() override;
};
class RGWStatBucket_ObjStore_SWIFT : public RGWStatBucket_ObjStore {
public:
RGWStatBucket_ObjStore_SWIFT() {}
~RGWStatBucket_ObjStore_SWIFT() override {}
void send_response() override;
};
class RGWCreateBucket_ObjStore_SWIFT : public RGWCreateBucket_ObjStore {
protected:
bool need_metadata_upload() const override { return true; }
public:
RGWCreateBucket_ObjStore_SWIFT() {}
~RGWCreateBucket_ObjStore_SWIFT() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWDeleteBucket_ObjStore_SWIFT : public RGWDeleteBucket_ObjStore {
public:
RGWDeleteBucket_ObjStore_SWIFT() {}
~RGWDeleteBucket_ObjStore_SWIFT() override {}
void send_response() override;
};
class RGWPutObj_ObjStore_SWIFT : public RGWPutObj_ObjStore {
std::string lo_etag;
public:
RGWPutObj_ObjStore_SWIFT() {}
~RGWPutObj_ObjStore_SWIFT() override {}
int update_slo_segment_size(rgw_slo_entry& entry);
int verify_permission(optional_yield y) override;
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWPutMetadataAccount_ObjStore_SWIFT : public RGWPutMetadataAccount_ObjStore {
public:
RGWPutMetadataAccount_ObjStore_SWIFT() {}
~RGWPutMetadataAccount_ObjStore_SWIFT() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWPutMetadataBucket_ObjStore_SWIFT : public RGWPutMetadataBucket_ObjStore {
public:
RGWPutMetadataBucket_ObjStore_SWIFT() {}
~RGWPutMetadataBucket_ObjStore_SWIFT() override {}
int get_params(optional_yield y) override;
void send_response() override;
};
class RGWPutMetadataObject_ObjStore_SWIFT : public RGWPutMetadataObject_ObjStore {
public:
RGWPutMetadataObject_ObjStore_SWIFT() {}
~RGWPutMetadataObject_ObjStore_SWIFT() override {}
int get_params(optional_yield y) override;
void send_response() override;
bool need_object_expiration() override { return true; }
};
class RGWDeleteObj_ObjStore_SWIFT : public RGWDeleteObj_ObjStore {
public:
RGWDeleteObj_ObjStore_SWIFT() {}
~RGWDeleteObj_ObjStore_SWIFT() override {}
int verify_permission(optional_yield y) override;
int get_params(optional_yield y) override;
bool need_object_expiration() override { return true; }
void send_response() override;
};
class RGWCopyObj_ObjStore_SWIFT : public RGWCopyObj_ObjStore {
bool sent_header;
protected:
void dump_copy_info();
public:
RGWCopyObj_ObjStore_SWIFT() : sent_header(false) {}
~RGWCopyObj_ObjStore_SWIFT() override {}
int init_dest_policy() override;
int get_params(optional_yield y) override;
void send_response() override;
void send_partial_response(off_t ofs) override;
};
class RGWGetACLs_ObjStore_SWIFT : public RGWGetACLs_ObjStore {
public:
RGWGetACLs_ObjStore_SWIFT() {}
~RGWGetACLs_ObjStore_SWIFT() override {}
void send_response() override {}
};
class RGWPutACLs_ObjStore_SWIFT : public RGWPutACLs_ObjStore {
public:
RGWPutACLs_ObjStore_SWIFT() : RGWPutACLs_ObjStore() {}
~RGWPutACLs_ObjStore_SWIFT() override {}
void send_response() override {}
};
class RGWOptionsCORS_ObjStore_SWIFT : public RGWOptionsCORS_ObjStore {
public:
RGWOptionsCORS_ObjStore_SWIFT() {}
~RGWOptionsCORS_ObjStore_SWIFT() override {}
void send_response() override;
};
class RGWBulkDelete_ObjStore_SWIFT : public RGWBulkDelete_ObjStore {
public:
RGWBulkDelete_ObjStore_SWIFT() {}
~RGWBulkDelete_ObjStore_SWIFT() override {}
int get_data(std::list<RGWBulkDelete::acct_path_t>& items,
bool * is_truncated) override;
void send_response() override;
};
class RGWBulkUploadOp_ObjStore_SWIFT : public RGWBulkUploadOp_ObjStore {
size_t conlen;
size_t curpos;
public:
RGWBulkUploadOp_ObjStore_SWIFT()
: conlen(0),
curpos(0) {
}
~RGWBulkUploadOp_ObjStore_SWIFT() = default;
std::unique_ptr<StreamGetter> create_stream() override;
void send_response() override;
};
class RGWInfo_ObjStore_SWIFT : public RGWInfo_ObjStore {
protected:
struct info
{
bool is_admin_info;
std::function<void (Formatter&, const ConfigProxy&, rgw::sal::Driver*)> list_data;
};
static const std::vector<std::pair<std::string, struct info>> swift_info;
public:
RGWInfo_ObjStore_SWIFT() {}
~RGWInfo_ObjStore_SWIFT() override {}
void execute(optional_yield y) override;
void send_response() override;
static void list_swift_data(Formatter& formatter, const ConfigProxy& config, rgw::sal::Driver* driver);
static void list_tempauth_data(Formatter& formatter, const ConfigProxy& config, rgw::sal::Driver* driver);
static void list_tempurl_data(Formatter& formatter, const ConfigProxy& config, rgw::sal::Driver* driver);
static void list_slo_data(Formatter& formatter, const ConfigProxy& config, rgw::sal::Driver* driver);
static bool is_expired(const std::string& expires, const DoutPrefixProvider* dpp);
};
class RGWFormPost : public RGWPostObj_ObjStore {
std::string get_current_filename() const override;
std::string get_current_content_type() const override;
std::size_t get_max_file_size() /*const*/;
bool is_next_file_to_upload() override;
bool is_integral();
bool is_non_expired();
void get_owner_info(const req_state* s,
RGWUserInfo& owner_info) const;
parts_collection_t ctrl_parts;
boost::optional<post_form_part> current_data_part;
std::string prefix;
bool stream_done = false;
class SignatureHelper;
public:
RGWFormPost() = default;
~RGWFormPost() = default;
void init(rgw::sal::Driver* driver,
req_state* s,
RGWHandler* dialect_handler) override;
int get_params(optional_yield y) override;
int get_data(ceph::bufferlist& bl, bool& again) override;
void send_response() override;
static bool is_formpost_req(req_state* const s);
};
class RGWFormPost::SignatureHelper
{
private:
static constexpr uint32_t output_size =
CEPH_CRYPTO_HMACSHA1_DIGESTSIZE * 2 + 1;
unsigned char dest[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE]; // 20
char dest_str[output_size];
public:
SignatureHelper() = default;
const char* calc(const std::string& key,
const std::string_view& path_info,
const std::string_view& redirect,
const std::string_view& max_file_size,
const std::string_view& max_file_count,
const std::string_view& expires) {
using ceph::crypto::HMACSHA1;
using UCHARPTR = const unsigned char*;
HMACSHA1 hmac((UCHARPTR) key.data(), key.size());
hmac.Update((UCHARPTR) path_info.data(), path_info.size());
hmac.Update((UCHARPTR) "\n", 1);
hmac.Update((UCHARPTR) redirect.data(), redirect.size());
hmac.Update((UCHARPTR) "\n", 1);
hmac.Update((UCHARPTR) max_file_size.data(), max_file_size.size());
hmac.Update((UCHARPTR) "\n", 1);
hmac.Update((UCHARPTR) max_file_count.data(), max_file_count.size());
hmac.Update((UCHARPTR) "\n", 1);
hmac.Update((UCHARPTR) expires.data(), expires.size());
hmac.Final(dest);
buf_to_hex((UCHARPTR) dest, sizeof(dest), dest_str);
return dest_str;
}
const char* get_signature() const {
return dest_str;
}
bool is_equal_to(const std::string& rhs) const {
/* never allow out-of-range exception */
if (rhs.size() < (output_size - 1)) {
return false;
}
return rhs.compare(0 /* pos */, output_size, dest_str) == 0;
}
}; /* RGWFormPost::SignatureHelper */
class RGWSwiftWebsiteHandler {
rgw::sal::Driver* const driver;
req_state* const s;
RGWHandler_REST* const handler;
bool is_web_mode() const;
bool can_be_website_req() const;
bool is_web_dir() const;
bool is_index_present(const std::string& index) const;
int serve_errordoc(int http_ret, std::string error_doc, optional_yield y);
RGWOp* get_ws_redirect_op();
RGWOp* get_ws_index_op();
RGWOp* get_ws_listing_op();
public:
RGWSwiftWebsiteHandler(rgw::sal::Driver* const driver,
req_state* const s,
RGWHandler_REST* const handler)
: driver(driver),
s(s),
handler(handler) {
}
int error_handler(const int err_no,
std::string* const error_content,
optional_yield y);
int retarget_bucket(RGWOp* op, RGWOp** new_op);
int retarget_object(RGWOp* op, RGWOp** new_op);
};
class RGWHandler_REST_SWIFT : public RGWHandler_REST {
friend class RGWRESTMgr_SWIFT;
friend class RGWRESTMgr_SWIFT_Info;
protected:
const rgw::auth::Strategy& auth_strategy;
virtual bool is_acl_op() const {
return false;
}
static int init_from_header(rgw::sal::Driver* driver, req_state* s,
const std::string& frontend_prefix);
public:
explicit RGWHandler_REST_SWIFT(const rgw::auth::Strategy& auth_strategy)
: auth_strategy(auth_strategy) {
}
~RGWHandler_REST_SWIFT() override = default;
int validate_bucket_name(const std::string& bucket);
int init(rgw::sal::Driver* driver, req_state *s, rgw::io::BasicClient *cio) override;
int authorize(const DoutPrefixProvider *dpp, optional_yield y) override;
int postauth_init(optional_yield y) override;
RGWAccessControlPolicy *alloc_policy() { return nullptr; /* return new RGWAccessControlPolicy_SWIFT; */ }
void free_policy(RGWAccessControlPolicy *policy) { delete policy; }
};
class RGWHandler_REST_Service_SWIFT : public RGWHandler_REST_SWIFT {
protected:
RGWOp *op_get() override;
RGWOp *op_head() override;
RGWOp *op_put() override;
RGWOp *op_post() override;
RGWOp *op_delete() override;
public:
using RGWHandler_REST_SWIFT::RGWHandler_REST_SWIFT;
~RGWHandler_REST_Service_SWIFT() override = default;
};
class RGWHandler_REST_Bucket_SWIFT : public RGWHandler_REST_SWIFT {
/* We need the boost::optional here only because of handler's late
* initialization (see the init() method). */
boost::optional<RGWSwiftWebsiteHandler> website_handler;
protected:
bool is_obj_update_op() const override {
return s->op == OP_POST;
}
RGWOp *get_obj_op(bool get_data);
RGWOp *op_get() override;
RGWOp *op_head() override;
RGWOp *op_put() override;
RGWOp *op_delete() override;
RGWOp *op_post() override;
RGWOp *op_options() override;
public:
using RGWHandler_REST_SWIFT::RGWHandler_REST_SWIFT;
~RGWHandler_REST_Bucket_SWIFT() override = default;
int error_handler(int err_no, std::string *error_content, optional_yield y) override {
return website_handler->error_handler(err_no, error_content, y);
}
int retarget(RGWOp* op, RGWOp** new_op, optional_yield) override {
return website_handler->retarget_bucket(op, new_op);
}
int init(rgw::sal::Driver* const driver,
req_state* const s,
rgw::io::BasicClient* const cio) override {
website_handler = boost::in_place<RGWSwiftWebsiteHandler>(driver, s, this);
return RGWHandler_REST_SWIFT::init(driver, s, cio);
}
};
class RGWHandler_REST_Obj_SWIFT : public RGWHandler_REST_SWIFT {
/* We need the boost::optional here only because of handler's late
* initialization (see the init() method). */
boost::optional<RGWSwiftWebsiteHandler> website_handler;
protected:
bool is_obj_update_op() const override {
return s->op == OP_POST;
}
RGWOp *get_obj_op(bool get_data);
RGWOp *op_get() override;
RGWOp *op_head() override;
RGWOp *op_put() override;
RGWOp *op_delete() override;
RGWOp *op_post() override;
RGWOp *op_copy() override;
RGWOp *op_options() override;
public:
using RGWHandler_REST_SWIFT::RGWHandler_REST_SWIFT;
~RGWHandler_REST_Obj_SWIFT() override = default;
int error_handler(int err_no, std::string *error_content,
optional_yield y) override {
return website_handler->error_handler(err_no, error_content, y);
}
int retarget(RGWOp* op, RGWOp** new_op, optional_yield) override {
return website_handler->retarget_object(op, new_op);
}
int init(rgw::sal::Driver* const driver,
req_state* const s,
rgw::io::BasicClient* const cio) override {
website_handler = boost::in_place<RGWSwiftWebsiteHandler>(driver, s, this);
return RGWHandler_REST_SWIFT::init(driver, s, cio);
}
};
class RGWRESTMgr_SWIFT : public RGWRESTMgr {
protected:
RGWRESTMgr* get_resource_mgr_as_default(req_state* const s,
const std::string& uri,
std::string* const out_uri) override {
return this->get_resource_mgr(s, uri, out_uri);
}
public:
RGWRESTMgr_SWIFT() = default;
~RGWRESTMgr_SWIFT() override = default;
RGWHandler_REST *get_handler(rgw::sal::Driver* driver,
req_state *s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix) override;
};
class RGWGetCrossDomainPolicy_ObjStore_SWIFT
: public RGWGetCrossDomainPolicy_ObjStore {
public:
RGWGetCrossDomainPolicy_ObjStore_SWIFT() = default;
~RGWGetCrossDomainPolicy_ObjStore_SWIFT() override = default;
void send_response() override;
};
class RGWGetHealthCheck_ObjStore_SWIFT
: public RGWGetHealthCheck_ObjStore {
public:
RGWGetHealthCheck_ObjStore_SWIFT() = default;
~RGWGetHealthCheck_ObjStore_SWIFT() override = default;
void send_response() override;
};
class RGWHandler_SWIFT_CrossDomain : public RGWHandler_REST {
public:
RGWHandler_SWIFT_CrossDomain() = default;
~RGWHandler_SWIFT_CrossDomain() override = default;
RGWOp *op_get() override {
return new RGWGetCrossDomainPolicy_ObjStore_SWIFT();
}
int init(rgw::sal::Driver* const driver,
req_state* const state,
rgw::io::BasicClient* const cio) override {
state->dialect = "swift";
state->formatter = new JSONFormatter;
state->format = RGWFormat::JSON;
return RGWHandler::init(driver, state, cio);
}
int authorize(const DoutPrefixProvider *dpp, optional_yield) override {
return 0;
}
int postauth_init(optional_yield) override {
return 0;
}
int read_permissions(RGWOp *, optional_yield y) override {
return 0;
}
virtual RGWAccessControlPolicy *alloc_policy() { return nullptr; }
virtual void free_policy(RGWAccessControlPolicy *policy) {}
};
class RGWRESTMgr_SWIFT_CrossDomain : public RGWRESTMgr {
protected:
RGWRESTMgr *get_resource_mgr(req_state* const s,
const std::string& uri,
std::string* const out_uri) override {
return this;
}
public:
RGWRESTMgr_SWIFT_CrossDomain() = default;
~RGWRESTMgr_SWIFT_CrossDomain() override = default;
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry&,
const std::string&) override {
s->prot_flags |= RGW_REST_SWIFT;
return new RGWHandler_SWIFT_CrossDomain;
}
};
class RGWHandler_SWIFT_HealthCheck : public RGWHandler_REST {
public:
RGWHandler_SWIFT_HealthCheck() = default;
~RGWHandler_SWIFT_HealthCheck() override = default;
RGWOp *op_get() override {
return new RGWGetHealthCheck_ObjStore_SWIFT();
}
int init(rgw::sal::Driver* const driver,
req_state* const state,
rgw::io::BasicClient* const cio) override {
state->dialect = "swift";
state->formatter = new JSONFormatter;
state->format = RGWFormat::JSON;
return RGWHandler::init(driver, state, cio);
}
int authorize(const DoutPrefixProvider *dpp, optional_yield y) override {
return 0;
}
int postauth_init(optional_yield) override {
return 0;
}
int read_permissions(RGWOp *, optional_yield y) override {
return 0;
}
virtual RGWAccessControlPolicy *alloc_policy() { return nullptr; }
virtual void free_policy(RGWAccessControlPolicy *policy) {}
};
class RGWRESTMgr_SWIFT_HealthCheck : public RGWRESTMgr {
protected:
RGWRESTMgr *get_resource_mgr(req_state* const s,
const std::string& uri,
std::string* const out_uri) override {
return this;
}
public:
RGWRESTMgr_SWIFT_HealthCheck() = default;
~RGWRESTMgr_SWIFT_HealthCheck() override = default;
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state* const s,
const rgw::auth::StrategyRegistry&,
const std::string&) override {
s->prot_flags |= RGW_REST_SWIFT;
return new RGWHandler_SWIFT_HealthCheck;
}
};
class RGWHandler_REST_SWIFT_Info : public RGWHandler_REST_SWIFT {
public:
using RGWHandler_REST_SWIFT::RGWHandler_REST_SWIFT;
~RGWHandler_REST_SWIFT_Info() override = default;
RGWOp *op_get() override {
return new RGWInfo_ObjStore_SWIFT();
}
int init(rgw::sal::Driver* const driver,
req_state* const state,
rgw::io::BasicClient* const cio) override {
state->dialect = "swift";
state->formatter = new JSONFormatter;
state->format = RGWFormat::JSON;
return RGWHandler::init(driver, state, cio);
}
int authorize(const DoutPrefixProvider *dpp, optional_yield) override {
return 0;
}
int postauth_init(optional_yield) override {
return 0;
}
int read_permissions(RGWOp *, optional_yield y) override {
return 0;
}
};
class RGWRESTMgr_SWIFT_Info : public RGWRESTMgr {
public:
RGWRESTMgr_SWIFT_Info() = default;
~RGWRESTMgr_SWIFT_Info() override = default;
RGWHandler_REST *get_handler(rgw::sal::Driver* driver,
req_state* s,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string& frontend_prefix) override;
};
| 20,185 | 28.425656 | 108 |
h
|
null |
ceph-main/src/rgw/rgw_rest_usage.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_op.h"
#include "rgw_usage.h"
#include "rgw_rest_usage.h"
#include "rgw_sal.h"
#include "include/str_list.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
class RGWOp_Usage_Get : public RGWRESTOp {
public:
RGWOp_Usage_Get() {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("usage", RGW_CAP_READ);
}
void execute(optional_yield y) override;
const char* name() const override { return "get_usage"; }
};
void RGWOp_Usage_Get::execute(optional_yield y) {
map<std::string, bool> categories;
string uid_str;
string bucket_name;
uint64_t start, end;
bool show_entries;
bool show_summary;
RESTArgs::get_string(s, "uid", uid_str, &uid_str);
RESTArgs::get_string(s, "bucket", bucket_name, &bucket_name);
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(uid_str));
std::unique_ptr<rgw::sal::Bucket> bucket;
if (!bucket_name.empty()) {
driver->get_bucket(nullptr, user.get(), std::string(), bucket_name, &bucket, null_yield);
}
RESTArgs::get_epoch(s, "start", 0, &start);
RESTArgs::get_epoch(s, "end", (uint64_t)-1, &end);
RESTArgs::get_bool(s, "show-entries", true, &show_entries);
RESTArgs::get_bool(s, "show-summary", true, &show_summary);
string cat_str;
RESTArgs::get_string(s, "categories", cat_str, &cat_str);
if (!cat_str.empty()) {
list<string> cat_list;
list<string>::iterator iter;
get_str_list(cat_str, cat_list);
for (iter = cat_list.begin(); iter != cat_list.end(); ++iter) {
categories[*iter] = true;
}
}
op_ret = RGWUsage::show(this, driver, user.get(), bucket.get(), start, end, show_entries, show_summary, &categories, flusher);
}
class RGWOp_Usage_Delete : public RGWRESTOp {
public:
RGWOp_Usage_Delete() {}
int check_caps(const RGWUserCaps& caps) override {
return caps.check_cap("usage", RGW_CAP_WRITE);
}
void execute(optional_yield y) override;
const char* name() const override { return "trim_usage"; }
};
void RGWOp_Usage_Delete::execute(optional_yield y) {
string uid_str;
string bucket_name;
uint64_t start, end;
RESTArgs::get_string(s, "uid", uid_str, &uid_str);
RESTArgs::get_string(s, "bucket", bucket_name, &bucket_name);
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(uid_str));
std::unique_ptr<rgw::sal::Bucket> bucket;
if (!bucket_name.empty()) {
driver->get_bucket(nullptr, user.get(), std::string(), bucket_name, &bucket, null_yield);
}
RESTArgs::get_epoch(s, "start", 0, &start);
RESTArgs::get_epoch(s, "end", (uint64_t)-1, &end);
if (rgw::sal::User::empty(user.get()) &&
bucket_name.empty() &&
!start &&
end == (uint64_t)-1) {
bool remove_all;
RESTArgs::get_bool(s, "remove-all", false, &remove_all);
if (!remove_all) {
op_ret = -EINVAL;
return;
}
}
op_ret = RGWUsage::trim(this, driver, user.get(), bucket.get(), start, end, y);
}
RGWOp *RGWHandler_Usage::op_get()
{
return new RGWOp_Usage_Get;
}
RGWOp *RGWHandler_Usage::op_delete()
{
return new RGWOp_Usage_Delete;
}
| 3,198 | 25.221311 | 128 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_usage.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_rest.h"
#include "rgw_rest_s3.h"
class RGWHandler_Usage : public RGWHandler_Auth_S3 {
protected:
RGWOp *op_get() override;
RGWOp *op_delete() override;
public:
using RGWHandler_Auth_S3::RGWHandler_Auth_S3;
~RGWHandler_Usage() override = default;
int read_permissions(RGWOp*, optional_yield) override {
return 0;
}
};
class RGWRESTMgr_Usage : public RGWRESTMgr {
public:
RGWRESTMgr_Usage() = default;
~RGWRESTMgr_Usage() override = default;
RGWHandler_REST* get_handler(rgw::sal::Driver* driver,
req_state*,
const rgw::auth::StrategyRegistry& auth_registry,
const std::string&) override {
return new RGWHandler_Usage(auth_registry);
}
};
| 876 | 24.057143 | 80 |
h
|
null |
ceph-main/src/rgw/rgw_rest_user_policy.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 <regex>
#include "common/errno.h"
#include "common/Formatter.h"
#include "common/ceph_json.h"
#include "include/types.h"
#include "rgw_string.h"
#include "rgw_common.h"
#include "rgw_op.h"
#include "rgw_rest.h"
#include "rgw_rest_user_policy.h"
#include "rgw_sal.h"
#include "services/svc_zone.h"
#define dout_subsys ceph_subsys_rgw
void RGWRestUserPolicy::dump(Formatter *f) const
{
encode_json("PolicyName", policy_name , f);
encode_json("UserName", user_name , f);
encode_json("PolicyDocument", policy, f);
}
void RGWRestUserPolicy::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s);
}
int RGWRestUserPolicy::verify_permission(optional_yield y)
{
if (s->auth.identity->is_anonymous()) {
return -EACCES;
}
if(int ret = check_caps(s->user->get_caps()); ret == 0) {
return ret;
}
uint64_t op = get_op();
std::string user_name = s->info.args.get("UserName");
rgw_user user_id(user_name);
if (! verify_user_permission(this, s, rgw::ARN(rgw::ARN(user_id.id,
"user",
user_id.tenant)), op)) {
return -EACCES;
}
return 0;
}
bool RGWRestUserPolicy::validate_input()
{
if (policy_name.length() > MAX_POLICY_NAME_LEN) {
ldpp_dout(this, 0) << "ERROR: Invalid policy name length " << dendl;
return false;
}
std::regex regex_policy_name("[A-Za-z0-9:=,.@-]+");
if (! std::regex_match(policy_name, regex_policy_name)) {
ldpp_dout(this, 0) << "ERROR: Invalid chars in policy name " << dendl;
return false;
}
return true;
}
int RGWUserPolicyRead::check_caps(const RGWUserCaps& caps)
{
return caps.check_cap("user-policy", RGW_CAP_READ);
}
int RGWUserPolicyWrite::check_caps(const RGWUserCaps& caps)
{
return caps.check_cap("user-policy", RGW_CAP_WRITE);
}
uint64_t RGWPutUserPolicy::get_op()
{
return rgw::IAM::iamPutUserPolicy;
}
int RGWPutUserPolicy::get_params()
{
policy_name = url_decode(s->info.args.get("PolicyName"), true);
user_name = url_decode(s->info.args.get("UserName"), true);
policy = url_decode(s->info.args.get("PolicyDocument"), true);
if (policy_name.empty() || user_name.empty() || policy.empty()) {
ldpp_dout(this, 20) << "ERROR: one of policy name, user name or policy document is empty"
<< dendl;
return -EINVAL;
}
if (! validate_input()) {
return -EINVAL;
}
return 0;
}
void RGWPutUserPolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
bufferlist bl = bufferlist::static_from_string(policy);
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(user_name));
op_ret = user->load_user(s, s->yield);
if (op_ret < 0) {
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
op_ret = user->read_attrs(s, s->yield);
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
ceph::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) << "ERROR: forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
try {
const rgw::IAM::Policy p(
s->cct, s->user->get_tenant(), bl,
s->cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals"));
std::map<std::string, std::string> policies;
if (auto it = user->get_attrs().find(RGW_ATTR_USER_POLICY); it != user->get_attrs().end()) {
bufferlist out_bl = it->second;
decode(policies, out_bl);
}
bufferlist in_bl;
policies[policy_name] = policy;
constexpr unsigned int USER_POLICIES_MAX_NUM = 100;
const unsigned int max_num = s->cct->_conf->rgw_user_policies_max_num < 0 ?
USER_POLICIES_MAX_NUM : s->cct->_conf->rgw_user_policies_max_num;
if (policies.size() > max_num) {
ldpp_dout(this, 4) << "IAM user policies has reached the num config: "
<< max_num << ", cant add another" << dendl;
op_ret = -ERR_INVALID_REQUEST;
s->err.message =
"The number of IAM user policies should not exceed allowed limit "
"of " +
std::to_string(max_num) + " policies.";
return;
}
encode(policies, in_bl);
user->get_attrs()[RGW_ATTR_USER_POLICY] = in_bl;
op_ret = user->store_user(s, s->yield, false);
if (op_ret < 0) {
op_ret = -ERR_INTERNAL_ERROR;
}
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode user policies" << dendl;
op_ret = -EIO;
} catch (rgw::IAM::PolicyParseException& e) {
ldpp_dout(this, 5) << "failed to parse policy: " << e.what() << dendl;
s->err.message = e.what();
op_ret = -ERR_MALFORMED_DOC;
}
if (op_ret == 0) {
s->formatter->open_object_section("PutUserPolicyResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
}
uint64_t RGWGetUserPolicy::get_op()
{
return rgw::IAM::iamGetUserPolicy;
}
int RGWGetUserPolicy::get_params()
{
policy_name = s->info.args.get("PolicyName");
user_name = s->info.args.get("UserName");
if (policy_name.empty() || user_name.empty()) {
ldpp_dout(this, 20) << "ERROR: one of policy name or user name is empty"
<< dendl;
return -EINVAL;
}
return 0;
}
void RGWGetUserPolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(user_name));
op_ret = user->read_attrs(s, s->yield);
if (op_ret == -ENOENT) {
ldpp_dout(this, 0) << "ERROR: attrs not found for user" << user_name << dendl;
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
if (op_ret == 0) {
s->formatter->open_object_section("GetUserPolicyResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("GetUserPolicyResult");
std::map<std::string, std::string> policies;
if (auto it = user->get_attrs().find(RGW_ATTR_USER_POLICY); it != user->get_attrs().end()) {
bufferlist bl = it->second;
try {
decode(policies, bl);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode user policies" << dendl;
op_ret = -EIO;
return;
}
if (auto it = policies.find(policy_name); it != policies.end()) {
policy = policies[policy_name];
dump(s->formatter);
} else {
ldpp_dout(this, 0) << "ERROR: policy not found" << policy << dendl;
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
} else {
ldpp_dout(this, 0) << "ERROR: RGW_ATTR_USER_POLICY not found" << dendl;
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
s->formatter->close_section();
s->formatter->close_section();
}
if (op_ret < 0) {
op_ret = -ERR_INTERNAL_ERROR;
}
}
uint64_t RGWListUserPolicies::get_op()
{
return rgw::IAM::iamListUserPolicies;
}
int RGWListUserPolicies::get_params()
{
user_name = s->info.args.get("UserName");
if (user_name.empty()) {
ldpp_dout(this, 20) << "ERROR: user name is empty" << dendl;
return -EINVAL;
}
return 0;
}
void RGWListUserPolicies::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(user_name));
op_ret = user->read_attrs(s, s->yield);
if (op_ret == -ENOENT) {
ldpp_dout(this, 0) << "ERROR: attrs not found for user" << user_name << dendl;
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
if (op_ret == 0) {
std::map<std::string, std::string> policies;
if (auto it = user->get_attrs().find(RGW_ATTR_USER_POLICY); it != user->get_attrs().end()) {
s->formatter->open_object_section("ListUserPoliciesResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->open_object_section("ListUserPoliciesResult");
bufferlist bl = it->second;
try {
decode(policies, bl);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode user policies" << dendl;
op_ret = -EIO;
return;
}
s->formatter->open_object_section("PolicyNames");
for (const auto& p : policies) {
s->formatter->dump_string("member", p.first);
}
s->formatter->close_section();
s->formatter->close_section();
s->formatter->close_section();
} else {
ldpp_dout(this, 0) << "ERROR: RGW_ATTR_USER_POLICY not found" << dendl;
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
}
if (op_ret < 0) {
op_ret = -ERR_INTERNAL_ERROR;
}
}
uint64_t RGWDeleteUserPolicy::get_op()
{
return rgw::IAM::iamDeleteUserPolicy;
}
int RGWDeleteUserPolicy::get_params()
{
policy_name = s->info.args.get("PolicyName");
user_name = s->info.args.get("UserName");
if (policy_name.empty() || user_name.empty()) {
ldpp_dout(this, 20) << "ERROR: One of policy name or user name is empty"<< dendl;
return -EINVAL;
}
return 0;
}
void RGWDeleteUserPolicy::execute(optional_yield y)
{
op_ret = get_params();
if (op_ret < 0) {
return;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(user_name));
op_ret = user->load_user(s, s->yield);
if (op_ret < 0) {
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
op_ret = user->read_attrs(this, s->yield);
if (op_ret == -ENOENT) {
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
ceph::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) {
// a policy might've been uploaded to this site when there was no sync
// req. in earlier releases, proceed deletion
if (op_ret != -ENOENT) {
ldpp_dout(this, 5) << "forward_request_to_master returned ret=" << op_ret << dendl;
return;
}
ldpp_dout(this, 0) << "ERROR: forward_request_to_master returned ret=" << op_ret << dendl;
}
std::map<std::string, std::string> policies;
if (auto it = user->get_attrs().find(RGW_ATTR_USER_POLICY); it != user->get_attrs().end()) {
bufferlist out_bl = it->second;
try {
decode(policies, out_bl);
} catch (buffer::error& err) {
ldpp_dout(this, 0) << "ERROR: failed to decode user policies" << dendl;
op_ret = -EIO;
return;
}
if (auto p = policies.find(policy_name); p != policies.end()) {
bufferlist in_bl;
policies.erase(p);
encode(policies, in_bl);
user->get_attrs()[RGW_ATTR_USER_POLICY] = in_bl;
op_ret = user->store_user(s, s->yield, false);
if (op_ret < 0) {
op_ret = -ERR_INTERNAL_ERROR;
}
if (op_ret == 0) {
s->formatter->open_object_section("DeleteUserPoliciesResponse");
s->formatter->open_object_section("ResponseMetadata");
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->close_section();
s->formatter->close_section();
}
} else {
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
} else {
op_ret = -ERR_NO_SUCH_ENTITY;
return;
}
}
| 11,601 | 27.024155 | 105 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_user_policy.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include "rgw_rest.h"
class RGWRestUserPolicy : public RGWRESTOp {
protected:
static constexpr int MAX_POLICY_NAME_LEN = 128;
std::string policy_name;
std::string user_name;
std::string policy;
bool validate_input();
public:
int verify_permission(optional_yield y) override;
virtual uint64_t get_op() = 0;
void send_response() override;
void dump(Formatter *f) const;
};
class RGWUserPolicyRead : public RGWRestUserPolicy {
public:
RGWUserPolicyRead() = default;
int check_caps(const RGWUserCaps& caps) override;
};
class RGWUserPolicyWrite : public RGWRestUserPolicy {
public:
RGWUserPolicyWrite() = default;
int check_caps(const RGWUserCaps& caps) override;
};
class RGWPutUserPolicy : public RGWUserPolicyWrite {
public:
RGWPutUserPolicy() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "put_user-policy"; }
uint64_t get_op() override;
RGWOpType get_type() override { return RGW_OP_PUT_USER_POLICY; }
};
class RGWGetUserPolicy : public RGWUserPolicyRead {
public:
RGWGetUserPolicy() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "get_user_policy"; }
uint64_t get_op() override;
RGWOpType get_type() override { return RGW_OP_GET_USER_POLICY; }
};
class RGWListUserPolicies : public RGWUserPolicyRead {
public:
RGWListUserPolicies() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "list_user_policies"; }
uint64_t get_op() override;
RGWOpType get_type() override { return RGW_OP_LIST_USER_POLICIES; }
};
class RGWDeleteUserPolicy : public RGWUserPolicyWrite {
public:
RGWDeleteUserPolicy() = default;
void execute(optional_yield y) override;
int get_params();
const char* name() const override { return "delete_user_policy"; }
uint64_t get_op() override;
RGWOpType get_type() override { return RGW_OP_DELETE_USER_POLICY; }
};
| 2,127 | 27.756757 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_rest_zero.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
*
* 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_rest_zero.h"
#include <mutex>
#include <vector>
#include "common/strtol.h"
namespace rgw {
// all paths refer to a single resource that contains only a size
class ZeroResource {
public:
std::mutex mutex;
std::size_t size = 0;
};
// base op
class ZeroOp : public RGWOp {
protected:
ZeroResource* const resource;
const char* response_content_type = nullptr;
int64_t response_content_length = NO_CONTENT_LENGTH;
public:
explicit ZeroOp(ZeroResource* resource) : resource(resource) {}
int verify_permission(optional_yield y) override { return 0; }
void send_response() override;
};
void ZeroOp::send_response()
{
if (op_ret) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
end_header(s, this, response_content_type, response_content_length);
}
// DELETE op resets resource size to 0
class ZeroDeleteOp : public ZeroOp {
public:
explicit ZeroDeleteOp(ZeroResource* resource) : ZeroOp(resource) {}
const char* name() const override { return "zero_delete"; }
void execute(optional_yield y) override;
};
void ZeroDeleteOp::execute(optional_yield y)
{
auto lock = std::scoped_lock(resource->mutex);
resource->size = 0;
}
// GET op returns a request body of all zeroes
class ZeroGetOp : public ZeroOp {
public:
explicit ZeroGetOp(ZeroResource* resource) : ZeroOp(resource) {}
const char* name() const override { return "zero_get"; }
void execute(optional_yield y) override;
void send_response() override;
};
void ZeroGetOp::execute(optional_yield y)
{
response_content_type = "application/octet-stream";
auto lock = std::scoped_lock(resource->mutex);
response_content_length = resource->size;
}
void ZeroGetOp::send_response()
{
// send the response header
ZeroOp::send_response();
// write zeroes for the entire response body
size_t remaining = static_cast<size_t>(response_content_length);
const size_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
std::vector<char> zeroes;
zeroes.resize(std::min(remaining, chunk_size), '\0');
try {
while (remaining) {
const size_t count = std::min(zeroes.size(), remaining);
const int bytes = dump_body(s, zeroes.data(), count);
remaining -= bytes;
}
} catch (const std::exception& e) {
ldpp_dout(this, 0) << "recv_body failed with " << e.what() << dendl;
op_ret = -EIO;
return;
}
}
// HEAD op returns the current content length
class ZeroHeadOp : public ZeroOp {
public:
explicit ZeroHeadOp(ZeroResource* resource) : ZeroOp(resource) {}
const char* name() const override { return "zero_head"; }
void execute(optional_yield y) override;
};
void ZeroHeadOp::execute(optional_yield y)
{
response_content_type = "application/octet-stream";
auto lock = std::scoped_lock(resource->mutex);
response_content_length = resource->size;
}
// PUT op discards the entire request body then updates the content length
class ZeroPutOp : public ZeroOp {
public:
explicit ZeroPutOp(ZeroResource* resource) : ZeroOp(resource) {}
const char* name() const override { return "zero_put"; }
void execute(optional_yield y) override;
};
void ZeroPutOp::execute(optional_yield y)
{
if (!s->length) {
ldpp_dout(this, 0) << "missing content length" << dendl;
op_ret = -ERR_LENGTH_REQUIRED;
return;
}
const auto content_length = ceph::parse<size_t>(s->length);
if (!content_length) {
ldpp_dout(this, 0) << "failed to parse content length \""
<< s->length << '"' << dendl;
op_ret = -EINVAL;
return;
}
// read and discard the entire request body
size_t remaining = *content_length;
const size_t chunk_size = s->cct->_conf->rgw_max_chunk_size;
std::vector<char> buffer;
buffer.resize(std::min(remaining, chunk_size));
try {
while (remaining) {
const size_t count = std::min(buffer.size(), remaining);
const int bytes = recv_body(s, buffer.data(), count);
remaining -= bytes;
}
} catch (const std::exception& e) {
ldpp_dout(this, 0) << "recv_body failed with " << e.what() << dendl;
op_ret = -EIO;
return;
}
// on success, update the resource size
auto lock = std::scoped_lock(resource->mutex);
resource->size = *content_length;
}
class ZeroHandler : public RGWHandler_REST {
ZeroResource* const resource;
public:
explicit ZeroHandler(ZeroResource* resource) : resource(resource) {}
int init_permissions(RGWOp*, optional_yield) override { return 0; }
int read_permissions(RGWOp*, optional_yield) override { return 0; }
int authorize(const DoutPrefixProvider* dpp, optional_yield y) override { return 0; }
int postauth_init(optional_yield y) override { return 0; }
// op factory functions
RGWOp* op_delete() override { return new ZeroDeleteOp(resource); }
RGWOp* op_get() override { return new ZeroGetOp(resource); }
RGWOp* op_head() override { return new ZeroHeadOp(resource); }
RGWOp* op_put() override { return new ZeroPutOp(resource); }
};
RESTMgr_Zero::RESTMgr_Zero() : resource(std::make_unique<ZeroResource>()) {}
RGWHandler_REST* RESTMgr_Zero::get_handler(sal::Driver* driver, req_state* s,
const auth::StrategyRegistry& auth,
const std::string& prefix)
{
return new ZeroHandler(resource.get());
}
} // namespace rgw
| 5,689 | 27.592965 | 87 |
cc
|
null |
ceph-main/src/rgw/rgw_rest_zero.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
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <memory>
#include "rgw_rest.h"
namespace rgw {
class ZeroResource;
// a rest endpoint that's only useful for benchmarking the http frontend.
// requests are not authenticated, and do no reads/writes to the backend
class RESTMgr_Zero : public RGWRESTMgr {
std::unique_ptr<ZeroResource> resource;
public:
RESTMgr_Zero();
RGWHandler_REST* get_handler(sal::Driver* driver, req_state* s,
const auth::StrategyRegistry& auth,
const std::string& prefix) override;
};
} // namespace rgw
| 947 | 26.085714 | 73 |
h
|
null |
ceph-main/src/rgw/rgw_role.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 <boost/algorithm/string/replace.hpp>
#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_role.h"
#include "services/svc_zone.h"
#include "services/svc_sys_obj.h"
#include "services/svc_meta_be_sobj.h"
#include "services/svc_meta.h"
#include "services/svc_role_rados.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw { namespace sal {
const string RGWRole::role_name_oid_prefix = "role_names.";
const string RGWRole::role_oid_prefix = "roles.";
const string RGWRole::role_path_oid_prefix = "role_paths.";
const string RGWRole::role_arn_prefix = "arn:aws:iam::";
void RGWRoleInfo::dump(Formatter *f) const
{
encode_json("RoleId", id , f);
std::string role_name;
if (tenant.empty()) {
role_name = name;
} else {
role_name = tenant + '$' + name;
}
encode_json("RoleName", role_name , f);
encode_json("Path", path, f);
encode_json("Arn", arn, f);
encode_json("CreateDate", creation_date, f);
encode_json("MaxSessionDuration", max_session_duration, f);
encode_json("AssumeRolePolicyDocument", trust_policy, f);
if (!perm_policy_map.empty()) {
f->open_array_section("PermissionPolicies");
for (const auto& it : perm_policy_map) {
f->open_object_section("Policy");
encode_json("PolicyName", it.first, f);
encode_json("PolicyValue", it.second, f);
f->close_section();
}
f->close_section();
}
if (!tags.empty()) {
f->open_array_section("Tags");
for (const auto& it : tags) {
f->open_object_section("Tag");
encode_json("Key", it.first, f);
encode_json("Value", it.second, f);
f->close_section();
}
f->close_section();
}
}
void RGWRoleInfo::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("RoleId", id, obj);
JSONDecoder::decode_json("RoleName", name, obj);
JSONDecoder::decode_json("Path", path, obj);
JSONDecoder::decode_json("Arn", arn, obj);
JSONDecoder::decode_json("CreateDate", creation_date, obj);
JSONDecoder::decode_json("MaxSessionDuration", max_session_duration, obj);
JSONDecoder::decode_json("AssumeRolePolicyDocument", trust_policy, obj);
auto tags_iter = obj->find_first("Tags");
if (!tags_iter.end()) {
JSONObj* tags_json = *tags_iter;
auto iter = tags_json->find_first();
for (; !iter.end(); ++iter) {
std::string key, val;
JSONDecoder::decode_json("Key", key, *iter);
JSONDecoder::decode_json("Value", val, *iter);
this->tags.emplace(key, val);
}
}
auto perm_policy_iter = obj->find_first("PermissionPolicies");
if (!perm_policy_iter.end()) {
JSONObj* perm_policies = *perm_policy_iter;
auto iter = perm_policies->find_first();
for (; !iter.end(); ++iter) {
std::string policy_name, policy_val;
JSONDecoder::decode_json("PolicyName", policy_name, *iter);
JSONDecoder::decode_json("PolicyValue", policy_val, *iter);
this->perm_policy_map.emplace(policy_name, policy_val);
}
}
if (auto pos = name.find('$'); pos != std::string::npos) {
tenant = name.substr(0, pos);
name = name.substr(pos+1);
}
}
RGWRole::RGWRole(std::string name,
std::string tenant,
std::string path,
std::string trust_policy,
std::string max_session_duration_str,
std::multimap<std::string,std::string> tags)
{
info.name = std::move(name);
info.path = std::move(path);
info.trust_policy = std::move(trust_policy);
info.tenant = std::move(tenant);
info.tags = std::move(tags);
if (this->info.path.empty())
this->info.path = "/";
extract_name_tenant(this->info.name);
if (max_session_duration_str.empty()) {
info.max_session_duration = SESSION_DURATION_MIN;
} else {
info.max_session_duration = std::stoull(max_session_duration_str);
}
info.mtime = real_time();
}
RGWRole::RGWRole(std::string id)
{
info.id = std::move(id);
}
int RGWRole::get(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = read_name(dpp, y);
if (ret < 0) {
return ret;
}
ret = read_info(dpp, y);
if (ret < 0) {
return ret;
}
return 0;
}
int RGWRole::get_by_id(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = read_info(dpp, y);
if (ret < 0) {
return ret;
}
return 0;
}
void RGWRole::dump(Formatter *f) const
{
info.dump(f);
}
void RGWRole::decode_json(JSONObj *obj)
{
info.decode_json(obj);
}
bool RGWRole::validate_max_session_duration(const DoutPrefixProvider* dpp)
{
if (info.max_session_duration < SESSION_DURATION_MIN ||
info.max_session_duration > SESSION_DURATION_MAX) {
ldpp_dout(dpp, 0) << "ERROR: Invalid session duration, should be between 3600 and 43200 seconds " << dendl;
return false;
}
return true;
}
bool RGWRole::validate_input(const DoutPrefixProvider* dpp)
{
if (info.name.length() > MAX_ROLE_NAME_LEN) {
ldpp_dout(dpp, 0) << "ERROR: Invalid name length " << dendl;
return false;
}
if (info.path.length() > MAX_PATH_NAME_LEN) {
ldpp_dout(dpp, 0) << "ERROR: Invalid path length " << dendl;
return false;
}
std::regex regex_name("[A-Za-z0-9:=,.@-]+");
if (! std::regex_match(info.name, regex_name)) {
ldpp_dout(dpp, 0) << "ERROR: Invalid chars in name " << dendl;
return false;
}
std::regex regex_path("(/[!-~]+/)|(/)");
if (! std::regex_match(info.path,regex_path)) {
ldpp_dout(dpp, 0) << "ERROR: Invalid chars in path " << dendl;
return false;
}
if (!validate_max_session_duration(dpp)) {
return false;
}
return true;
}
void RGWRole::extract_name_tenant(const std::string& str) {
if (auto pos = str.find('$');
pos != std::string::npos) {
info.tenant = str.substr(0, pos);
info.name = str.substr(pos+1);
}
}
int RGWRole::update(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = store_info(dpp, false, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: storing info in Role pool: "
<< info.id << ": " << cpp_strerror(-ret) << dendl;
return ret;
}
return 0;
}
void RGWRole::set_perm_policy(const string& policy_name, const string& perm_policy)
{
info.perm_policy_map[policy_name] = perm_policy;
}
vector<string> RGWRole::get_role_policy_names()
{
vector<string> policy_names;
for (const auto& it : info.perm_policy_map)
{
policy_names.push_back(std::move(it.first));
}
return policy_names;
}
int RGWRole::get_role_policy(const DoutPrefixProvider* dpp, const string& policy_name, string& perm_policy)
{
const auto it = info.perm_policy_map.find(policy_name);
if (it == info.perm_policy_map.end()) {
ldpp_dout(dpp, 0) << "ERROR: Policy name: " << policy_name << " not found" << dendl;
return -ENOENT;
} else {
perm_policy = it->second;
}
return 0;
}
int RGWRole::delete_policy(const DoutPrefixProvider* dpp, const string& policy_name)
{
const auto& it = info.perm_policy_map.find(policy_name);
if (it == info.perm_policy_map.end()) {
ldpp_dout(dpp, 0) << "ERROR: Policy name: " << policy_name << " not found" << dendl;
return -ENOENT;
} else {
info.perm_policy_map.erase(it);
}
return 0;
}
void RGWRole::update_trust_policy(string& trust_policy)
{
this->info.trust_policy = trust_policy;
}
int RGWRole::set_tags(const DoutPrefixProvider* dpp, const multimap<string,string>& tags_map)
{
for (auto& it : tags_map) {
this->info.tags.emplace(it.first, it.second);
}
if (this->info.tags.size() > 50) {
ldpp_dout(dpp, 0) << "No. of tags is greater than 50" << dendl;
return -EINVAL;
}
return 0;
}
boost::optional<multimap<string,string>> RGWRole::get_tags()
{
if(this->info.tags.empty()) {
return boost::none;
}
return this->info.tags;
}
void RGWRole::erase_tags(const vector<string>& tagKeys)
{
for (auto& it : tagKeys) {
this->info.tags.erase(it);
}
}
void RGWRole::update_max_session_duration(const std::string& max_session_duration_str)
{
if (max_session_duration_str.empty()) {
info.max_session_duration = SESSION_DURATION_MIN;
} else {
info.max_session_duration = std::stoull(max_session_duration_str);
}
}
const string& RGWRole::get_names_oid_prefix()
{
return role_name_oid_prefix;
}
const string& RGWRole::get_info_oid_prefix()
{
return role_oid_prefix;
}
const string& RGWRole::get_path_oid_prefix()
{
return role_path_oid_prefix;
}
RGWRoleMetadataHandler::RGWRoleMetadataHandler(Driver* driver,
RGWSI_Role_RADOS *role_svc)
{
this->driver = driver;
base_init(role_svc->ctx(), role_svc->get_be_handler());
}
RGWMetadataObject *RGWRoleMetadataHandler::get_meta_obj(JSONObj *jo,
const obj_version& objv,
const ceph::real_time& mtime)
{
RGWRoleInfo info;
try {
info.decode_json(jo);
} catch (JSONDecoder:: err& e) {
return nullptr;
}
return new RGWRoleMetadataObject(info, objv, mtime, driver);
}
int RGWRoleMetadataHandler::do_get(RGWSI_MetaBackend_Handler::Op *op,
std::string& entry,
RGWMetadataObject **obj,
optional_yield y,
const DoutPrefixProvider *dpp)
{
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(entry);
int ret = role->read_info(dpp, y);
if (ret < 0) {
return ret;
}
RGWObjVersionTracker objv_tracker = role->get_objv_tracker();
real_time mtime = role->get_mtime();
RGWRoleInfo info = role->get_info();
RGWRoleMetadataObject *rdo = new RGWRoleMetadataObject(info, objv_tracker.read_version,
mtime, driver);
*obj = rdo;
return 0;
}
int RGWRoleMetadataHandler::do_remove(RGWSI_MetaBackend_Handler::Op *op,
std::string& entry,
RGWObjVersionTracker& objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp)
{
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(entry);
int ret = role->read_info(dpp, y);
if (ret < 0) {
return ret == -ENOENT? 0 : ret;
}
return role->delete_obj(dpp, y);
}
class RGWMetadataHandlerPut_Role : public RGWMetadataHandlerPut_SObj
{
RGWRoleMetadataHandler *rhandler;
RGWRoleMetadataObject *mdo;
public:
RGWMetadataHandlerPut_Role(RGWRoleMetadataHandler *handler,
RGWSI_MetaBackend_Handler::Op *op,
std::string& entry,
RGWMetadataObject *obj,
RGWObjVersionTracker& objv_tracker,
optional_yield y,
RGWMDLogSyncType type,
bool from_remote_zone) :
RGWMetadataHandlerPut_SObj(handler, op, entry, obj, objv_tracker, y, type, from_remote_zone),
rhandler(handler) {
mdo = static_cast<RGWRoleMetadataObject*>(obj);
}
int put_checked(const DoutPrefixProvider *dpp) override {
auto& info = mdo->get_role_info();
auto mtime = mdo->get_mtime();
auto* driver = mdo->get_driver();
info.mtime = mtime;
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(info);
int ret = role->create(dpp, true, info.id, y);
if (ret == -EEXIST) {
ret = role->update(dpp, y);
}
return ret < 0 ? ret : STATUS_APPLIED;
}
};
int RGWRoleMetadataHandler::do_put(RGWSI_MetaBackend_Handler::Op *op,
std::string& entry,
RGWMetadataObject *obj,
RGWObjVersionTracker& objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp,
RGWMDLogSyncType type,
bool from_remote_zone)
{
RGWMetadataHandlerPut_Role put_op(this, op , entry, obj, objv_tracker, y, type, from_remote_zone);
return do_put_operate(&put_op, dpp);
}
} } // namespace rgw::sal
| 12,464 | 27.011236 | 111 |
cc
|
null |
ceph-main/src/rgw/rgw_role.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/async/yield_context.h"
#include "common/ceph_json.h"
#include "common/ceph_context.h"
#include "rgw_rados.h"
#include "rgw_metadata.h"
class RGWRados;
namespace rgw { namespace sal {
struct RGWRoleInfo
{
std::string id;
std::string name;
std::string path;
std::string arn;
std::string creation_date;
std::string trust_policy;
std::map<std::string, std::string> perm_policy_map;
std::string tenant;
uint64_t max_session_duration;
std::multimap<std::string,std::string> tags;
std::map<std::string, bufferlist> attrs;
RGWObjVersionTracker objv_tracker;
real_time mtime;
RGWRoleInfo() = default;
~RGWRoleInfo() = default;
void encode(bufferlist& bl) const {
ENCODE_START(3, 1, bl);
encode(id, bl);
encode(name, bl);
encode(path, bl);
encode(arn, bl);
encode(creation_date, bl);
encode(trust_policy, bl);
encode(perm_policy_map, bl);
encode(tenant, bl);
encode(max_session_duration, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(3, bl);
decode(id, bl);
decode(name, bl);
decode(path, bl);
decode(arn, bl);
decode(creation_date, bl);
decode(trust_policy, bl);
decode(perm_policy_map, bl);
if (struct_v >= 2) {
decode(tenant, bl);
}
if (struct_v >= 3) {
decode(max_session_duration, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(RGWRoleInfo)
class RGWRole
{
public:
static const std::string role_name_oid_prefix;
static const std::string role_oid_prefix;
static const std::string role_path_oid_prefix;
static const std::string role_arn_prefix;
static constexpr int MAX_ROLE_NAME_LEN = 64;
static constexpr int MAX_PATH_NAME_LEN = 512;
static constexpr uint64_t SESSION_DURATION_MIN = 3600; // in seconds
static constexpr uint64_t SESSION_DURATION_MAX = 43200; // in seconds
protected:
RGWRoleInfo info;
public:
virtual int store_info(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y) = 0;
virtual int store_name(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y) = 0;
virtual int store_path(const DoutPrefixProvider *dpp, bool exclusive, optional_yield y) = 0;
virtual int read_id(const DoutPrefixProvider *dpp, const std::string& role_name, const std::string& tenant, std::string& role_id, optional_yield y) = 0;
virtual int read_name(const DoutPrefixProvider *dpp, optional_yield y) = 0;
virtual int read_info(const DoutPrefixProvider *dpp, optional_yield y) = 0;
bool validate_max_session_duration(const DoutPrefixProvider* dpp);
bool validate_input(const DoutPrefixProvider* dpp);
void extract_name_tenant(const std::string& str);
RGWRole(std::string name,
std::string tenant,
std::string path="",
std::string trust_policy="",
std::string max_session_duration_str="",
std::multimap<std::string,std::string> tags={});
explicit RGWRole(std::string id);
explicit RGWRole(const RGWRoleInfo& info) : info(info) {}
RGWRole() = default;
virtual ~RGWRole() = default;
const std::string& get_id() const { return info.id; }
const std::string& get_name() const { return info.name; }
const std::string& get_tenant() const { return info.tenant; }
const std::string& get_path() const { return info.path; }
const std::string& get_create_date() const { return info.creation_date; }
const std::string& get_assume_role_policy() const { return info.trust_policy;}
const uint64_t& get_max_session_duration() const { return info.max_session_duration; }
const RGWObjVersionTracker& get_objv_tracker() const { return info.objv_tracker; }
const real_time& get_mtime() const { return info.mtime; }
std::map<std::string, bufferlist>& get_attrs() { return info.attrs; }
RGWRoleInfo& get_info() { return info; }
void set_id(const std::string& id) { this->info.id = id; }
void set_mtime(const real_time& mtime) { this->info.mtime = mtime; }
virtual int create(const DoutPrefixProvider *dpp, bool exclusive, const std::string &role_id, optional_yield y) = 0;
virtual int delete_obj(const DoutPrefixProvider *dpp, optional_yield y) = 0;
int get(const DoutPrefixProvider *dpp, optional_yield y);
int get_by_id(const DoutPrefixProvider *dpp, optional_yield y);
int update(const DoutPrefixProvider *dpp, optional_yield y);
void update_trust_policy(std::string& trust_policy);
void set_perm_policy(const std::string& policy_name, const std::string& perm_policy);
std::vector<std::string> get_role_policy_names();
int get_role_policy(const DoutPrefixProvider* dpp, const std::string& policy_name, std::string& perm_policy);
int delete_policy(const DoutPrefixProvider* dpp, const std::string& policy_name);
int set_tags(const DoutPrefixProvider* dpp, const std::multimap<std::string,std::string>& tags_map);
boost::optional<std::multimap<std::string,std::string>> get_tags();
void erase_tags(const std::vector<std::string>& tagKeys);
void update_max_session_duration(const std::string& max_session_duration_str);
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
static const std::string& get_names_oid_prefix();
static const std::string& get_info_oid_prefix();
static const std::string& get_path_oid_prefix();
};
class RGWRoleMetadataObject: public RGWMetadataObject {
RGWRoleInfo info;
Driver* driver;
public:
RGWRoleMetadataObject() = default;
RGWRoleMetadataObject(RGWRoleInfo& info,
const obj_version& v,
real_time m,
Driver* driver) : RGWMetadataObject(v,m), info(info), driver(driver) {}
void dump(Formatter *f) const override {
info.dump(f);
}
RGWRoleInfo& get_role_info() {
return info;
}
Driver* get_driver() {
return driver;
}
};
class RGWRoleMetadataHandler: public RGWMetadataHandler_GenericMetaBE
{
public:
RGWRoleMetadataHandler(Driver* driver, RGWSI_Role_RADOS *role_svc);
std::string get_type() final { return "roles"; }
RGWMetadataObject *get_meta_obj(JSONObj *jo,
const obj_version& objv,
const ceph::real_time& mtime);
int do_get(RGWSI_MetaBackend_Handler::Op *op,
std::string& entry,
RGWMetadataObject **obj,
optional_yield y,
const DoutPrefixProvider *dpp) final;
int do_remove(RGWSI_MetaBackend_Handler::Op *op,
std::string& entry,
RGWObjVersionTracker& objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp) final;
int do_put(RGWSI_MetaBackend_Handler::Op *op,
std::string& entr,
RGWMetadataObject *obj,
RGWObjVersionTracker& objv_tracker,
optional_yield y,
const DoutPrefixProvider *dpp,
RGWMDLogSyncType type,
bool from_remote_zone) override;
private:
Driver* driver;
};
} } // namespace rgw::sal
| 7,005 | 32.361905 | 154 |
h
|
null |
ceph-main/src/rgw/rgw_s3select.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_s3select_private.h"
#define dout_subsys ceph_subsys_rgw
namespace rgw::s3select {
RGWOp* create_s3select_op()
{
return new RGWSelectObj_ObjStore_S3();
}
};
using namespace s3selectEngine;
std::string& aws_response_handler::get_sql_result()
{
return sql_result;
}
uint64_t aws_response_handler::get_processed_size()
{
return processed_size;
}
void aws_response_handler::update_processed_size(uint64_t value)
{
processed_size += value;
}
uint64_t aws_response_handler::get_total_bytes_returned()
{
return total_bytes_returned;
}
void aws_response_handler::update_total_bytes_returned(uint64_t value)
{
total_bytes_returned = value;
}
void aws_response_handler::push_header(const char* header_name, const char* header_value)
{
char x;
short s;
x = char(strlen(header_name));
m_buff_header.append(&x, sizeof(x));
m_buff_header.append(header_name);
x = char(7);
m_buff_header.append(&x, sizeof(x));
s = htons(uint16_t(strlen(header_value)));
m_buff_header.append(reinterpret_cast<char*>(&s), sizeof(s));
m_buff_header.append(header_value);
}
#define IDX( x ) static_cast<int>( x )
int aws_response_handler::create_header_records()
{
//headers description(AWS)
//[header-name-byte-length:1][header-name:variable-length][header-value-type:1][header-value:variable-length]
//1
push_header(header_name_str[IDX(header_name_En::EVENT_TYPE)], header_value_str[IDX(header_value_En::RECORDS)]);
//2
push_header(header_name_str[IDX(header_name_En::CONTENT_TYPE)], header_value_str[IDX(header_value_En::OCTET_STREAM)]);
//3
push_header(header_name_str[IDX(header_name_En::MESSAGE_TYPE)], header_value_str[IDX(header_value_En::EVENT)]);
return m_buff_header.size();
}
int aws_response_handler::create_header_continuation()
{
//headers description(AWS)
//1
push_header(header_name_str[IDX(header_name_En::EVENT_TYPE)], header_value_str[IDX(header_value_En::CONT)]);
//2
push_header(header_name_str[IDX(header_name_En::MESSAGE_TYPE)], header_value_str[IDX(header_value_En::EVENT)]);
return m_buff_header.size();
}
int aws_response_handler::create_header_progress()
{
//headers description(AWS)
//1
push_header(header_name_str[IDX(header_name_En::EVENT_TYPE)], header_value_str[IDX(header_value_En::PROGRESS)]);
//2
push_header(header_name_str[IDX(header_name_En::CONTENT_TYPE)], header_value_str[IDX(header_value_En::XML)]);
//3
push_header(header_name_str[IDX(header_name_En::MESSAGE_TYPE)], header_value_str[IDX(header_value_En::EVENT)]);
return m_buff_header.size();
}
int aws_response_handler::create_header_stats()
{
//headers description(AWS)
//1
push_header(header_name_str[IDX(header_name_En::EVENT_TYPE)], header_value_str[IDX(header_value_En::STATS)]);
//2
push_header(header_name_str[IDX(header_name_En::CONTENT_TYPE)], header_value_str[IDX(header_value_En::XML)]);
//3
push_header(header_name_str[IDX(header_name_En::MESSAGE_TYPE)], header_value_str[IDX(header_value_En::EVENT)]);
return m_buff_header.size();
}
int aws_response_handler::create_header_end()
{
//headers description(AWS)
//1
push_header(header_name_str[IDX(header_name_En::EVENT_TYPE)], header_value_str[IDX(header_value_En::END)]);
//2
push_header(header_name_str[IDX(header_name_En::MESSAGE_TYPE)], header_value_str[IDX(header_value_En::EVENT)]);
return m_buff_header.size();
}
int aws_response_handler::create_error_header_records(const char* error_message)
{
//headers description(AWS)
//[header-name-byte-length:1][header-name:variable-length][header-value-type:1][header-value:variable-length]
//1
push_header(header_name_str[IDX(header_name_En::ERROR_CODE)], header_value_str[IDX(header_value_En::ENGINE_ERROR)]);
//2
push_header(header_name_str[IDX(header_name_En::ERROR_MESSAGE)], error_message);
//3
push_header(header_name_str[IDX(header_name_En::MESSAGE_TYPE)], header_value_str[IDX(header_value_En::ERROR_TYPE)]);
return m_buff_header.size();
}
int aws_response_handler::create_message(u_int32_t header_len)
{
//message description(AWS):
//[total-byte-length:4][header-byte-length:4][crc:4][headers:variable-length][payload:variable-length][crc:4]
//s3select result is produced into sql_result, the sql_result is also the response-message, thus the attach headers and CRC
//are created later to the produced SQL result, and actually wrapping the payload.
auto push_encode_int = [&](u_int32_t s, int pos) {
u_int32_t x = htonl(s);
sql_result.replace(pos, sizeof(x), reinterpret_cast<char*>(&x), sizeof(x));
};
u_int32_t total_byte_len = 0;
u_int32_t preload_crc = 0;
u_int32_t message_crc = 0;
total_byte_len = sql_result.size() + 4; //the total is greater in 4 bytes than current size
push_encode_int(total_byte_len, 0);
push_encode_int(header_len, 4);
crc32.reset();
crc32 = std::for_each(sql_result.data(), sql_result.data() + 8, crc32); //crc for starting 8 bytes
preload_crc = crc32();
push_encode_int(preload_crc, 8);
crc32.reset();
crc32 = std::for_each(sql_result.begin(), sql_result.end(), crc32); //crc for payload + checksum
message_crc = crc32();
u_int32_t x = htonl(message_crc);
sql_result.append(reinterpret_cast<char*>(&x), sizeof(x));
return sql_result.size();
}
void aws_response_handler::init_response()
{
//12 positions for header-crc
sql_result.resize(header_crc_size, '\0');
}
void aws_response_handler::init_success_response()
{
m_buff_header.clear();
header_size = create_header_records();
sql_result.append(m_buff_header.c_str(), header_size);
#ifdef PAYLOAD_TAG
sql_result.append(PAYLOAD_LINE);
#endif
}
void aws_response_handler::send_continuation_response()
{
sql_result.resize(header_crc_size, '\0');
m_buff_header.clear();
header_size = create_header_continuation();
sql_result.append(m_buff_header.c_str(), header_size);
int buff_len = create_message(header_size);
s->formatter->write_bin_data(sql_result.data(), buff_len);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void aws_response_handler::init_progress_response()
{
sql_result.resize(header_crc_size, '\0');
m_buff_header.clear();
header_size = create_header_progress();
sql_result.append(m_buff_header.c_str(), header_size);
}
void aws_response_handler::init_stats_response()
{
sql_result.resize(header_crc_size, '\0');
m_buff_header.clear();
header_size = create_header_stats();
sql_result.append(m_buff_header.c_str(), header_size);
}
void aws_response_handler::init_end_response()
{
sql_result.resize(header_crc_size, '\0');
m_buff_header.clear();
header_size = create_header_end();
sql_result.append(m_buff_header.c_str(), header_size);
int buff_len = create_message(header_size);
s->formatter->write_bin_data(sql_result.data(), buff_len);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void aws_response_handler::init_error_response(const char* error_message)
{
//currently not in use. the headers in the case of error, are not extracted by AWS-cli.
m_buff_header.clear();
header_size = create_error_header_records(error_message);
sql_result.append(m_buff_header.c_str(), header_size);
}
void aws_response_handler::send_success_response()
{
#ifdef PAYLOAD_TAG
sql_result.append(END_PAYLOAD_LINE);
#endif
int buff_len = create_message(header_size);
s->formatter->write_bin_data(sql_result.data(), buff_len);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void aws_response_handler::send_error_response(const char* error_code,
const char* error_message,
const char* resource_id)
{
set_req_state_err(s, 0);
dump_errno(s, 400);
end_header(s, m_rgwop, "application/xml", CHUNKED_TRANSFER_ENCODING);
dump_start(s);
s->formatter->open_object_section("Error");
s->formatter->dump_string("Code", error_code);
s->formatter->dump_string("Message", error_message);
s->formatter->dump_string("Resource", "#Resource#");
s->formatter->dump_string("RequestId", resource_id);
s->formatter->close_section();
rgw_flush_formatter_and_reset(s, s->formatter);
}
void aws_response_handler::send_progress_response()
{
std::string progress_payload = fmt::format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Progress><BytesScanned>{}</BytesScanned><BytesProcessed>{}</BytesProcessed><BytesReturned>{}</BytesReturned></Progress>"
, get_processed_size(), get_processed_size(), get_total_bytes_returned());
sql_result.append(progress_payload);
int buff_len = create_message(header_size);
s->formatter->write_bin_data(sql_result.data(), buff_len);
rgw_flush_formatter_and_reset(s, s->formatter);
}
void aws_response_handler::send_stats_response()
{
std::string stats_payload = fmt::format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Stats><BytesScanned>{}</BytesScanned><BytesProcessed>{}</BytesProcessed><BytesReturned>{}</BytesReturned></Stats>"
, get_processed_size(), get_processed_size(), get_total_bytes_returned());
sql_result.append(stats_payload);
int buff_len = create_message(header_size);
s->formatter->write_bin_data(sql_result.data(), buff_len);
rgw_flush_formatter_and_reset(s, s->formatter);
}
RGWSelectObj_ObjStore_S3::RGWSelectObj_ObjStore_S3():
m_buff_header(std::make_unique<char[]>(1000)),
m_scan_range_ind(false),
m_start_scan_sz(0),
m_end_scan_sz(0),
m_object_size_for_processing(0),
m_parquet_type(false),
m_json_type(false),
chunk_number(0),
m_requested_range(0),
m_scan_offset(1024),
m_skip_next_chunk(false),
m_is_trino_request(false)
{
set_get_data(true);
fp_get_obj_size = [&]() {
return get_obj_size();
};
fp_range_req = [&](int64_t start, int64_t len, void* buff, optional_yield* y) {
ldout(s->cct, 10) << "S3select: range-request start: " << start << " length: " << len << dendl;
auto status = range_request(start, len, buff, *y);
return status;
};
#ifdef _ARROW_EXIST
m_rgw_api.set_get_size_api(fp_get_obj_size);
m_rgw_api.set_range_req_api(fp_range_req);
#endif
fp_result_header_format = [this](std::string& result) {
m_aws_response_handler.init_response();
m_aws_response_handler.init_success_response();
return 0;
};
fp_s3select_result_format = [this](std::string& result) {
fp_chunked_transfer_encoding();
m_aws_response_handler.send_success_response();
return 0;
};
fp_debug_mesg = [&](const char* mesg){
ldpp_dout(this, 10) << mesg << dendl;
};
fp_chunked_transfer_encoding = [&](void){
if (chunk_number == 0) {
if (op_ret < 0) {
set_req_state_err(s, op_ret);
}
dump_errno(s);
// Explicitly use chunked transfer encoding so that we can stream the result
// to the user without having to wait for the full length of it.
end_header(s, this, "application/xml", CHUNKED_TRANSFER_ENCODING);
}
chunk_number++;
};
}
RGWSelectObj_ObjStore_S3::~RGWSelectObj_ObjStore_S3()
{}
int RGWSelectObj_ObjStore_S3::get_params(optional_yield y)
{
if(m_s3select_query.empty() == false) {
return 0;
}
#ifndef _ARROW_EXIST
m_parquet_type = false;
ldpp_dout(this, 10) << "arrow library is not installed" << dendl;
#endif
//retrieve s3-select query from payload
bufferlist data;
int ret;
int max_size = 4096;
std::tie(ret, data) = read_all_input(s, max_size, false);
if (ret != 0) {
ldpp_dout(this, 10) << "s3-select query: failed to retrieve query; ret = " << ret << dendl;
return ret;
}
m_s3select_query = data.to_str();
if (m_s3select_query.length() > 0) {
ldpp_dout(this, 10) << "s3-select query: " << m_s3select_query << dendl;
} else {
ldpp_dout(this, 10) << "s3-select query: failed to retrieve query;" << dendl;
return -1;
}
const auto& m = s->info.env->get_map();
auto user_agent = m.find("HTTP_USER_AGENT"); {
if (user_agent != m.end()){
if (user_agent->second.find("Trino") != std::string::npos){
m_is_trino_request = true;
ldpp_dout(this, 10) << "s3-select query: request sent by Trino." << dendl;
}
}
}
int status = handle_aws_cli_parameters(m_sql_query);
if (status<0) {
return status;
}
return RGWGetObj_ObjStore_S3::get_params(y);
}
int RGWSelectObj_ObjStore_S3::run_s3select_on_csv(const char* query, const char* input, size_t input_length)
{
int status = 0;
uint32_t length_before_processing, length_post_processing;
csv_object::csv_defintions csv;
const char* s3select_syntax_error = "s3select-Syntax-Error";
const char* s3select_resource_id = "resourcse-id";
const char* s3select_processTime_error = "s3select-ProcessingTime-Error";
s3select_syntax.parse_query(query);
if (m_row_delimiter.size()) {
csv.row_delimiter = *m_row_delimiter.c_str();
}
if (m_column_delimiter.size()) {
csv.column_delimiter = *m_column_delimiter.c_str();
}
if (m_quot.size()) {
csv.quot_char = *m_quot.c_str();
}
if (m_escape_char.size()) {
csv.escape_char = *m_escape_char.c_str();
}
if (output_row_delimiter.size()) {
csv.output_row_delimiter = *output_row_delimiter.c_str();
}
if (output_column_delimiter.size()) {
csv.output_column_delimiter = *output_column_delimiter.c_str();
}
if (output_quot.size()) {
csv.output_quot_char = *output_quot.c_str();
}
if (output_escape_char.size()) {
csv.output_escape_char = *output_escape_char.c_str();
}
if(output_quote_fields.compare("ALWAYS") == 0) {
csv.quote_fields_always = true;
} else if(output_quote_fields.compare("ASNEEDED") == 0) {
csv.quote_fields_asneeded = true;
}
if(m_header_info.compare("IGNORE")==0) {
csv.ignore_header_info=true;
} else if(m_header_info.compare("USE")==0) {
csv.use_header_info=true;
}
//m_s3_csv_object.set_external_debug_system(fp_debug_mesg);
m_s3_csv_object.set_result_formatters(fp_s3select_result_format,fp_result_header_format);
m_s3_csv_object.set_csv_query(&s3select_syntax, csv);
if (s3select_syntax.get_error_description().empty() == false) {
//error-flow (syntax-error)
m_aws_response_handler.send_error_response(s3select_syntax_error,
s3select_syntax.get_error_description().c_str(),
s3select_resource_id);
ldpp_dout(this, 10) << "s3-select query: failed to prase the following query {" << query << "}" << dendl;
ldpp_dout(this, 10) << "s3-select query: syntax-error {" << s3select_syntax.get_error_description() << "}" << dendl;
return -1;
} else {
if (input == nullptr) {
input = "";
}
fp_result_header_format(m_aws_response_handler.get_sql_result());
length_before_processing = m_s3_csv_object.get_return_result_size();
//query is correct(syntax), processing is starting.
status = m_s3_csv_object.run_s3select_on_stream(m_aws_response_handler.get_sql_result(), input, input_length, m_object_size_for_processing);
length_post_processing = m_s3_csv_object.get_return_result_size();
m_aws_response_handler.update_total_bytes_returned( m_s3_csv_object.get_return_result_size() );
if (status < 0) {
//error flow(processing-time)
m_aws_response_handler.send_error_response(s3select_processTime_error,
m_s3_csv_object.get_error_description().c_str(),
s3select_resource_id);
ldpp_dout(this, 10) << "s3-select query: failed to process query; {" << m_s3_csv_object.get_error_description() << "}" << dendl;
return -1;
}
}
if ((length_post_processing-length_before_processing) != 0) {
ldpp_dout(this, 10) << "s3-select: sql-result-size = " << m_aws_response_handler.get_sql_result().size() << dendl;
} else {
m_aws_response_handler.send_continuation_response();
}
if (enable_progress == true) {
fp_chunked_transfer_encoding();
m_aws_response_handler.init_progress_response();
m_aws_response_handler.send_progress_response();
}
return status;
}
int RGWSelectObj_ObjStore_S3::run_s3select_on_parquet(const char* query)
{
int status = 0;
#ifdef _ARROW_EXIST
if (!m_s3_parquet_object.is_set()) {
//parsing the SQL statement
s3select_syntax.parse_query(m_sql_query.c_str());
//m_s3_parquet_object.set_external_debug_system(fp_debug_mesg);
try {
//at this stage the Parquet-processing requires for the meta-data that reside on Parquet object
m_s3_parquet_object.set_parquet_object(std::string("s3object"), &s3select_syntax, &m_rgw_api);
} catch(base_s3select_exception& e) {
ldpp_dout(this, 10) << "S3select: failed upon parquet-reader construction: " << e.what() << dendl;
fp_result_header_format(m_aws_response_handler.get_sql_result());
m_aws_response_handler.get_sql_result().append(e.what());
fp_s3select_result_format(m_aws_response_handler.get_sql_result());
return -1;
}
}
if (s3select_syntax.get_error_description().empty() == false) {
//the SQL statement failed the syntax parser
fp_result_header_format(m_aws_response_handler.get_sql_result());
m_aws_response_handler.get_sql_result().append(s3select_syntax.get_error_description().data());
fp_s3select_result_format(m_aws_response_handler.get_sql_result());
ldpp_dout(this, 10) << "s3-select query: failed to prase query; {" << s3select_syntax.get_error_description() << "}" << dendl;
status = -1;
} else {
fp_result_header_format(m_aws_response_handler.get_sql_result());
//at this stage the Parquet-processing "takes control", it keep calling to s3-range-request according to the SQL statement.
status = m_s3_parquet_object.run_s3select_on_object(m_aws_response_handler.get_sql_result(), fp_s3select_result_format, fp_result_header_format);
if (status < 0) {
m_aws_response_handler.get_sql_result().append(m_s3_parquet_object.get_error_description());
fp_s3select_result_format(m_aws_response_handler.get_sql_result());
ldout(s->cct, 10) << "S3select: failure while execution" << m_s3_parquet_object.get_error_description() << dendl;
}
}
#endif
return status;
}
int RGWSelectObj_ObjStore_S3::run_s3select_on_json(const char* query, const char* input, size_t input_length)
{
int status = 0;
const char* s3select_processTime_error = "s3select-ProcessingTime-Error";
const char* s3select_syntax_error = "s3select-Syntax-Error";
const char* s3select_resource_id = "resourcse-id";
const char* s3select_json_error = "json-Format-Error";
m_aws_response_handler.init_response();
//the JSON data-type should be(currently) only DOCUMENT
if (m_json_datatype.compare("DOCUMENT") != 0) {
const char* s3select_json_error_msg = "s3-select query: wrong json dataType should use DOCUMENT; ";
m_aws_response_handler.send_error_response(s3select_json_error,
s3select_json_error_msg,
s3select_resource_id);
ldpp_dout(this, 10) << s3select_json_error_msg << dendl;
return -EINVAL;
}
//parsing the SQL statement
s3select_syntax.parse_query(m_sql_query.c_str());
if (s3select_syntax.get_error_description().empty() == false) {
//SQL statement is wrong(syntax).
m_aws_response_handler.send_error_response(s3select_syntax_error,
s3select_syntax.get_error_description().c_str(),
s3select_resource_id);
ldpp_dout(this, 10) << "s3-select query: failed to prase query; {" << s3select_syntax.get_error_description() << "}" << dendl;
return -EINVAL;
}
//initializing json processor
m_s3_json_object.set_json_query(&s3select_syntax);
if (input == nullptr) {
input = "";
}
m_aws_response_handler.init_success_response();
uint32_t length_before_processing = m_aws_response_handler.get_sql_result().size();
//query is correct(syntax), processing is starting.
try {
status = m_s3_json_object.run_s3select_on_stream(m_aws_response_handler.get_sql_result(), input, input_length, m_object_size_for_processing);
} catch(base_s3select_exception& e) {
ldpp_dout(this, 10) << "S3select: failed to process JSON object: " << e.what() << dendl;
m_aws_response_handler.get_sql_result().append(e.what());
m_aws_response_handler.send_error_response(s3select_processTime_error,
e.what(),
s3select_resource_id);
return -EINVAL;
}
uint32_t length_post_processing = m_aws_response_handler.get_sql_result().size();
m_aws_response_handler.update_total_bytes_returned(length_post_processing - length_before_processing);
if (status < 0) {
//error flow(processing-time)
m_aws_response_handler.send_error_response(s3select_processTime_error,
m_s3_json_object.get_error_description().c_str(),
s3select_resource_id);
ldpp_dout(this, 10) << "s3-select query: failed to process query; {" << m_s3_json_object.get_error_description() << "}" << dendl;
return -EINVAL;
}
fp_chunked_transfer_encoding();
if (length_post_processing-length_before_processing != 0) {
m_aws_response_handler.send_success_response();
} else {
m_aws_response_handler.send_continuation_response();
}
if (enable_progress == true) {
m_aws_response_handler.init_progress_response();
m_aws_response_handler.send_progress_response();
}
return status;
}
int RGWSelectObj_ObjStore_S3::handle_aws_cli_parameters(std::string& sql_query)
{
std::string input_tag{"InputSerialization"};
std::string output_tag{"OutputSerialization"};
if (chunk_number !=0) {
return 0;
}
#define GT ">"
#define LT "<"
#define APOS "'"
if (m_s3select_query.find(GT) != std::string::npos) {
boost::replace_all(m_s3select_query, GT, ">");
}
if (m_s3select_query.find(LT) != std::string::npos) {
boost::replace_all(m_s3select_query, LT, "<");
}
if (m_s3select_query.find(APOS) != std::string::npos) {
boost::replace_all(m_s3select_query, APOS, "'");
}
//AWS cli s3select parameters
if (m_s3select_query.find(input_tag+"><CSV") != std::string::npos) {
ldpp_dout(this, 10) << "s3select: engine is set to process CSV objects" << dendl;
}
else if (m_s3select_query.find(input_tag+"><JSON") != std::string::npos) {
m_json_type=true;
ldpp_dout(this, 10) << "s3select: engine is set to process JSON objects" << dendl;
} else if (m_s3select_query.find(input_tag+"><Parquet") != std::string::npos) {
m_parquet_type=true;
ldpp_dout(this, 10) << "s3select: engine is set to process Parquet objects" << dendl;
}
extract_by_tag(m_s3select_query, "Expression", sql_query);
extract_by_tag(m_s3select_query, "Enabled", m_enable_progress);
size_t _qi = m_s3select_query.find("<" + input_tag + ">", 0);
size_t _qe = m_s3select_query.find("</" + input_tag + ">", _qi);
m_s3select_input = m_s3select_query.substr(_qi + input_tag.size() + 2, _qe - (_qi + input_tag.size() + 2));
extract_by_tag(m_s3select_input, "FieldDelimiter", m_column_delimiter);
extract_by_tag(m_s3select_input, "QuoteCharacter", m_quot);
extract_by_tag(m_s3select_input, "RecordDelimiter", m_row_delimiter);
extract_by_tag(m_s3select_input, "FileHeaderInfo", m_header_info);
extract_by_tag(m_s3select_input, "Type", m_json_datatype);
if (m_row_delimiter.size()==0) {
m_row_delimiter='\n';
} else if (m_row_delimiter.compare(" ") == 0) {
//presto change
m_row_delimiter='\n';
}
extract_by_tag(m_s3select_input, "QuoteEscapeCharacter", m_escape_char);
extract_by_tag(m_s3select_input, "CompressionType", m_compression_type);
size_t _qo = m_s3select_query.find("<" + output_tag + ">", 0);
size_t _qs = m_s3select_query.find("</" + output_tag + ">", _qi);
m_s3select_output = m_s3select_query.substr(_qo + output_tag.size() + 2, _qs - (_qo + output_tag.size() + 2));
extract_by_tag(m_s3select_output, "FieldDelimiter", output_column_delimiter);
extract_by_tag(m_s3select_output, "QuoteCharacter", output_quot);
extract_by_tag(m_s3select_output, "QuoteEscapeCharacter", output_escape_char);
extract_by_tag(m_s3select_output, "QuoteFields", output_quote_fields);
extract_by_tag(m_s3select_output, "RecordDelimiter", output_row_delimiter);
if (output_row_delimiter.size()==0) {
output_row_delimiter='\n';
} else if (output_row_delimiter.compare(" ") == 0) {
//presto change
output_row_delimiter='\n';
}
if (m_compression_type.length()>0 && m_compression_type.compare("NONE") != 0) {
ldpp_dout(this, 10) << "RGW supports currently only NONE option for compression type" << dendl;
return -1;
}
extract_by_tag(m_s3select_query, "Start", m_start_scan);
extract_by_tag(m_s3select_query, "End", m_end_scan);
if (m_start_scan.size() || m_end_scan.size()) {
m_scan_range_ind = true;
if (m_start_scan.size()) {
m_start_scan_sz = std::stol(m_start_scan);
}
if (m_end_scan.size()) {
m_end_scan_sz = std::stol(m_end_scan);
} else {
m_end_scan_sz = std::numeric_limits<std::int64_t>::max();
}
}
if (m_enable_progress.compare("true")==0) {
enable_progress = true;
} else {
enable_progress = false;
}
return 0;
}
int RGWSelectObj_ObjStore_S3::extract_by_tag(std::string input, std::string tag_name, std::string& result)
{
result = "";
size_t _qs = input.find("<" + tag_name + ">", 0);
size_t qs_input = _qs + tag_name.size() + 2;
if (_qs == std::string::npos) {
return -1;
}
size_t _qe = input.find("</" + tag_name + ">", qs_input);
if (_qe == std::string::npos) {
return -1;
}
result = input.substr(qs_input, _qe - qs_input);
return 0;
}
size_t RGWSelectObj_ObjStore_S3::get_obj_size()
{
return s->obj_size;
}
int RGWSelectObj_ObjStore_S3::range_request(int64_t ofs, int64_t len, void* buff, optional_yield y)
{
//purpose: implementation for arrow::ReadAt, this may take several async calls.
//send_response_date(call_back) accumulate buffer, upon completion control is back to ReadAt.
range_req_str = "bytes=" + std::to_string(ofs) + "-" + std::to_string(ofs+len-1);
range_str = range_req_str.c_str();
range_parsed = false;
RGWGetObj::parse_range();
requested_buffer.clear();
m_request_range = len;
ldout(s->cct, 10) << "S3select: calling execute(async):" << " request-offset :" << ofs << " request-length :" << len << " buffer size : " << requested_buffer.size() << dendl;
RGWGetObj::execute(y);
if (buff) {
memcpy(buff, requested_buffer.data(), len);
}
ldout(s->cct, 10) << "S3select: done waiting, buffer is complete buffer-size:" << requested_buffer.size() << dendl;
return len;
}
void RGWSelectObj_ObjStore_S3::execute(optional_yield y)
{
int status = 0;
char parquet_magic[4];
static constexpr uint8_t parquet_magic1[4] = {'P', 'A', 'R', '1'};
static constexpr uint8_t parquet_magicE[4] = {'P', 'A', 'R', 'E'};
get_params(y);
#ifdef _ARROW_EXIST
m_rgw_api.m_y = &y;
#endif
if (m_parquet_type) {
//parquet processing
range_request(0, 4, parquet_magic, y);
if (memcmp(parquet_magic, parquet_magic1, 4) && memcmp(parquet_magic, parquet_magicE, 4)) {
ldout(s->cct, 10) << s->object->get_name() << " does not contain parquet magic" << dendl;
op_ret = -ERR_INVALID_REQUEST;
return;
}
s3select_syntax.parse_query(m_sql_query.c_str());
status = run_s3select_on_parquet(m_sql_query.c_str());
if (status) {
ldout(s->cct, 10) << "S3select: failed to process query <" << m_sql_query << "> on object " << s->object->get_name() << dendl;
op_ret = -ERR_INVALID_REQUEST;
} else {
ldout(s->cct, 10) << "S3select: complete query with success " << dendl;
}
} else {
//CSV or JSON processing
if (m_scan_range_ind) {
m_requested_range = (m_end_scan_sz - m_start_scan_sz);
if(m_is_trino_request){
// fetch more than requested(m_scan_offset), that additional bytes are scanned for end of row,
// thus the additional length will be processed, and no broken row for Trino.
// assumption: row is smaller than m_scan_offset. (a different approach is to request for additional range)
range_request(m_start_scan_sz, m_requested_range + m_scan_offset, nullptr, y);
} else {
range_request(m_start_scan_sz, m_requested_range, nullptr, y);
}
} else {
RGWGetObj::execute(y);
}
}//if (m_parquet_type)
}
int RGWSelectObj_ObjStore_S3::parquet_processing(bufferlist& bl, off_t ofs, off_t len)
{
fp_chunked_transfer_encoding();
size_t append_in_callback = 0;
int part_no = 1;
//concat the requested buffer
for (auto& it : bl.buffers()) {
if (it.length() == 0) {
ldout(s->cct, 10) << "S3select: get zero-buffer while appending request-buffer " << dendl;
}
append_in_callback += it.length();
ldout(s->cct, 10) << "S3select: part " << part_no++ << " it.length() = " << it.length() << dendl;
requested_buffer.append(&(it)[0]+ofs, len);
}
ldout(s->cct, 10) << "S3select:append_in_callback = " << append_in_callback << dendl;
if (requested_buffer.size() < m_request_range) {
ldout(s->cct, 10) << "S3select: need another round buffe-size: " << requested_buffer.size() << " request range length:" << m_request_range << dendl;
return 0;
} else {//buffer is complete
ldout(s->cct, 10) << "S3select: buffer is complete " << requested_buffer.size() << " request range length:" << m_request_range << dendl;
m_request_range = 0;
}
return 0;
}
void RGWSelectObj_ObjStore_S3::shape_chunk_per_trino_requests(const char* it_cp, off_t& ofs, off_t& len)
{
//in case it is a scan range request and sent by Trino client.
//this routine chops the start/end of chunks.
//the purpose is to return "perfect" results, with no broken or missing lines.
off_t new_offset = 0;
if(m_scan_range_ind){//only upon range-scan
int64_t sc=0;
int64_t start =0;
const char* row_delimiter = m_row_delimiter.c_str();
ldpp_dout(this, 10) << "s3select query: per Trino request the first and last chunk should modified." << dendl;
//chop the head of the first chunk and only upon the slice does not include the head of the object.
if(m_start_scan_sz && (m_aws_response_handler.get_processed_size()==0)){
char* p = const_cast<char*>(it_cp+ofs);
while(strncmp(row_delimiter,p,1) && (p - (it_cp+ofs)) < len)p++;
if(!strncmp(row_delimiter,p,1)){
new_offset += (p - (it_cp+ofs))+1;
}
}
//RR : end of the range-request. the original request sent by Trino client
//RD : row-delimiter
//[ ... ] : chunk boundaries
//chop the end of the last chunk for this request
//if it's the last chunk, search for first row-delimiter for the following different use-cases
if((m_aws_response_handler.get_processed_size()+len) >= m_requested_range){
//had pass the requested range, start to search for first delimiter
if(m_aws_response_handler.get_processed_size()>m_requested_range){
//the previous chunk contain the complete request(all data) and an extra bytes.
//thus, search for the first row-delimiter
//[:previous (RR) ... ][:current (RD) ]
start = 0;
} else if(m_aws_response_handler.get_processed_size()){
//the *current* chunk contain the complete request in the middle of the chunk.
//thus, search for the first row-delimiter after the complete request position
//[:current (RR) .... (RD) ]
start = m_requested_range - m_aws_response_handler.get_processed_size();
} else {
//the current chunk is the first chunk and it contains complete request
//[:current:first-chunk (RR) .... (RD) ]
start = m_requested_range;
}
for(sc=start;sc<len;sc++)//assumption : row-delimiter must exist or its end ebject
{
char* p = const_cast<char*>(it_cp) + ofs + sc;
if(!strncmp(row_delimiter,p,1)){
ldout(s->cct, 10) << "S3select: found row-delimiter on " << sc << " get_processed_size = " << m_aws_response_handler.get_processed_size() << dendl;
len = sc + 1;//+1 is for delimiter. TODO what about m_object_size_for_processing (to update according to len)
//the end of row exist in current chunk.
//thus, the next chunk should be skipped
m_skip_next_chunk = true;
break;
}
}
}
ofs += new_offset;
}
ldout(s->cct, 10) << "S3select: shape_chunk_per_trino_requests:update progress len = " << len << dendl;
len -= new_offset;
}
int RGWSelectObj_ObjStore_S3::csv_processing(bufferlist& bl, off_t ofs, off_t len)
{
int status = 0;
if(m_skip_next_chunk == true){
return status;
}
if (s->obj_size == 0 || m_object_size_for_processing == 0) {
status = run_s3select_on_csv(m_sql_query.c_str(), nullptr, 0);
if (status<0){
return -EINVAL;
}
} else {
auto bl_len = bl.get_num_buffers();
int buff_no=0;
for(auto& it : bl.buffers()) {
ldpp_dout(this, 10) << "s3select :processing segment " << buff_no << " out of " << bl_len << " off " << ofs
<< " len " << len << " obj-size " << m_object_size_for_processing << dendl;
if (it.length() == 0 || len == 0) {
ldpp_dout(this, 10) << "s3select :it->_len is zero. segment " << buff_no << " out of " << bl_len
<< " obj-size " << m_object_size_for_processing << dendl;
continue;
}
if((ofs + len) > it.length()){
ldpp_dout(this, 10) << "offset and length may cause invalid read: ofs = " << ofs << " len = " << len << " it.length() = " << it.length() << dendl;
ofs = 0;
len = it.length();
}
if(m_is_trino_request){
shape_chunk_per_trino_requests(&(it)[0], ofs, len);
}
ldpp_dout(this, 10) << "s3select: chunk: ofs = " << ofs << " len = " << len << " it.length() = " << it.length() << " m_object_size_for_processing = " << m_object_size_for_processing << dendl;
m_aws_response_handler.update_processed_size(it.length());//NOTE : to run analysis to validate len is aligned with m_processed_bytes
status = run_s3select_on_csv(m_sql_query.c_str(), &(it)[0] + ofs, len);
if (status<0) {
return -EINVAL;
}
if (m_s3_csv_object.is_sql_limit_reached()) {
break;
}
buff_no++;
}//for
}//else
ldpp_dout(this, 10) << "s3select : m_aws_response_handler.get_processed_size() " << m_aws_response_handler.get_processed_size()
<< " m_object_size_for_processing " << uint64_t(m_object_size_for_processing) << dendl;
if (m_aws_response_handler.get_processed_size() >= uint64_t(m_object_size_for_processing) || m_s3_csv_object.is_sql_limit_reached()) {
if (status >=0) {
m_aws_response_handler.init_stats_response();
m_aws_response_handler.send_stats_response();
m_aws_response_handler.init_end_response();
ldpp_dout(this, 10) << "s3select : reached the end of query request : aws_response_handler.get_processed_size() " << m_aws_response_handler.get_processed_size()
<< "m_object_size_for_processing : " << m_object_size_for_processing << dendl;
}
if (m_s3_csv_object.is_sql_limit_reached()) {
//stop fetching chunks
ldpp_dout(this, 10) << "s3select : reached the limit :" << m_aws_response_handler.get_processed_size() << dendl;
status = -ENOENT;
}
}
return status;
}
int RGWSelectObj_ObjStore_S3::json_processing(bufferlist& bl, off_t ofs, off_t len)
{
int status = 0;
if (s->obj_size == 0 || m_object_size_for_processing == 0) {
//in case of empty object the s3select-function returns a correct "empty" result(for aggregation and non-aggregation queries).
status = run_s3select_on_json(m_sql_query.c_str(), nullptr, 0);
if (status<0)
return -EINVAL;
} else {
//loop on buffer-list(chunks)
auto bl_len = bl.get_num_buffers();
int i=0;
for(auto& it : bl.buffers()) {
ldpp_dout(this, 10) << "processing segment " << i << " out of " << bl_len << " off " << ofs
<< " len " << len << " obj-size " << m_object_size_for_processing << dendl;
//skipping the empty chunks
if (len == 0) {
ldpp_dout(this, 10) << "s3select:it->_len is zero. segment " << i << " out of " << bl_len
<< " obj-size " << m_object_size_for_processing << dendl;
continue;
}
if((ofs + len) > it.length()){
ldpp_dout(this, 10) << "s3select: offset and length may cause invalid read: ofs = " << ofs << " len = " << len << " it.length() = " << it.length() << dendl;
ofs = 0;
len = it.length();
}
m_aws_response_handler.update_processed_size(len);
status = run_s3select_on_json(m_sql_query.c_str(), &(it)[0] + ofs, len);
if (status<0) {
status = -EINVAL;
break;
}
if (m_s3_json_object.is_sql_limit_reached()) {
break;
}
i++;
}//for
}//else
if (status>=0 && (m_aws_response_handler.get_processed_size() == uint64_t(m_object_size_for_processing) || m_s3_json_object.is_sql_limit_reached())) {
//flush the internal JSON buffer(upon last chunk)
status = run_s3select_on_json(m_sql_query.c_str(), nullptr, 0);
if (status<0) {
return -EINVAL;
}
if (status >=0) {
m_aws_response_handler.init_stats_response();
m_aws_response_handler.send_stats_response();
m_aws_response_handler.init_end_response();
}
if (m_s3_json_object.is_sql_limit_reached()){
//stop fetching chunks
status = -ENOENT;
ldpp_dout(this, 10) << "s3select : reached the limit :" << m_aws_response_handler.get_processed_size() << dendl;
}
}
return status;
}
int RGWSelectObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t ofs, off_t len)
{
if (m_scan_range_ind == false){
m_object_size_for_processing = s->obj_size;
}
if (m_scan_range_ind == true){
if (m_end_scan_sz == -1){
m_end_scan_sz = s->obj_size;
}
if (static_cast<uint64_t>((m_end_scan_sz - m_start_scan_sz))>s->obj_size){ //in the case user provides range bigger than object-size
m_object_size_for_processing = s->obj_size;
} else {
m_object_size_for_processing = m_end_scan_sz - m_start_scan_sz;
}
}
if (!m_aws_response_handler.is_set()) {
m_aws_response_handler.set(s, this);
}
if (len == 0 && s->obj_size != 0) {
return 0;
}
if (m_parquet_type) {
return parquet_processing(bl,ofs,len);
}
if (m_json_type) {
return json_processing(bl,ofs,len);
}
return csv_processing(bl,ofs,len);
}
| 38,228 | 37.190809 | 209 |
cc
|
null |
ceph-main/src/rgw/rgw_s3select.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
//
#pragma once
namespace rgw::s3select {
RGWOp* create_s3select_op();
}
| 181 | 15.545455 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_s3select_private.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 <errno.h>
#include <array>
#include <string.h>
#include <string_view>
#include "common/ceph_crypto.h"
#include "common/split.h"
#include "common/Formatter.h"
#include "common/utf8.h"
#include "common/ceph_json.h"
#include "common/safe_io.h"
#include "common/errno.h"
#include "auth/Crypto.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/tokenizer.hpp>
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#ifdef HAVE_WARN_IMPLICIT_CONST_INT_FLOAT_CONVERSION
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wimplicit-const-int-float-conversion"
#endif
#ifdef HAVE_WARN_IMPLICIT_CONST_INT_FLOAT_CONVERSION
#pragma clang diagnostic pop
#endif
#undef BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <liboath/oath.h>
#pragma GCC diagnostic push
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma clang diagnostic ignored "-Wdeprecated"
#include <s3select/include/s3select.h>
#pragma GCC diagnostic pop
#pragma clang diagnostic pop
#include "rgw_rest_s3.h"
#include "rgw_s3select.h"
class aws_response_handler
{
private:
std::string sql_result;
req_state* s;
uint32_t header_size;
// the parameters are according to CRC-32 algorithm and its aligned with AWS-cli checksum
boost::crc_optimal<32, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true> crc32;
RGWOp* m_rgwop;
std::string m_buff_header;
uint64_t total_bytes_returned;
uint64_t processed_size;
enum class header_name_En {
EVENT_TYPE,
CONTENT_TYPE,
MESSAGE_TYPE,
ERROR_CODE,
ERROR_MESSAGE
};
enum class header_value_En {
RECORDS,
OCTET_STREAM,
EVENT,
CONT,
PROGRESS,
END,
XML,
STATS,
ENGINE_ERROR,
ERROR_TYPE
};
const char* PAYLOAD_LINE= "\n<Payload>\n<Records>\n<Payload>\n";
const char* END_PAYLOAD_LINE= "\n</Payload></Records></Payload>";
const char* header_name_str[5] = {":event-type", ":content-type", ":message-type", ":error-code", ":error-message"};
const char* header_value_str[10] = {"Records", "application/octet-stream", "event", "Cont", "Progress", "End", "text/xml", "Stats", "s3select-engine-error", "error"};
static constexpr size_t header_crc_size = 12;
void push_header(const char* header_name, const char* header_value);
int create_message(u_int32_t header_len);
public:
aws_response_handler(req_state* ps, RGWOp* rgwop) : s(ps), m_rgwop(rgwop), total_bytes_returned{0}, processed_size{0}
{}
aws_response_handler() : s(nullptr), m_rgwop(nullptr), total_bytes_returned{0}, processed_size{0}
{}
bool is_set()
{
if(s==nullptr || m_rgwop == nullptr){
return false;
}
return true;
}
void set(req_state* ps, RGWOp* rgwop)
{
s = ps;
m_rgwop = rgwop;
}
std::string& get_sql_result();
uint64_t get_processed_size();
void update_processed_size(uint64_t value);
uint64_t get_total_bytes_returned();
void update_total_bytes_returned(uint64_t value);
int create_header_records();
int create_header_continuation();
int create_header_progress();
int create_header_stats();
int create_header_end();
int create_error_header_records(const char* error_message);
void init_response();
void init_success_response();
void send_continuation_response();
void init_progress_response();
void init_end_response();
void init_stats_response();
void init_error_response(const char* error_message);
void send_success_response();
void send_progress_response();
void send_stats_response();
void send_error_response(const char* error_code,
const char* error_message,
const char* resource_id);
}; //end class aws_response_handler
class RGWSelectObj_ObjStore_S3 : public RGWGetObj_ObjStore_S3
{
private:
s3selectEngine::s3select s3select_syntax;
std::string m_s3select_query;
std::string m_s3select_input;
std::string m_s3select_output;
s3selectEngine::csv_object m_s3_csv_object;
#ifdef _ARROW_EXIST
s3selectEngine::parquet_object m_s3_parquet_object;
#endif
s3selectEngine::json_object m_s3_json_object;
std::string m_column_delimiter;
std::string m_quot;
std::string m_row_delimiter;
std::string m_compression_type;
std::string m_escape_char;
std::unique_ptr<char[]> m_buff_header;
std::string m_header_info;
std::string m_sql_query;
std::string m_enable_progress;
std::string output_column_delimiter;
std::string output_quot;
std::string output_escape_char;
std::string output_quote_fields;
std::string output_row_delimiter;
std::string m_start_scan;
std::string m_end_scan;
bool m_scan_range_ind;
int64_t m_start_scan_sz;
int64_t m_end_scan_sz;
int64_t m_object_size_for_processing;
aws_response_handler m_aws_response_handler;
bool enable_progress;
//parquet request
bool m_parquet_type;
//json request
std::string m_json_datatype;
bool m_json_type;
#ifdef _ARROW_EXIST
s3selectEngine::rgw_s3select_api m_rgw_api;
#endif
//a request for range may statisfy by several calls to send_response_date;
size_t m_request_range;
std::string requested_buffer;
std::string range_req_str;
std::function<int(std::string&)> fp_result_header_format;
std::function<int(std::string&)> fp_s3select_result_format;
std::function<void(const char*)> fp_debug_mesg;
std::function<void(void)> fp_chunked_transfer_encoding;
int m_header_size;
public:
unsigned int chunk_number;
size_t m_requested_range;
size_t m_scan_offset;
bool m_skip_next_chunk;
bool m_is_trino_request;
RGWSelectObj_ObjStore_S3();
virtual ~RGWSelectObj_ObjStore_S3();
virtual int send_response_data(bufferlist& bl, off_t ofs, off_t len) override;
virtual int get_params(optional_yield y) override;
virtual void execute(optional_yield) override;
private:
int csv_processing(bufferlist& bl, off_t ofs, off_t len);
int parquet_processing(bufferlist& bl, off_t ofs, off_t len);
int json_processing(bufferlist& bl, off_t ofs, off_t len);
int run_s3select_on_csv(const char* query, const char* input, size_t input_length);
int run_s3select_on_parquet(const char* query);
int run_s3select_on_json(const char* query, const char* input, size_t input_length);
int extract_by_tag(std::string input, std::string tag_name, std::string& result);
void convert_escape_seq(std::string& esc);
int handle_aws_cli_parameters(std::string& sql_query);
int range_request(int64_t start, int64_t len, void*, optional_yield);
size_t get_obj_size();
std::function<int(int64_t, int64_t, void*, optional_yield*)> fp_range_req;
std::function<size_t(void)> fp_get_obj_size;
void shape_chunk_per_trino_requests(const char*, off_t& ofs, off_t& len);
};
| 6,863 | 25.501931 | 168 |
h
|
null |
ceph-main/src/rgw/rgw_sal.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <errno.h>
#include <stdlib.h>
#include <system_error>
#include <unistd.h>
#include <sstream>
#include "common/errno.h"
#include "rgw_sal.h"
#include "rgw_sal_rados.h"
#include "driver/rados/config/store.h"
#include "driver/json_config/store.h"
#include "rgw_d3n_datacache.h"
#ifdef WITH_RADOSGW_DBSTORE
#include "rgw_sal_dbstore.h"
#include "driver/dbstore/config/store.h"
#endif
#ifdef WITH_RADOSGW_D4N
#include "driver/d4n/rgw_sal_d4n.h"
#endif
#ifdef WITH_RADOSGW_MOTR
#include "rgw_sal_motr.h"
#endif
#ifdef WITH_RADOSGW_DAOS
#include "rgw_sal_daos.h"
#endif
#define dout_subsys ceph_subsys_rgw
extern "C" {
extern rgw::sal::Driver* newRadosStore(void);
#ifdef WITH_RADOSGW_DBSTORE
extern rgw::sal::Driver* newDBStore(CephContext *cct);
#endif
#ifdef WITH_RADOSGW_MOTR
extern rgw::sal::Driver* newMotrStore(CephContext *cct);
#endif
#ifdef WITH_RADOSGW_DAOS
extern rgw::sal::Driver* newDaosStore(CephContext *cct);
#endif
extern rgw::sal::Driver* newBaseFilter(rgw::sal::Driver* next);
#ifdef WITH_RADOSGW_D4N
extern rgw::sal::Driver* newD4NFilter(rgw::sal::Driver* next);
#endif
}
RGWObjState::RGWObjState() {
}
RGWObjState::~RGWObjState() {
}
RGWObjState::RGWObjState(const RGWObjState& rhs) : obj (rhs.obj) {
is_atomic = rhs.is_atomic;
has_attrs = rhs.has_attrs;
exists = rhs.exists;
size = rhs.size;
accounted_size = rhs.accounted_size;
mtime = rhs.mtime;
epoch = rhs.epoch;
if (rhs.obj_tag.length()) {
obj_tag = rhs.obj_tag;
}
if (rhs.tail_tag.length()) {
tail_tag = rhs.tail_tag;
}
write_tag = rhs.write_tag;
fake_tag = rhs.fake_tag;
shadow_obj = rhs.shadow_obj;
has_data = rhs.has_data;
if (rhs.data.length()) {
data = rhs.data;
}
prefetch_data = rhs.prefetch_data;
keep_tail = rhs.keep_tail;
is_olh = rhs.is_olh;
objv_tracker = rhs.objv_tracker;
pg_ver = rhs.pg_ver;
compressed = rhs.compressed;
}
rgw::sal::Driver* DriverManager::init_storage_provider(const DoutPrefixProvider* dpp,
CephContext* cct,
const Config& cfg,
bool use_gc_thread,
bool use_lc_thread,
bool quota_threads,
bool run_sync_thread,
bool run_reshard_thread,
bool run_notification_thread,
bool use_cache,
bool use_gc, optional_yield y)
{
rgw::sal::Driver* driver{nullptr};
if (cfg.store_name.compare("rados") == 0) {
driver = newRadosStore();
RGWRados* rados = static_cast<rgw::sal::RadosStore* >(driver)->getRados();
if ((*rados).set_use_cache(use_cache)
.set_use_datacache(false)
.set_use_gc(use_gc)
.set_run_gc_thread(use_gc_thread)
.set_run_lc_thread(use_lc_thread)
.set_run_quota_threads(quota_threads)
.set_run_sync_thread(run_sync_thread)
.set_run_reshard_thread(run_reshard_thread)
.set_run_notification_thread(run_notification_thread)
.init_begin(cct, dpp) < 0) {
delete driver;
return nullptr;
}
if (driver->initialize(cct, dpp) < 0) {
delete driver;
return nullptr;
}
if (rados->init_complete(dpp, y) < 0) {
delete driver;
return nullptr;
}
}
else if (cfg.store_name.compare("d3n") == 0) {
driver = new rgw::sal::RadosStore();
RGWRados* rados = new D3nRGWDataCache<RGWRados>;
dynamic_cast<rgw::sal::RadosStore*>(driver)->setRados(rados);
rados->set_store(static_cast<rgw::sal::RadosStore* >(driver));
if ((*rados).set_use_cache(use_cache)
.set_use_datacache(true)
.set_run_gc_thread(use_gc_thread)
.set_run_lc_thread(use_lc_thread)
.set_run_quota_threads(quota_threads)
.set_run_sync_thread(run_sync_thread)
.set_run_reshard_thread(run_reshard_thread)
.set_run_notification_thread(run_notification_thread)
.init_begin(cct, dpp) < 0) {
delete driver;
return nullptr;
}
if (driver->initialize(cct, dpp) < 0) {
delete driver;
return nullptr;
}
if (rados->init_complete(dpp, y) < 0) {
delete driver;
return nullptr;
}
lsubdout(cct, rgw, 1) << "rgw_d3n: rgw_d3n_l1_local_datacache_enabled=" <<
cct->_conf->rgw_d3n_l1_local_datacache_enabled << dendl;
lsubdout(cct, rgw, 1) << "rgw_d3n: rgw_d3n_l1_datacache_persistent_path='" <<
cct->_conf->rgw_d3n_l1_datacache_persistent_path << "'" << dendl;
lsubdout(cct, rgw, 1) << "rgw_d3n: rgw_d3n_l1_datacache_size=" <<
cct->_conf->rgw_d3n_l1_datacache_size << dendl;
lsubdout(cct, rgw, 1) << "rgw_d3n: rgw_d3n_l1_evict_cache_on_start=" <<
cct->_conf->rgw_d3n_l1_evict_cache_on_start << dendl;
lsubdout(cct, rgw, 1) << "rgw_d3n: rgw_d3n_l1_fadvise=" <<
cct->_conf->rgw_d3n_l1_fadvise << dendl;
lsubdout(cct, rgw, 1) << "rgw_d3n: rgw_d3n_l1_eviction_policy=" <<
cct->_conf->rgw_d3n_l1_eviction_policy << dendl;
}
#ifdef WITH_RADOSGW_DBSTORE
else if (cfg.store_name.compare("dbstore") == 0) {
driver = newDBStore(cct);
if ((*(rgw::sal::DBStore*)driver).set_run_lc_thread(use_lc_thread)
.initialize(cct, dpp) < 0) {
delete driver;
return nullptr;
}
}
#endif
#ifdef WITH_RADOSGW_MOTR
else if (cfg.store_name.compare("motr") == 0) {
driver = newMotrStore(cct);
if (driver == nullptr) {
ldpp_dout(dpp, 0) << "newMotrStore() failed!" << dendl;
return driver;
}
((rgw::sal::MotrStore *)driver)->init_metadata_cache(dpp, cct);
return store;
}
#endif
#ifdef WITH_RADOSGW_DAOS
else if (cfg.store_name.compare("daos") == 0) {
driver = newDaosStore(cct);
if (driver == nullptr) {
ldpp_dout(dpp, 0) << "newDaosStore() failed!" << dendl;
return driver;
}
int ret = driver->initialize(cct, dpp);
if (ret != 0) {
ldpp_dout(dpp, 20) << "ERROR: store->initialize() failed: " << ret << dendl;
delete driver;
return nullptr;
}
}
#endif
if (cfg.filter_name.compare("base") == 0) {
rgw::sal::Driver* next = driver;
driver = newBaseFilter(next);
if (driver->initialize(cct, dpp) < 0) {
delete driver;
delete next;
return nullptr;
}
}
#ifdef WITH_RADOSGW_D4N
else if (cfg.filter_name.compare("d4n") == 0) {
rgw::sal::Driver* next = driver;
driver = newD4NFilter(next);
if (driver->initialize(cct, dpp) < 0) {
delete driver;
delete next;
return nullptr;
}
}
#endif
return driver;
}
rgw::sal::Driver* DriverManager::init_raw_storage_provider(const DoutPrefixProvider* dpp, CephContext* cct, const Config& cfg)
{
rgw::sal::Driver* driver = nullptr;
if (cfg.store_name.compare("rados") == 0) {
driver = newRadosStore();
RGWRados* rados = static_cast<rgw::sal::RadosStore* >(driver)->getRados();
rados->set_context(cct);
int ret = rados->init_svc(true, dpp);
if (ret < 0) {
ldout(cct, 0) << "ERROR: failed to init services (ret=" << cpp_strerror(-ret) << ")" << dendl;
delete driver;
return nullptr;
}
if (rados->init_rados() < 0) {
delete driver;
return nullptr;
}
if (driver->initialize(cct, dpp) < 0) {
delete driver;
return nullptr;
}
} else if (cfg.store_name.compare("dbstore") == 0) {
#ifdef WITH_RADOSGW_DBSTORE
driver = newDBStore(cct);
if ((*(rgw::sal::DBStore*)driver).initialize(cct, dpp) < 0) {
delete driver;
return nullptr;
}
#else
driver = nullptr;
#endif
} else if (cfg.store_name.compare("motr") == 0) {
#ifdef WITH_RADOSGW_MOTR
driver = newMotrStore(cct);
#else
driver = nullptr;
#endif
} else if (cfg.store_name.compare("daos") == 0) {
#ifdef WITH_RADOSGW_DAOS
driver = newDaosStore(cct);
if (driver->initialize(cct, dpp) < 0) {
delete driver;
return nullptr;
}
#else
driver = nullptr;
#endif
}
if (cfg.filter_name.compare("base") == 0) {
rgw::sal::Driver* next = driver;
driver = newBaseFilter(next);
if (driver->initialize(cct, dpp) < 0) {
delete driver;
delete next;
return nullptr;
}
}
return driver;
}
void DriverManager::close_storage(rgw::sal::Driver* driver)
{
if (!driver)
return;
driver->finalize();
delete driver;
}
DriverManager::Config DriverManager::get_config(bool admin, CephContext* cct)
{
DriverManager::Config cfg;
// Get the store backend
const auto& config_store = g_conf().get_val<std::string>("rgw_backend_store");
if (config_store == "rados") {
cfg.store_name = "rados";
/* Check to see if d3n is configured, but only for non-admin */
const auto& d3n = g_conf().get_val<bool>("rgw_d3n_l1_local_datacache_enabled");
if (!admin && d3n) {
if (g_conf().get_val<Option::size_t>("rgw_max_chunk_size") !=
g_conf().get_val<Option::size_t>("rgw_obj_stripe_size")) {
lsubdout(cct, rgw_datacache, 0) << "rgw_d3n: WARNING: D3N DataCache disabling (D3N requires that the chunk_size equals stripe_size)" << dendl;
} else if (!g_conf().get_val<bool>("rgw_beast_enable_async")) {
lsubdout(cct, rgw_datacache, 0) << "rgw_d3n: WARNING: D3N DataCache disabling (D3N requires yield context - rgw_beast_enable_async=true)" << dendl;
} else {
cfg.store_name = "d3n";
}
}
}
#ifdef WITH_RADOSGW_DBSTORE
else if (config_store == "dbstore") {
cfg.store_name = "dbstore";
}
#endif
#ifdef WITH_RADOSGW_MOTR
else if (config_store == "motr") {
cfg.store_name = "motr";
}
#endif
#ifdef WITH_RADOSGW_DAOS
else if (config_store == "daos") {
cfg.store_name = "daos";
}
#endif
// Get the filter
cfg.filter_name = "none";
const auto& config_filter = g_conf().get_val<std::string>("rgw_filter");
if (config_filter == "base") {
cfg.filter_name = "base";
}
#ifdef WITH_RADOSGW_D4N
else if (config_filter == "d4n") {
cfg.filter_name= "d4n";
}
#endif
return cfg;
}
auto DriverManager::create_config_store(const DoutPrefixProvider* dpp,
std::string_view type)
-> std::unique_ptr<rgw::sal::ConfigStore>
{
try {
if (type == "rados") {
return rgw::rados::create_config_store(dpp);
#ifdef WITH_RADOSGW_DBSTORE
} else if (type == "dbstore") {
const auto uri = g_conf().get_val<std::string>("dbstore_config_uri");
return rgw::dbstore::create_config_store(dpp, uri);
#endif
} else if (type == "json") {
auto filename = g_conf().get_val<std::string>("rgw_json_config");
return rgw::sal::create_json_config_store(dpp, filename);
} else {
ldpp_dout(dpp, -1) << "ERROR: unrecognized config store type '"
<< type << "'" << dendl;
return nullptr;
}
} catch (const std::exception& e) {
ldpp_dout(dpp, -1) << "ERROR: failed to initialize config store '"
<< type << "': " << e.what() << dendl;
}
return nullptr;
}
namespace rgw::sal {
int Object::range_to_ofs(uint64_t obj_size, int64_t &ofs, int64_t &end)
{
if (ofs < 0) {
ofs += obj_size;
if (ofs < 0)
ofs = 0;
end = obj_size - 1;
} else if (end < 0) {
end = obj_size - 1;
}
if (obj_size > 0) {
if (ofs >= (off_t)obj_size) {
return -ERANGE;
}
if (end >= (off_t)obj_size) {
end = obj_size - 1;
}
}
return 0;
}
} // namespace rgw::sal
| 11,881 | 26.761682 | 149 |
cc
|
null |
ceph-main/src/rgw/rgw_sal.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 "rgw_sal_fwd.h"
#include "rgw_lua.h"
#include "rgw_user.h"
#include "rgw_notify_event_type.h"
#include "common/tracer.h"
#include "rgw_datalog_notify.h"
#include "include/random.h"
class RGWRESTMgr;
class RGWAccessListFilter;
class RGWLC;
struct rgw_user_bucket;
class RGWUsageBatch;
class RGWCoroutinesManagerRegistry;
class RGWBucketSyncPolicyHandler;
using RGWBucketSyncPolicyHandlerRef = std::shared_ptr<RGWBucketSyncPolicyHandler>;
class RGWDataSyncStatusManager;
class RGWSyncModuleInstance;
typedef std::shared_ptr<RGWSyncModuleInstance> RGWSyncModuleInstanceRef;
class RGWCompressionInfo;
struct rgw_pubsub_topics;
struct rgw_pubsub_bucket_topics;
using RGWBucketListNameFilter = std::function<bool (const std::string&)>;
namespace rgw {
class Aio;
namespace IAM { struct Policy; }
}
class RGWGetDataCB {
public:
virtual int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) = 0;
RGWGetDataCB() {}
virtual ~RGWGetDataCB() {}
};
struct RGWUsageIter {
std::string read_iter;
uint32_t index;
RGWUsageIter() : index(0) {}
};
/**
* @struct RGWClusterStat
* Cluster-wide usage information
*/
struct RGWClusterStat {
/// total device size
uint64_t kb;
/// total used
uint64_t kb_used;
/// total available/free
uint64_t kb_avail;
/// number of objects
uint64_t num_objects;
};
class RGWGetBucketStats_CB : public RefCountedObject {
protected:
rgw_bucket bucket;
std::map<RGWObjCategory, RGWStorageStats>* stats;
public:
explicit RGWGetBucketStats_CB(const rgw_bucket& _bucket) : bucket(_bucket), stats(NULL) {}
~RGWGetBucketStats_CB() override {}
virtual void handle_response(int r) = 0;
virtual void set_response(std::map<RGWObjCategory, RGWStorageStats>* _stats) {
stats = _stats;
}
};
class RGWGetUserStats_CB : public RefCountedObject {
protected:
rgw_user user;
RGWStorageStats stats;
public:
explicit RGWGetUserStats_CB(const rgw_user& _user) : user(_user) {}
~RGWGetUserStats_CB() override {}
virtual void handle_response(int r) = 0;
virtual void set_response(RGWStorageStats& _stats) {
stats = _stats;
}
};
struct RGWObjState {
rgw_obj obj;
bool is_atomic{false};
bool has_attrs{false};
bool exists{false};
uint64_t size{0}; //< size of raw object
uint64_t accounted_size{0}; //< size before compression, encryption
ceph::real_time mtime;
uint64_t epoch{0};
bufferlist obj_tag;
bufferlist tail_tag;
std::string write_tag;
bool fake_tag{false};
std::string shadow_obj;
bool has_data{false};
bufferlist data;
bool prefetch_data{false};
bool keep_tail{false};
bool is_olh{false};
bufferlist olh_tag;
uint64_t pg_ver{false};
uint32_t zone_short_id{0};
bool compressed{false};
/* important! don't forget to update copy constructor */
RGWObjVersionTracker objv_tracker;
std::map<std::string, ceph::buffer::list> attrset;
RGWObjState();
RGWObjState(const RGWObjState& rhs);
~RGWObjState();
bool get_attr(std::string name, bufferlist& dest) {
auto iter = attrset.find(name);
if (iter != attrset.end()) {
dest = iter->second;
return true;
}
return false;
}
};
/**
* @defgroup RGWSAL RGW Store Abstraction Layer
*
* The Store Abstraction Layer is an API that separates the top layer of RGW that
* handles client protocols (such as S3 or Swift) from the bottom layer of RGW that
* interacts with a backing store. It allows the creation of multiple backing stores
* that can co-exist with a single RGW instance, and allows the creation of stacking
* layers of translators that can modify operations as they pass down the stack.
* Examples of translators might be a cache layer, a duplication layer that copies
* operations to multiple stores, or a policy layer that sends some operations to one
* store and some to another.
*
* The basic unit of a SAL implementation is the Store. Whether an actual backing store
* or a translator, there will be a Store implementation that represents it. Examples
* are the RadosStore that communicates via RADOS with a Ceph cluster, and the DBStore
* that uses a SQL db (such as SQLite3) as a backing store. There is a singleton
* instance of each Store.
*
* Data within RGW is owned by a User. The User is the unit of authentication and
* access control.
*
* Data within RGW is stored as an Object. Each Object is a single chunk of data, owned
* by a single User, contained within a single Bucket. It has metadata associated with
* it, such as size, owner, and so on, and a set of key-value attributes that can
* contain anything needed by the top half.
*
* Data with RGW is organized into Buckets. Each Bucket is owned by a User, and
* contains Objects. There is a single, flat layer of Buckets, there is no hierarchy,
* and each Object is contained in a single Bucket.
*
* Instantiations of SAL classes are done as unique pointers, using std::unique_ptr.
* Instances of these classes are acquired via getters, and it's up to the caller to
* manage the lifetime.
*
* @note Anything using RGWObjContext is subject to change, as that type will not be
* used in the final API.
* @{
*/
/**
* @file rgw_sal.h
* @brief Base abstractions and API for SAL
*/
namespace rgw { namespace sal {
/**
* @addtogroup RGWSAL
* @{
*/
#define RGW_SAL_VERSION 1
struct MPSerializer;
class GCChain;
class RGWOIDCProvider;
class RGWRole;
enum AttrsMod {
ATTRSMOD_NONE = 0,
ATTRSMOD_REPLACE = 1,
ATTRSMOD_MERGE = 2
};
// a simple streaming data processing abstraction
/**
* @brief A simple streaming data processing abstraction
*/
class DataProcessor {
public:
virtual ~DataProcessor() {}
/**
* @brief Consume a bufferlist in its entirety at the given object offset.
*
* An empty bufferlist is given to request that any buffered data be flushed, though this doesn't
* wait for completions
*/
virtual int process(bufferlist&& data, uint64_t offset) = 0;
};
/**
* @brief a data consumer that writes an object in a bucket
*/
class ObjectProcessor : public DataProcessor {
public:
/** prepare to start processing object data */
virtual int prepare(optional_yield y) = 0;
/** complete the operation and make its result visible to clients */
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y) = 0;
};
/** A list of key-value attributes */
using Attrs = std::map<std::string, ceph::buffer::list>;
/**
* @brief Base singleton representing a Store or Filter
*
* The Driver is the base abstraction of the SAL layer. It represents a base storage
* mechanism, or a intermediate stacking layer. There is a single instance of a given
* Driver per RGW, and this Driver mediates all access to it's backing.
*
* A Driver contains, loosely, @a User, @a Bucket, and @a Object entities. The @a Object
* contains data, and it's associated metadata. The @a Bucket contains Objects, and
* metadata about the bucket. Both Buckets and Objects are owned by a @a User, which is
* the basic unit of access control.
*
* A Driver also has metadata and some global responsibilities. For example, a driver is
* responsible for managing the LifeCycle activities for it's data.
*/
class Driver {
public:
Driver() {}
virtual ~Driver() = default;
/** Post-creation initialization of driver */
virtual int initialize(CephContext *cct, const DoutPrefixProvider *dpp) = 0;
/** Name of this driver provider (e.g., "rados") */
virtual const std::string get_name() const = 0;
/** Get cluster unique identifier */
virtual std::string get_cluster_id(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Get a User from a rgw_user. Does not query driver for user info, so quick */
virtual std::unique_ptr<User> get_user(const rgw_user& u) = 0;
/** Lookup a User by access key. Queries driver for user info. */
virtual int get_user_by_access_key(const DoutPrefixProvider* dpp, const std::string& key, optional_yield y, std::unique_ptr<User>* user) = 0;
/** Lookup a User by email address. Queries driver for user info. */
virtual int get_user_by_email(const DoutPrefixProvider* dpp, const std::string& email, optional_yield y, std::unique_ptr<User>* user) = 0;
/** Lookup a User by swift username. Queries driver for user info. */
virtual int get_user_by_swift(const DoutPrefixProvider* dpp, const std::string& user_str, optional_yield y, std::unique_ptr<User>* user) = 0;
/** Get a basic Object. This Object is not looked up, and is incomplete, since is
* does not have a bucket. This should only be used when an Object is needed before
* there is a Bucket, otherwise use the get_object() in the Bucket class. */
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& k) = 0;
/** Get a Bucket by info. Does not query the driver, just uses the give bucket info. */
virtual int get_bucket(User* u, const RGWBucketInfo& i, std::unique_ptr<Bucket>* bucket) = 0;
/** Lookup a Bucket by key. Queries driver for bucket info. */
virtual int get_bucket(const DoutPrefixProvider* dpp, User* u, const rgw_bucket& b, std::unique_ptr<Bucket>* bucket, optional_yield y) = 0;
/** Lookup a Bucket by name. Queries driver for bucket info. */
virtual int get_bucket(const DoutPrefixProvider* dpp, User* u, const std::string& tenant, const std::string& name, std::unique_ptr<Bucket>* bucket, optional_yield y) = 0;
/** For multisite, this driver is the zone's master */
virtual bool is_meta_master() = 0;
/** For multisite, forward an OP to the zone's master */
virtual int forward_request_to_master(const DoutPrefixProvider *dpp, User* user, obj_version* objv,
bufferlist& in_data, JSONParser* jp, req_info& info,
optional_yield y) = 0;
virtual int forward_iam_request_to_master(const DoutPrefixProvider *dpp, const RGWAccessKey& key, obj_version* objv,
bufferlist& in_data,
RGWXMLDecoder::XMLParser* parser, req_info& info,
optional_yield y) = 0;
/** Get zone info for this driver */
virtual Zone* get_zone() = 0;
/** Get a unique ID specific to this zone. */
virtual std::string zone_unique_id(uint64_t unique_num) = 0;
/** Get a unique Swift transaction ID specific to this zone */
virtual std::string zone_unique_trans_id(const uint64_t unique_num) = 0;
/** Lookup a zonegroup by ID */
virtual int get_zonegroup(const std::string& id, std::unique_ptr<ZoneGroup>* zonegroup) = 0;
/** List all zones in all zone groups by ID */
virtual int list_all_zones(const DoutPrefixProvider* dpp, std::list<std::string>& zone_ids) = 0;
/** Get statistics about the cluster represented by this driver */
virtual int cluster_stat(RGWClusterStat& stats) = 0;
/** Get a @a Lifecycle object. Used to manage/run lifecycle transitions */
virtual std::unique_ptr<Lifecycle> get_lifecycle(void) = 0;
/** Get a @a Notification object. Used to communicate with non-RGW daemons, such as
* management/tracking software */
/** RGWOp variant */
virtual std::unique_ptr<Notification> get_notification(rgw::sal::Object* obj, rgw::sal::Object* src_obj, req_state* s,
rgw::notify::EventType event_type, optional_yield y, const std::string* object_name=nullptr) = 0;
/** No-req_state variant (e.g., rgwlc) */
virtual std::unique_ptr<Notification> get_notification(
const DoutPrefixProvider* dpp, rgw::sal::Object* obj, rgw::sal::Object* src_obj,
rgw::notify::EventType event_type, rgw::sal::Bucket* _bucket, std::string& _user_id, std::string& _user_tenant,
std::string& _req_id, optional_yield y) = 0;
/** Read the topic config entry into @a data and (optionally) @a objv_tracker */
virtual int read_topics(const std::string& tenant, rgw_pubsub_topics& topics, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) = 0;
/** Write @a info and (optionally) @a objv_tracker into the config */
virtual int write_topics(const std::string& tenant, const rgw_pubsub_topics& topics, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) = 0;
/** Remove the topic config, optionally a specific version */
virtual int remove_topics(const std::string& tenant, RGWObjVersionTracker* objv_tracker,
optional_yield y,const DoutPrefixProvider *dpp) = 0;
/** Get access to the lifecycle management thread */
virtual RGWLC* get_rgwlc(void) = 0;
/** Get access to the coroutine registry. Used to create new coroutine managers */
virtual RGWCoroutinesManagerRegistry* get_cr_registry() = 0;
/** Log usage data to the driver. Usage data is things like bytes sent/received and
* op count */
virtual int log_usage(const DoutPrefixProvider *dpp, std::map<rgw_user_bucket, RGWUsageBatch>& usage_info, optional_yield y) = 0;
/** Log OP data to the driver. Data is opaque to SAL */
virtual int log_op(const DoutPrefixProvider *dpp, std::string& oid, bufferlist& bl) = 0;
/** Register this driver to the service map. Somewhat Rados specific; may be removed*/
virtual int register_to_service_map(const DoutPrefixProvider *dpp, const std::string& daemon_type,
const std::map<std::string, std::string>& meta) = 0;
/** Get default quota info. Used as fallback if a user or bucket has no quota set*/
virtual void get_quota(RGWQuota& quota) = 0;
/** Get global rate limit configuration*/
virtual void get_ratelimit(RGWRateLimitInfo& bucket_ratelimit, RGWRateLimitInfo& user_ratelimit, RGWRateLimitInfo& anon_ratelimit) = 0;
/** Enable or disable a set of bucket. e.g. if a User is suspended */
virtual int set_buckets_enabled(const DoutPrefixProvider* dpp, std::vector<rgw_bucket>& buckets, bool enabled, optional_yield y) = 0;
/** Get a new request ID */
virtual uint64_t get_new_req_id() = 0;
/** Get a handler for bucket sync policy. */
virtual int get_sync_policy_handler(const DoutPrefixProvider* dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef* phandler,
optional_yield y) = 0;
/** Get a status manager for bucket sync */
virtual RGWDataSyncStatusManager* get_data_sync_manager(const rgw_zone_id& source_zone) = 0;
/** Wake up sync threads for bucket metadata sync */
virtual void wakeup_meta_sync_shards(std::set<int>& shard_ids) = 0;
/** Wake up sync threads for bucket data sync */
virtual void wakeup_data_sync_shards(const DoutPrefixProvider *dpp, const rgw_zone_id& source_zone, boost::container::flat_map<int, boost::container::flat_set<rgw_data_notify_entry>>& shard_ids) = 0;
/** Clear all usage statistics globally */
virtual int clear_usage(const DoutPrefixProvider *dpp, optional_yield y) = 0;
/** Get usage statistics for all users and buckets */
virtual int read_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool* is_truncated,
RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) = 0;
/** Trim usage log for all users and buckets */
virtual int trim_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y) = 0;
/** Get a configuration value for the given name */
virtual int get_config_key_val(std::string name, bufferlist* bl) = 0;
/** Start a metadata listing of the given section */
virtual int meta_list_keys_init(const DoutPrefixProvider *dpp, const std::string& section, const std::string& marker, void** phandle) = 0;
/** Get the next key from a metadata list */
virtual int meta_list_keys_next(const DoutPrefixProvider *dpp, void* handle, int max, std::list<std::string>& keys, bool* truncated) = 0;
/** Complete a metadata listing */
virtual void meta_list_keys_complete(void* handle) = 0;
/** Get the marker associated with the current metadata listing */
virtual std::string meta_get_marker(void* handle) = 0;
/** Remove a specific metadata key */
virtual int meta_remove(const DoutPrefixProvider* dpp, std::string& metadata_key, optional_yield y) = 0;
/** Get an instance of the Sync module for bucket sync */
virtual const RGWSyncModuleInstanceRef& get_sync_module() = 0;
/** Get the ID of the current host */
virtual std::string get_host_id() = 0;
/** Get a Lua script manager for running lua scripts */
virtual std::unique_ptr<LuaManager> get_lua_manager() = 0;
/** Get an IAM Role by name etc. */
virtual std::unique_ptr<RGWRole> get_role(std::string name,
std::string tenant,
std::string path="",
std::string trust_policy="",
std::string max_session_duration_str="",
std::multimap<std::string,std::string> tags={}) = 0;
/** Get an IAM Role by ID */
virtual std::unique_ptr<RGWRole> get_role(std::string id) = 0;
virtual std::unique_ptr<RGWRole> get_role(const RGWRoleInfo& info) = 0;
/** Get all IAM Roles optionally filtered by path */
virtual int get_roles(const DoutPrefixProvider *dpp,
optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
std::vector<std::unique_ptr<RGWRole>>& roles) = 0;
/** Get an empty Open ID Connector provider */
virtual std::unique_ptr<RGWOIDCProvider> get_oidc_provider() = 0;
/** Get all Open ID Connector providers, optionally filtered by tenant */
virtual int get_oidc_providers(const DoutPrefixProvider *dpp,
const std::string& tenant,
std::vector<std::unique_ptr<RGWOIDCProvider>>& providers, optional_yield y) = 0;
/** Get a Writer that appends to an object */
virtual std::unique_ptr<Writer> get_append_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
const std::string& unique_tag,
uint64_t position,
uint64_t *cur_accounted_size) = 0;
/** Get a Writer that atomically writes an entire object */
virtual std::unique_ptr<Writer> get_atomic_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t olh_epoch,
const std::string& unique_tag) = 0;
/** Get the compression type of a placement rule */
virtual const std::string& get_compression_type(const rgw_placement_rule& rule) = 0;
/** Check to see if this placement rule is valid */
virtual bool valid_placement(const rgw_placement_rule& rule) = 0;
/** Clean up a driver for termination */
virtual void finalize(void) = 0;
/** Get the Ceph context associated with this driver. May be removed. */
virtual CephContext* ctx(void) = 0;
/** Register admin APIs unique to this driver */
virtual void register_admin_apis(RGWRESTMgr* mgr) = 0;
};
/**
* @brief User abstraction
*
* This represents a user. In general, there will be a @a User associated with an OP
* (the user performing the OP), and potentially several others acting as owners.
* Lifetime of a User is a bit tricky , since it must last as long as any Buckets
* associated with it. A User has associated metadata, including a set of key/value
* attributes, and statistics (including usage) about the User.
*/
class User {
public:
User() {}
virtual ~User() = default;
/** Clone a copy of this user. Used when modification is necessary of the copy */
virtual std::unique_ptr<User> clone() = 0;
/** List the buckets owned by a user */
virtual int list_buckets(const DoutPrefixProvider* dpp,
const std::string& marker, const std::string& end_marker,
uint64_t max, bool need_stats, BucketList& buckets,
optional_yield y) = 0;
/** Create a new bucket owned by this user. Creates in the backing store, not just the instantiation. */
virtual int create_bucket(const DoutPrefixProvider* dpp,
const rgw_bucket& b,
const std::string& zonegroup_id,
rgw_placement_rule& placement_rule,
std::string& swift_ver_location,
const RGWQuotaInfo* pquota_info,
const RGWAccessControlPolicy& policy,
Attrs& attrs,
RGWBucketInfo& info,
obj_version& ep_objv,
bool exclusive,
bool obj_lock_enabled,
bool* existed,
req_info& req_info,
std::unique_ptr<Bucket>* bucket,
optional_yield y) = 0;
/** Get the display name for this User */
virtual std::string& get_display_name() = 0;
/** Get the tenant name for this User */
virtual const std::string& get_tenant() = 0;
/** Set the tenant name for this User */
virtual void set_tenant(std::string& _t) = 0;
/** Get the namespace for this User */
virtual const std::string& get_ns() = 0;
/** Set the namespace for this User */
virtual void set_ns(std::string& _ns) = 0;
/** Clear the namespace for this User */
virtual void clear_ns() = 0;
/** Get the full ID for this User */
virtual const rgw_user& get_id() const = 0;
/** Get the type of this User */
virtual uint32_t get_type() const = 0;
/** Get the maximum number of buckets allowed for this User */
virtual int32_t get_max_buckets() const = 0;
/** Set the maximum number of buckets allowed for this User */
virtual void set_max_buckets(int32_t _max_buckets) = 0;
/** Set quota info */
virtual void set_info(RGWQuotaInfo& _quota) = 0;
/** Get the capabilities for this User */
virtual const RGWUserCaps& get_caps() const = 0;
/** Get the version tracker for this User */
virtual RGWObjVersionTracker& get_version_tracker() = 0;
/** Get the cached attributes for this User */
virtual Attrs& get_attrs() = 0;
/** Set the cached attributes fro this User */
virtual void set_attrs(Attrs& _attrs) = 0;
/** Check if a User is empty */
virtual bool empty() const = 0;
/** Check if a User pointer is empty */
static bool empty(const User* u) { return (!u || u->empty()); }
/** Check if a User unique_pointer is empty */
static bool empty(const std::unique_ptr<User>& u) { return (!u || u->empty()); }
/** Read the User attributes from the backing Store */
virtual int read_attrs(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Set the attributes in attrs, leaving any other existing attrs set, and
* write them to the backing store; a merge operation */
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp, Attrs& new_attrs, optional_yield y) = 0;
/** Read the User stats from the backing Store, synchronous */
virtual int read_stats(const DoutPrefixProvider *dpp,
optional_yield y, RGWStorageStats* stats,
ceph::real_time* last_stats_sync = nullptr,
ceph::real_time* last_stats_update = nullptr) = 0;
/** Read the User stats from the backing Store, asynchronous */
virtual int read_stats_async(const DoutPrefixProvider *dpp, RGWGetUserStats_CB* cb) = 0;
/** Flush accumulated stat changes for this User to the backing store */
virtual int complete_flush_stats(const DoutPrefixProvider *dpp, optional_yield y) = 0;
/** Read detailed usage stats for this User from the backing store */
virtual int read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) = 0;
/** Trim User usage stats to the given epoch range */
virtual int trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y) = 0;
/** Load this User from the backing store. requires ID to be set, fills all other fields. */
virtual int load_user(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Store this User to the backing store */
virtual int store_user(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, RGWUserInfo* old_info = nullptr) = 0;
/** Remove this User from the backing store */
virtual int remove_user(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Verify multi-factor authentication for this user */
virtual int verify_mfa(const std::string& mfa_str, bool* verified, const DoutPrefixProvider* dpp, optional_yield y) = 0;
/* dang temporary; will be removed when User is complete */
virtual RGWUserInfo& get_info() = 0;
/** Print the User to @a out */
virtual void print(std::ostream& out) const = 0;
friend inline std::ostream& operator<<(std::ostream& out, const User& u) {
u.print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const User* u) {
if (!u)
out << "<NULL>";
else
u->print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const std::unique_ptr<User>& p) {
out << p.get();
return out;
}
};
/**
* @brief Bucket abstraction
*
* This represents a bucket. A bucket is a container for objects. It is owned by a user, and has
* it's own set of metadata, including a set of key/value attributes. A bucket may not contain
* other buckets, only objects. Buckets have Access Control Lists (ACLs) that control what users
* can access the contents of the bucket, and in what ways.
*/
class Bucket {
public:
/**
* @brief Parameters for a bucket list operation
*/
struct ListParams {
std::string prefix;
std::string delim;
rgw_obj_key marker;
rgw_obj_key end_marker;
std::string ns;
bool enforce_ns{true};
RGWAccessListFilter* access_list_filter{nullptr};
RGWBucketListNameFilter force_check_filter;
bool list_versions{false};
bool allow_unordered{false};
int shard_id{RGW_NO_SHARD};
friend std::ostream& operator<<(std::ostream& out, const ListParams& p) {
out << "rgw::sal::Bucket::ListParams{ prefix=\"" << p.prefix <<
"\", delim=\"" << p.delim <<
"\", marker=\"" << p.marker <<
"\", end_marker=\"" << p.end_marker <<
"\", ns=\"" << p.ns <<
"\", enforce_ns=" << p.enforce_ns <<
", list_versions=" << p.list_versions <<
", allow_unordered=" << p.allow_unordered <<
", shard_id=" << p.shard_id <<
" }";
return out;
}
};
/**
* @brief Results from a bucket list operation
*/
struct ListResults {
std::vector<rgw_bucket_dir_entry> objs;
std::map<std::string, bool> common_prefixes;
bool is_truncated{false};
rgw_obj_key next_marker;
};
Bucket() = default;
virtual ~Bucket() = default;
/** Get an @a Object belonging to this bucket */
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& key) = 0;
/** List the contents of this bucket */
virtual int list(const DoutPrefixProvider* dpp, ListParams&, int, ListResults&, optional_yield y) = 0;
/** Get the cached attributes associated with this bucket */
virtual Attrs& get_attrs(void) = 0;
/** Set the cached attributes on this bucket */
virtual int set_attrs(Attrs a) = 0;
/** Remove this bucket from the backing store */
virtual int remove_bucket(const DoutPrefixProvider* dpp, bool delete_children, bool forward_to_master, req_info* req_info, optional_yield y) = 0;
/** Remove this bucket, bypassing garbage collection. May be removed */
virtual int remove_bucket_bypass_gc(int concurrent_max, bool
keep_index_consistent,
optional_yield y, const
DoutPrefixProvider *dpp) = 0;
/** Get then ACL for this bucket */
virtual RGWAccessControlPolicy& get_acl(void) = 0;
/** Set the ACL for this bucket */
virtual int set_acl(const DoutPrefixProvider* dpp, RGWAccessControlPolicy& acl, optional_yield y) = 0;
// XXXX hack
virtual void set_owner(rgw::sal::User* _owner) = 0;
/** Load this bucket from the backing store. Requires the key to be set, fills other fields.
* If @a get_stats is true, then statistics on the bucket are also looked up. */
virtual int load_bucket(const DoutPrefixProvider* dpp, optional_yield y, bool get_stats = false) = 0;
/** Read the bucket stats from the backing Store, synchronous */
virtual int read_stats(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, std::string* bucket_ver, std::string* master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string* max_marker = nullptr,
bool* syncstopped = nullptr) = 0;
/** Read the bucket stats from the backing Store, asynchronous */
virtual int read_stats_async(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, RGWGetBucketStats_CB* ctx) = 0;
/** Sync this bucket's stats to the owning user's stats in the backing store */
virtual int sync_user_stats(const DoutPrefixProvider *dpp, optional_yield y) = 0;
/** Refresh the metadata stats (size, count, and so on) from the backing store */
virtual int update_container_stats(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Check if this bucket needs resharding, and schedule it if it does */
virtual int check_bucket_shards(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Change the owner of this bucket in the backing store. Current owner must be set. Does not
* change ownership of the objects in the bucket. */
virtual int chown(const DoutPrefixProvider* dpp, User& new_user, optional_yield y) = 0;
/** Store the cached bucket info into the backing store */
virtual int put_info(const DoutPrefixProvider* dpp, bool exclusive, ceph::real_time mtime, optional_yield y) = 0;
/** Check to see if the given user is the owner of this bucket */
virtual bool is_owner(User* user) = 0;
/** Get the owner of this bucket */
virtual User* get_owner(void) = 0;
/** Get the owner of this bucket in the form of an ACLOwner object */
virtual ACLOwner get_acl_owner(void) = 0;
/** Check in the backing store if this bucket is empty */
virtual int check_empty(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Chec k if the given size fits within the quota */
virtual int check_quota(const DoutPrefixProvider *dpp, RGWQuota& quota, uint64_t obj_size, optional_yield y, bool check_size_only = false) = 0;
/** Set the attributes in attrs, leaving any other existing attrs set, and
* write them to the backing store; a merge operation */
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp, Attrs& new_attrs, optional_yield y) = 0;
/** Try to refresh the cached bucket info from the backing store. Used in
* read-modify-update loop. */
virtual int try_refresh_info(const DoutPrefixProvider* dpp, ceph::real_time* pmtime, optional_yield y) = 0;
/** Read usage information about this bucket from the backing store */
virtual int read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) = 0;
/** Trim the usage information to the given epoch range */
virtual int trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y) = 0;
/** Remove objects from the bucket index of this bucket. May be removed from API */
virtual int remove_objs_from_index(const DoutPrefixProvider *dpp, std::list<rgw_obj_index_key>& objs_to_unlink) = 0;
/** Check the state of the bucket index, and get stats from it. May be removed from API */
virtual int check_index(const DoutPrefixProvider *dpp, std::map<RGWObjCategory, RGWStorageStats>& existing_stats, std::map<RGWObjCategory, RGWStorageStats>& calculated_stats) = 0;
/** Rebuild the bucket index. May be removed from API */
virtual int rebuild_index(const DoutPrefixProvider *dpp) = 0;
/** Set a timeout on the check_index() call. May be removed from API */
virtual int set_tag_timeout(const DoutPrefixProvider *dpp, uint64_t timeout) = 0;
/** Remove this specific bucket instance from the backing store. May be removed from API */
virtual int purge_instance(const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Set the cached object count of this bucket */
virtual void set_count(uint64_t _count) = 0;
/** Set the cached size of this bucket */
virtual void set_size(uint64_t _size) = 0;
/** Check if this instantiation is empty */
virtual bool empty() const = 0;
/** Get the cached name of this bucket */
virtual const std::string& get_name() const = 0;
/** Get the cached tenant of this bucket */
virtual const std::string& get_tenant() const = 0;
/** Get the cached marker of this bucket */
virtual const std::string& get_marker() const = 0;
/** Get the cached ID of this bucket */
virtual const std::string& get_bucket_id() const = 0;
/** Get the cached size of this bucket */
virtual size_t get_size() const = 0;
/** Get the cached rounded size of this bucket */
virtual size_t get_size_rounded() const = 0;
/** Get the cached object count of this bucket */
virtual uint64_t get_count() const = 0;
/** Get the cached placement rule of this bucket */
virtual rgw_placement_rule& get_placement_rule() = 0;
/** Get the cached creation time of this bucket */
virtual ceph::real_time& get_creation_time() = 0;
/** Get the cached modification time of this bucket */
virtual ceph::real_time& get_modification_time() = 0;
/** Get the cached version of this bucket */
virtual obj_version& get_version() = 0;
/** Set the cached version of this bucket */
virtual void set_version(obj_version &ver) = 0;
/** Check if this bucket is versioned */
virtual bool versioned() = 0;
/** Check if this bucket has versioning enabled */
virtual bool versioning_enabled() = 0;
/** Check if a Bucket pointer is empty */
static bool empty(const Bucket* b) { return (!b || b->empty()); }
/** Check if a Bucket unique pointer is empty */
static bool empty(const std::unique_ptr<Bucket>& b) { return (!b || b->empty()); }
/** Clone a copy of this bucket. Used when modification is necessary of the copy */
virtual std::unique_ptr<Bucket> clone() = 0;
/** Create a multipart upload in this bucket */
virtual std::unique_ptr<MultipartUpload> get_multipart_upload(
const std::string& oid,
std::optional<std::string> upload_id=std::nullopt,
ACLOwner owner={}, ceph::real_time mtime=real_clock::now()) = 0;
/** List multipart uploads currently in this bucket */
virtual int list_multiparts(const DoutPrefixProvider *dpp,
const std::string& prefix,
std::string& marker,
const std::string& delim,
const int& max_uploads,
std::vector<std::unique_ptr<MultipartUpload>>& uploads,
std::map<std::string, bool> *common_prefixes,
bool *is_truncated, optional_yield y) = 0;
/** Abort multipart uploads in a bucket */
virtual int abort_multiparts(const DoutPrefixProvider* dpp,
CephContext* cct, optional_yield y) = 0;
/** Read the bucket notification config into @a notifications with and (optionally) @a objv_tracker */
virtual int read_topics(rgw_pubsub_bucket_topics& notifications,
RGWObjVersionTracker* objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0;
/** Write @a notifications with (optionally) @a objv_tracker into the bucket notification config */
virtual int write_topics(const rgw_pubsub_bucket_topics& notifications, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) = 0;
/** Remove the bucket notification config with (optionally) @a objv_tracker */
virtual int remove_topics(RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) = 0;
/* dang - This is temporary, until the API is completed */
virtual rgw_bucket& get_key() = 0;
virtual RGWBucketInfo& get_info() = 0;
/** Print the User to @a out */
virtual void print(std::ostream& out) const = 0;
friend inline std::ostream& operator<<(std::ostream& out, const Bucket& b) {
b.print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const Bucket* b) {
if (!b)
out << "<NULL>";
else
b->print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const std::unique_ptr<Bucket>& p) {
out << p.get();
return out;
}
virtual bool operator==(const Bucket& b) const = 0;
virtual bool operator!=(const Bucket& b) const = 0;
friend class BucketList;
};
/**
* @brief A list of buckets
*
* This is the result from a bucket listing operation.
*/
class BucketList {
std::map<std::string, std::unique_ptr<Bucket>> buckets;
bool truncated;
public:
BucketList() : buckets(), truncated(false) {}
BucketList(BucketList&& _bl) :
buckets(std::move(_bl.buckets)),
truncated(_bl.truncated)
{ }
BucketList& operator=(const BucketList&) = delete;
BucketList& operator=(BucketList&& _bl) {
for (auto& ent : _bl.buckets) {
buckets.emplace(ent.first, std::move(ent.second));
}
truncated = _bl.truncated;
return *this;
};
/** Get the list of buckets. The list is a map of <bucket-name, Bucket> pairs. */
std::map<std::string, std::unique_ptr<Bucket>>& get_buckets() { return buckets; }
/** True if the list is truncated (that is, there are more buckets to list) */
bool is_truncated(void) const { return truncated; }
/** Set the truncated state of the list */
void set_truncated(bool trunc) { truncated = trunc; }
/** Add a bucket to the list. Takes ownership of the bucket */
void add(std::unique_ptr<Bucket> bucket) {
buckets.emplace(bucket->get_name(), std::move(bucket));
}
/** The number of buckets in this list */
size_t count() const { return buckets.size(); }
/** Clear the list */
void clear(void) {
buckets.clear();
truncated = false;
}
};
/**
* @brief Object abstraction
*
* This represents an Object. An Object is the basic unit of data storage. It
* represents a blob of data, a set of metadata (such as size, owner, ACLs, etc.) and
* a set of key/value attributes. Objects may be versioned. If a versioned object
* is written to, a new object with the same name but a different version is created,
* and the old version of the object is still accessible. If an unversioned object
* is written to, it is replaced, and the old data is not accessible.
*/
class Object {
public:
/**
* @brief Read operation on an Object
*
* This represents a Read operation on an Object. Read operations are optionally
* asynchronous, using the iterate() API.
*/
struct ReadOp {
struct Params {
const ceph::real_time* mod_ptr{nullptr};
const ceph::real_time* unmod_ptr{nullptr};
bool high_precision_time{false};
uint32_t mod_zone_id{0};
uint64_t mod_pg_ver{0};
const char* if_match{nullptr};
const char* if_nomatch{nullptr};
ceph::real_time* lastmod{nullptr};
rgw_obj* target_obj{nullptr}; // XXX dang remove?
} params;
virtual ~ReadOp() = default;
/** Prepare the Read op. Must be called first */
virtual int prepare(optional_yield y, const DoutPrefixProvider* dpp) = 0;
/** Synchronous read. Read from @a ofs to @a end (inclusive)
* into @a bl. Length is `end - ofs + 1`. */
virtual int read(int64_t ofs, int64_t end, bufferlist& bl,
optional_yield y, const DoutPrefixProvider* dpp) = 0;
/** Asynchronous read. Read from @a ofs to @a end (inclusive)
* calling @a cb on each read chunk. Length is `end - ofs +
* 1`. */
virtual int iterate(const DoutPrefixProvider* dpp, int64_t ofs,
int64_t end, RGWGetDataCB* cb, optional_yield y) = 0;
/** Get an attribute by name */
virtual int get_attr(const DoutPrefixProvider* dpp, const char* name, bufferlist& dest, optional_yield y) = 0;
};
/**
* @brief Delete operation on an Object
*
* This deletes an Object from the backing store.
*/
struct DeleteOp {
struct Params {
ACLOwner bucket_owner;
ACLOwner obj_owner;
int versioning_status{0};
uint64_t olh_epoch{0};
std::string marker_version_id;
uint32_t bilog_flags{0};
std::list<rgw_obj_index_key>* remove_objs{nullptr};
ceph::real_time expiration_time;
ceph::real_time unmod_since;
ceph::real_time mtime;
bool high_precision_time{false};
rgw_zone_set* zones_trace{nullptr};
bool abortmp{false};
uint64_t parts_accounted_size{0};
} params;
struct Result {
bool delete_marker{false};
std::string version_id;
} result;
virtual ~DeleteOp() = default;
/** Delete the object */
virtual int delete_obj(const DoutPrefixProvider* dpp, optional_yield y) = 0;
};
Object() {}
virtual ~Object() = default;
/** Shortcut synchronous delete call for common deletes */
virtual int delete_object(const DoutPrefixProvider* dpp,
optional_yield y,
bool prevent_versioning = false) = 0;
/** Copy an this object to another object. */
virtual int copy_object(User* user,
req_info* info, const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object, rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket,
const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime, ceph::real_time* mtime,
const ceph::real_time* mod_ptr, const ceph::real_time* unmod_ptr,
bool high_precision_time,
const char* if_match, const char* if_nomatch,
AttrsMod attrs_mod, bool copy_if_newer, Attrs& attrs,
RGWObjCategory category, uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at,
std::string* version_id, std::string* tag, std::string* etag,
void (*progress_cb)(off_t, void *), void* progress_data,
const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Get the ACL for this object */
virtual RGWAccessControlPolicy& get_acl(void) = 0;
/** Set the ACL for this object */
virtual int set_acl(const RGWAccessControlPolicy& acl) = 0;
/** Mark further operations on this object as being atomic */
virtual void set_atomic() = 0;
/** Check if this object is atomic */
virtual bool is_atomic() = 0;
/** Pre-fetch data when reading */
virtual void set_prefetch_data() = 0;
/** Check if this object should prefetch */
virtual bool is_prefetch_data() = 0;
/** Mark data as compressed */
virtual void set_compressed() = 0;
/** Check if this object is compressed */
virtual bool is_compressed() = 0;
/** Invalidate cached info about this object, except atomic, prefetch, and
* compressed */
virtual void invalidate() = 0;
/** Check to see if this object has an empty key. This means it's uninitialized */
virtual bool empty() const = 0;
/** Get the name of this object */
virtual const std::string &get_name() const = 0;
/** Get the object state for this object. Will be removed in the future */
virtual int get_obj_state(const DoutPrefixProvider* dpp, RGWObjState **state, optional_yield y, bool follow_olh = true) = 0;
/** Set the object state for this object */
virtual void set_obj_state(RGWObjState& _state) = 0;
/** Set attributes for this object from the backing store. Attrs can be set or
* deleted. @note the attribute APIs may be revisited in the future. */
virtual int set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs, Attrs* delattrs, optional_yield y) = 0;
/** Get attributes for this object */
virtual int get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp, rgw_obj* target_obj = NULL) = 0;
/** Modify attributes for this object. */
virtual int modify_obj_attrs(const char* attr_name, bufferlist& attr_val, optional_yield y, const DoutPrefixProvider* dpp) = 0;
/** Delete attributes for this object */
virtual int delete_obj_attrs(const DoutPrefixProvider* dpp, const char* attr_name, optional_yield y) = 0;
/** Check to see if this object has expired */
virtual bool is_expired() = 0;
/** Create a randomized instance ID for this object */
virtual void gen_rand_obj_instance_name() = 0;
/** Get a multipart serializer for this object */
virtual std::unique_ptr<MPSerializer> get_serializer(const DoutPrefixProvider *dpp,
const std::string& lock_name) = 0;
/** Move the data of an object to new placement storage */
virtual int transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime,
uint64_t olh_epoch,
const DoutPrefixProvider* dpp,
optional_yield y) = 0;
/** Move an object to the cloud */
virtual int transition_to_cloud(Bucket* bucket,
rgw::sal::PlacementTier* tier,
rgw_bucket_dir_entry& o,
std::set<std::string>& cloud_targets,
CephContext* cct,
bool update_object,
const DoutPrefixProvider* dpp,
optional_yield y) = 0;
/** Check to see if two placement rules match */
virtual bool placement_rules_match(rgw_placement_rule& r1, rgw_placement_rule& r2) = 0;
/** Dump driver-specific object layout info in JSON */
virtual int dump_obj_layout(const DoutPrefixProvider *dpp, optional_yield y, Formatter* f) = 0;
/** Get the cached attributes for this object */
virtual Attrs& get_attrs(void) = 0;
/** Get the (const) cached attributes for this object */
virtual const Attrs& get_attrs(void) const = 0;
/** Set the cached attributes for this object */
virtual int set_attrs(Attrs a) = 0;
/** Check to see if attributes are cached on this object */
virtual bool has_attrs(void) = 0;
/** Get the cached modification time for this object */
virtual ceph::real_time get_mtime(void) const = 0;
/** Get the cached size for this object */
virtual uint64_t get_obj_size(void) const = 0;
/** Get the bucket containing this object */
virtual Bucket* get_bucket(void) const = 0;
/** Set the bucket containing this object */
virtual void set_bucket(Bucket* b) = 0;
/** Get the sharding hash representation of this object */
virtual std::string get_hash_source(void) = 0;
/** Set the sharding hash representation of this object */
virtual void set_hash_source(std::string s) = 0;
/** Build an Object Identifier string for this object */
virtual std::string get_oid(void) const = 0;
/** True if this object is a delete marker (newest version is deleted) */
virtual bool get_delete_marker(void) = 0;
/** True if this object is stored in the extra data pool */
virtual bool get_in_extra_data(void) = 0;
/** Set the in_extra_data field */
virtual void set_in_extra_data(bool i) = 0;
/** Helper to sanitize object size, offset, and end values */
int range_to_ofs(uint64_t obj_size, int64_t &ofs, int64_t &end);
/** Set the cached size of this object */
virtual void set_obj_size(uint64_t s) = 0;
/** Set the cached name of this object */
virtual void set_name(const std::string& n) = 0;
/** Set the cached key of this object */
virtual void set_key(const rgw_obj_key& k) = 0;
/** Get an rgw_obj representing this object */
virtual rgw_obj get_obj(void) const = 0;
/** Restore the previous swift version of this object */
virtual int swift_versioning_restore(bool& restored, /* out */
const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Copy the current version of a swift object to the configured destination bucket*/
virtual int swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y) = 0;
/** Get a new ReadOp for this object */
virtual std::unique_ptr<ReadOp> get_read_op() = 0;
/** Get a new DeleteOp for this object */
virtual std::unique_ptr<DeleteOp> get_delete_op() = 0;
/// Return stored torrent info or -ENOENT if there isn't any.
virtual int get_torrent_info(const DoutPrefixProvider* dpp,
optional_yield y, bufferlist& bl) = 0;
/** Get the OMAP values matching the given set of keys */
virtual int omap_get_vals_by_keys(const DoutPrefixProvider *dpp, const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals) = 0;
/** Get a single OMAP value matching the given key */
virtual int omap_set_val_by_key(const DoutPrefixProvider *dpp, const std::string& key, bufferlist& val,
bool must_exist, optional_yield y) = 0;
/** Change the ownership of this object */
virtual int chown(User& new_user, const DoutPrefixProvider* dpp, optional_yield y) = 0;
/** Check to see if the given object pointer is uninitialized */
static bool empty(const Object* o) { return (!o || o->empty()); }
/** Check to see if the given object unique pointer is uninitialized */
static bool empty(const std::unique_ptr<Object>& o) { return (!o || o->empty()); }
/** Get a unique copy of this object */
virtual std::unique_ptr<Object> clone() = 0;
/* dang - This is temporary, until the API is completed */
/** Get the key for this object */
virtual rgw_obj_key& get_key() = 0;
/** Set the instance for this object */
virtual void set_instance(const std::string &i) = 0;
/** Get the instance for this object */
virtual const std::string &get_instance() const = 0;
/** Check to see if this object has an instance set */
virtual bool have_instance(void) = 0;
/** Clear the instance on this object */
virtual void clear_instance() = 0;
/** Print the User to @a out */
virtual void print(std::ostream& out) const = 0;
friend inline std::ostream& operator<<(std::ostream& out, const Object& o) {
o.print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const Object* o) {
if (!o)
out << "<NULL>";
else
o->print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const std::unique_ptr<Object>& p) {
out << p.get();
return out;
}
};
/**
* @brief Abstraction of a single part of a multipart upload
*/
class MultipartPart {
public:
MultipartPart() = default;
virtual ~MultipartPart() = default;
/** Get the part number of this part */
virtual uint32_t get_num() = 0;
/** Get the size of this part */
virtual uint64_t get_size() = 0;
/** Get the etag of this part */
virtual const std::string& get_etag() = 0;
/** Get the modification time of this part */
virtual ceph::real_time& get_mtime() = 0;
};
/**
* @brief Abstraction of a multipart upload
*
* This represents a multipart upload. For large objects, it's inefficient to do a
* single, long-lived upload of the object. Instead, protocols such as S3 allow the
* client to start a multipart upload, and then upload object in smaller parts in
* parallel. A MultipartUpload consists of a target bucket, a unique identifier, and a
* set of upload parts.
*/
class MultipartUpload {
public:
MultipartUpload() = default;
virtual ~MultipartUpload() = default;
/** Get the name of the object representing this upload in the backing store */
virtual const std::string& get_meta() const = 0;
/** Get the name of the target object for this upload */
virtual const std::string& get_key() const = 0;
/** Get the unique ID of this upload */
virtual const std::string& get_upload_id() const = 0;
/** Get the owner of this upload */
virtual const ACLOwner& get_owner() const = 0;
/** Get the modification time of this upload */
virtual ceph::real_time& get_mtime() = 0;
/** Get all the cached parts that make up this upload */
virtual std::map<uint32_t, std::unique_ptr<MultipartPart>>& get_parts() = 0;
/** Get the trace context of this upload */
virtual const jspan_context& get_trace() = 0;
/** Get the Object that represents this upload */
virtual std::unique_ptr<rgw::sal::Object> get_meta_obj() = 0;
/** Initialize this upload */
virtual int init(const DoutPrefixProvider* dpp, optional_yield y, ACLOwner& owner, rgw_placement_rule& dest_placement, rgw::sal::Attrs& attrs) = 0;
/** List all the parts of this upload, filling the parts cache */
virtual int list_parts(const DoutPrefixProvider* dpp, CephContext* cct,
int num_parts, int marker,
int* next_marker, bool* truncated, optional_yield y,
bool assume_unsorted = false) = 0;
/** Abort this upload */
virtual int abort(const DoutPrefixProvider* dpp, CephContext* cct, optional_yield y) = 0;
/** Complete this upload, making it available as a normal object */
virtual int complete(const DoutPrefixProvider* dpp,
optional_yield y, CephContext* cct,
std::map<int, std::string>& part_etags,
std::list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed,
RGWCompressionInfo& cs_info, off_t& ofs,
std::string& tag, ACLOwner& owner,
uint64_t olh_epoch,
rgw::sal::Object* target_obj) = 0;
/** Get placement and/or attribute info for this upload */
virtual int get_info(const DoutPrefixProvider *dpp, optional_yield y, rgw_placement_rule** rule, rgw::sal::Attrs* attrs = nullptr) = 0;
/** Get a Writer to write to a part of this upload */
virtual std::unique_ptr<Writer> get_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t part_num,
const std::string& part_num_str) = 0;
/** Print the Upload to @a out */
virtual void print(std::ostream& out) const = 0;
friend inline std::ostream& operator<<(std::ostream& out, const MultipartUpload& u) {
u.print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const MultipartUpload* u) {
if (!u)
out << "<NULL>";
else
u->print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const
std::unique_ptr<MultipartUpload>& p) {
out << p.get();
return out;
}
};
/**
* @brief Interface of a lock/serialization
*/
class Serializer {
public:
Serializer() = default;
virtual ~Serializer() = default;
/** Try to take the lock for the given amount of time. */
virtual int try_lock(const DoutPrefixProvider *dpp, utime_t dur, optional_yield y) = 0;
/** Unlock the lock */
virtual int unlock() = 0;
/** Print the Serializer to @a out */
virtual void print(std::ostream& out) const = 0;
friend inline std::ostream& operator<<(std::ostream& out, const Serializer& s) {
s.print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const Serializer* s) {
if (!s)
out << "<NULL>";
else
s->print(out);
return out;
}
};
/** @brief Abstraction of a serializer for multipart uploads
*/
class MPSerializer : public Serializer {
public:
MPSerializer() = default;
virtual ~MPSerializer() = default;
virtual void clear_locked() = 0;
/** Check to see if locked */
virtual bool is_locked() = 0;
};
/** @brief Abstraction of a serializer for Lifecycle
*/
class LCSerializer : public Serializer {
public:
LCSerializer() {}
virtual ~LCSerializer() = default;
};
/**
* @brief Abstraction for lifecycle processing
*
* Lifecycle processing loops over the objects in a bucket, applying per-bucket policy
* to each object. Examples of policy can be deleting after a certain amount of time,
* deleting extra versions, changing the storage class, and so on.
*/
class Lifecycle {
public:
/** Head of a lifecycle run. Used for tracking parallel lifecycle runs. */
struct LCHead {
LCHead() = default;
virtual ~LCHead() = default;
virtual time_t& get_start_date() = 0;
virtual void set_start_date(time_t) = 0;
virtual std::string& get_marker() = 0;
virtual void set_marker(const std::string&) = 0;
virtual time_t& get_shard_rollover_date() = 0;
virtual void set_shard_rollover_date(time_t) = 0;
};
/** Single entry in a lifecycle run. Multiple entries can exist processing different
* buckets. */
struct LCEntry {
LCEntry() = default;
virtual ~LCEntry() = default;
virtual std::string& get_bucket() = 0;
virtual void set_bucket(const std::string&) = 0;
virtual std::string& get_oid() = 0;
virtual void set_oid(const std::string&) = 0;
virtual uint64_t get_start_time() = 0;
virtual void set_start_time(uint64_t) = 0;
virtual uint32_t get_status() = 0;
virtual void set_status(uint32_t) = 0;
/** Print the entry to @a out */
virtual void print(std::ostream& out) const = 0;
friend inline std::ostream& operator<<(std::ostream& out, const LCEntry& e) {
e.print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const LCEntry* e) {
if (!e)
out << "<NULL>";
else
e->print(out);
return out;
}
friend inline std::ostream& operator<<(std::ostream& out, const std::unique_ptr<LCEntry>& p) {
out << p.get();
return out;
}
};
Lifecycle() = default;
virtual ~Lifecycle() = default;
/** Get an empty entry */
virtual std::unique_ptr<LCEntry> get_entry() = 0;
/** Get an entry matching the given marker */
virtual int get_entry(const std::string& oid, const std::string& marker, std::unique_ptr<LCEntry>* entry) = 0;
/** Get the entry following the given marker */
virtual int get_next_entry(const std::string& oid, const std::string& marker, std::unique_ptr<LCEntry>* entry) = 0;
/** Store a modified entry in then backing store */
virtual int set_entry(const std::string& oid, LCEntry& entry) = 0;
/** List all known entries */
virtual int list_entries(const std::string& oid, const std::string& marker,
uint32_t max_entries,
std::vector<std::unique_ptr<LCEntry>>& entries) = 0;
/** Remove an entry from the backing store */
virtual int rm_entry(const std::string& oid, LCEntry& entry) = 0;
/** Get a head */
virtual int get_head(const std::string& oid, std::unique_ptr<LCHead>* head) = 0;
/** Store a modified head to the backing store */
virtual int put_head(const std::string& oid, LCHead& head) = 0;
/** Get a serializer for lifecycle */
virtual std::unique_ptr<LCSerializer> get_serializer(const std::string& lock_name,
const std::string& oid,
const std::string& cookie) = 0;
};
/**
* @brief Abstraction for a Notification event
*
* RGW can generate notifications for various events, such as object creation or
* deletion.
*/
class Notification {
protected:
public:
Notification() {}
virtual ~Notification() = default;
/** Indicate the start of the event associated with this notification */
virtual int publish_reserve(const DoutPrefixProvider *dpp, RGWObjTags* obj_tags = nullptr) = 0;
/** Indicate the successful completion of the event associated with this notification */
virtual int publish_commit(const DoutPrefixProvider* dpp, uint64_t size,
const ceph::real_time& mtime, const std::string& etag, const std::string& version) = 0;
};
/**
* @brief Abstraction for an asynchronous writer
*
* Writing is done through a set of filters. This allows chaining filters to do things
* like compression and encryption on async writes. This is the base abstraction for
* those filters.
*/
class Writer : public ObjectProcessor {
public:
Writer() {}
virtual ~Writer() = default;
/** prepare to start processing object data */
virtual int prepare(optional_yield y) = 0;
/**
* Process a buffer. Called multiple times to write different buffers.
* data.length() == 0 indicates the last call and may be used to flush
* the data buffers.
*/
virtual int process(bufferlist&& data, uint64_t offset) = 0;
/** complete the operation and make its result visible to clients */
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y) = 0;
};
/**
* @brief Abstraction of a placement tier
*
* This abstraction allows access to information about placement tiers,
* including storage class.
*/
class PlacementTier {
public:
virtual ~PlacementTier() = default;
/** Get the type of this tier */
virtual const std::string& get_tier_type() = 0;
/** Get the storage class of this tier */
virtual const std::string& get_storage_class() = 0;
/** Should we retain the head object when transitioning */
virtual bool retain_head_object() = 0;
/** Get the placement rule associated with this tier */
};
/**
* @brief Abstraction of a zone group
*
* This class allows access to information about a zonegroup. It may be the
* group containing the current zone, or another group.
*/
class ZoneGroup {
public:
virtual ~ZoneGroup() = default;
/** Get the ID of this zonegroup */
virtual const std::string& get_id() const = 0;
/** Get the name of this zonegroup */
virtual const std::string& get_name() const = 0;
/** Determine if two zonegroups are the same */
virtual int equals(const std::string& other_zonegroup) const = 0;
/** Get the endpoint from zonegroup, or from master zone if not set */
virtual const std::string& get_endpoint() const = 0;
/** Check if a placement target (by name) exists in this zonegroup */
virtual bool placement_target_exists(std::string& target) const = 0;
/** Check if this is the master zonegroup */
virtual bool is_master_zonegroup() const = 0;
/** Get the API name of this zonegroup */
virtual const std::string& get_api_name() const = 0;
/** Get the list of placement target names for this zone */
virtual int get_placement_target_names(std::set<std::string>& names) const = 0;
/** Get the name of the default placement target for this zone */
virtual const std::string& get_default_placement_name() const = 0;
/** Get the list of hostnames from this zone */
virtual int get_hostnames(std::list<std::string>& names) const = 0;
/** Get the list of hostnames that host s3 websites from this zone */
virtual int get_s3website_hostnames(std::list<std::string>& names) const = 0;
/** Get the number of zones in this zonegroup */
virtual int get_zone_count() const = 0;
/** Get the placement tier associated with the rule */
virtual int get_placement_tier(const rgw_placement_rule& rule, std::unique_ptr<PlacementTier>* tier) = 0;
/** Get a zone by ID */
virtual int get_zone_by_id(const std::string& id, std::unique_ptr<Zone>* zone) = 0;
/** Get a zone by Name */
virtual int get_zone_by_name(const std::string& name, std::unique_ptr<Zone>* zone) = 0;
/** List zones in zone group by ID */
virtual int list_zones(std::list<std::string>& zone_ids) = 0;
/** Clone a copy of this zonegroup. */
virtual std::unique_ptr<ZoneGroup> clone() = 0;
};
/**
* @brief Abstraction of a Zone
*
* This abstraction allows access to information about zones. This can be the zone
* containing the RGW, or another zone.
*/
class Zone {
public:
virtual ~Zone() = default;
/** Clone a copy of this zone. */
virtual std::unique_ptr<Zone> clone() = 0;
/** Get info about the zonegroup containing this zone */
virtual ZoneGroup& get_zonegroup() = 0;
/** Get the ID of this zone */
virtual const std::string& get_id() = 0;
/** Get the name of this zone */
virtual const std::string& get_name() const = 0;
/** True if this zone is writable */
virtual bool is_writeable() = 0;
/** Get the URL for the endpoint for redirecting to this zone */
virtual bool get_redirect_endpoint(std::string* endpoint) = 0;
/** Check to see if the given API is supported in this zone */
virtual bool has_zonegroup_api(const std::string& api) const = 0;
/** Get the current period ID for this zone */
virtual const std::string& get_current_period_id() = 0;
/** Get thes system access key for this zone */
virtual const RGWAccessKey& get_system_key() = 0;
/** Get the name of the realm containing this zone */
virtual const std::string& get_realm_name() = 0;
/** Get the ID of the realm containing this zone */
virtual const std::string& get_realm_id() = 0;
/** Get the tier type for the zone */
virtual const std::string_view get_tier_type() = 0;
/** Get a handler for zone sync policy. */
virtual RGWBucketSyncPolicyHandlerRef get_sync_policy_handler() = 0;
};
/**
* @brief Abstraction of a manager for Lua scripts and packages
*
* RGW can load and process Lua scripts. This will handle loading/storing scripts; adding, deleting, and listing packages
*/
class LuaManager {
public:
virtual ~LuaManager() = default;
/** Get a script named with the given key from the backing store */
virtual int get_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, std::string& script) = 0;
/** Put a script named with the given key to the backing store */
virtual int put_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, const std::string& script) = 0;
/** Delete a script named with the given key from the backing store */
virtual int del_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key) = 0;
/** Add a lua package */
virtual int add_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name) = 0;
/** Remove a lua package */
virtual int remove_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name) = 0;
/** List lua packages */
virtual int list_packages(const DoutPrefixProvider* dpp, optional_yield y, rgw::lua::packages_t& packages) = 0;
};
/** @} namespace rgw::sal in group RGWSAL */
} } // namespace rgw::sal
/**
* @brief A manager for Drivers
*
* This will manage the singleton instances of the various drivers. Drivers come in two
* varieties: Full and Raw. A full driver is suitable for use in a radosgw daemon. It
* has full access to the cluster, if any. A raw driver is a stripped down driver, used
* for admin commands.
*/
class DriverManager {
public:
struct Config {
/** Name of store to create */
std::string store_name;
/** Name of filter to create or "none" */
std::string filter_name;
};
DriverManager() {}
/** Get a full driver by service name */
static rgw::sal::Driver* get_storage(const DoutPrefixProvider* dpp,
CephContext* cct,
const Config& cfg,
bool use_gc_thread,
bool use_lc_thread,
bool quota_threads,
bool run_sync_thread,
bool run_reshard_thread,
bool run_notification_thread, optional_yield y,
bool use_cache = true,
bool use_gc = true) {
rgw::sal::Driver* driver = init_storage_provider(dpp, cct, cfg, use_gc_thread,
use_lc_thread,
quota_threads,
run_sync_thread,
run_reshard_thread,
run_notification_thread,
use_cache, use_gc, y);
return driver;
}
/** Get a stripped down driver by service name */
static rgw::sal::Driver* get_raw_storage(const DoutPrefixProvider* dpp,
CephContext* cct, const Config& cfg) {
rgw::sal::Driver* driver = init_raw_storage_provider(dpp, cct, cfg);
return driver;
}
/** Initialize a new full Driver */
static rgw::sal::Driver* init_storage_provider(const DoutPrefixProvider* dpp,
CephContext* cct,
const Config& cfg,
bool use_gc_thread,
bool use_lc_thread,
bool quota_threads,
bool run_sync_thread,
bool run_reshard_thread,
bool run_notification_thread,
bool use_metadata_cache,
bool use_gc, optional_yield y);
/** Initialize a new raw Driver */
static rgw::sal::Driver* init_raw_storage_provider(const DoutPrefixProvider* dpp,
CephContext* cct,
const Config& cfg);
/** Close a Driver when it's no longer needed */
static void close_storage(rgw::sal::Driver* driver);
/** Get the config for Drivers */
static Config get_config(bool admin, CephContext* cct);
/** Create a ConfigStore */
static auto create_config_store(const DoutPrefixProvider* dpp,
std::string_view type)
-> std::unique_ptr<rgw::sal::ConfigStore>;
};
/** @} */
| 70,616 | 42.059146 | 203 |
h
|
null |
ceph-main/src/rgw/rgw_sal_config.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 <memory>
#include <optional>
#include <span>
#include <string>
#include "rgw_sal_fwd.h"
class DoutPrefixProvider;
class optional_yield;
struct RGWPeriod;
struct RGWPeriodConfig;
struct RGWRealm;
struct RGWZoneGroup;
struct RGWZoneParams;
namespace rgw::sal {
/// Results of a listing operation
template <typename T>
struct ListResult {
/// The subspan of the input entries that contain results
std::span<T> entries;
/// The next marker to resume listing, or empty
std::string next;
};
/// Storage abstraction for realm/zonegroup/zone configuration
class ConfigStore {
public:
virtual ~ConfigStore() {}
/// @group Realm
///@{
/// Set the cluster-wide default realm id
virtual int write_default_realm_id(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
std::string_view realm_id) = 0;
/// Read the cluster's default realm id
virtual int read_default_realm_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string& realm_id) = 0;
/// Delete the cluster's default realm id
virtual int delete_default_realm_id(const DoutPrefixProvider* dpp,
optional_yield y) = 0;
/// Create a realm
virtual int create_realm(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
const RGWRealm& info,
std::unique_ptr<RealmWriter>* writer) = 0;
/// Read a realm by id
virtual int read_realm_by_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id,
RGWRealm& info,
std::unique_ptr<RealmWriter>* writer) = 0;
/// Read a realm by name
virtual int read_realm_by_name(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_name,
RGWRealm& info,
std::unique_ptr<RealmWriter>* writer) = 0;
/// Read the cluster's default realm
virtual int read_default_realm(const DoutPrefixProvider* dpp,
optional_yield y,
RGWRealm& info,
std::unique_ptr<RealmWriter>* writer) = 0;
/// Look up a realm id by its name
virtual int read_realm_id(const DoutPrefixProvider* dpp,
optional_yield y, std::string_view realm_name,
std::string& realm_id) = 0;
/// Notify the cluster of a new period, so radosgws can reload with the new
/// configuration
virtual int realm_notify_new_period(const DoutPrefixProvider* dpp,
optional_yield y,
const RGWPeriod& period) = 0;
/// List up to 'entries.size()' realm names starting from the given marker
virtual int list_realm_names(const DoutPrefixProvider* dpp,
optional_yield y, const std::string& marker,
std::span<std::string> entries,
ListResult<std::string>& result) = 0;
///@}
/// @group Period
///@{
/// Write a period and advance its latest epoch
virtual int create_period(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
const RGWPeriod& info) = 0;
/// Read a period by id and epoch. If no epoch is given, read the latest
virtual int read_period(const DoutPrefixProvider* dpp,
optional_yield y, std::string_view period_id,
std::optional<uint32_t> epoch, RGWPeriod& info) = 0;
/// Delete all period epochs with the given period id
virtual int delete_period(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view period_id) = 0;
/// List up to 'entries.size()' period ids starting from the given marker
virtual int list_period_ids(const DoutPrefixProvider* dpp,
optional_yield y, const std::string& marker,
std::span<std::string> entries,
ListResult<std::string>& result) = 0;
///@}
/// @group ZoneGroup
///@{
/// Set the cluster-wide default zonegroup id
virtual int write_default_zonegroup_id(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
std::string_view realm_id,
std::string_view zonegroup_id) = 0;
/// Read the cluster's default zonegroup id
virtual int read_default_zonegroup_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id,
std::string& zonegroup_id) = 0;
/// Delete the cluster's default zonegroup id
virtual int delete_default_zonegroup_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id) = 0;
/// Create a zonegroup
virtual int create_zonegroup(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
const RGWZoneGroup& info,
std::unique_ptr<ZoneGroupWriter>* writer) = 0;
/// Read a zonegroup by id
virtual int read_zonegroup_by_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view zonegroup_id,
RGWZoneGroup& info,
std::unique_ptr<ZoneGroupWriter>* writer) = 0;
/// Read a zonegroup by name
virtual int read_zonegroup_by_name(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view zonegroup_name,
RGWZoneGroup& info,
std::unique_ptr<ZoneGroupWriter>* writer) = 0;
/// Read the cluster's default zonegroup
virtual int read_default_zonegroup(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id,
RGWZoneGroup& info,
std::unique_ptr<ZoneGroupWriter>* writer) = 0;
/// List up to 'entries.size()' zonegroup names starting from the given marker
virtual int list_zonegroup_names(const DoutPrefixProvider* dpp,
optional_yield y, const std::string& marker,
std::span<std::string> entries,
ListResult<std::string>& result) = 0;
///@}
/// @group Zone
///@{
/// Set the realm-wide default zone id
virtual int write_default_zone_id(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
std::string_view realm_id,
std::string_view zone_id) = 0;
/// Read the realm's default zone id
virtual int read_default_zone_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id,
std::string& zone_id) = 0;
/// Delete the realm's default zone id
virtual int delete_default_zone_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id) = 0;
/// Create a zone
virtual int create_zone(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
const RGWZoneParams& info,
std::unique_ptr<ZoneWriter>* writer) = 0;
/// Read a zone by id
virtual int read_zone_by_id(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view zone_id,
RGWZoneParams& info,
std::unique_ptr<ZoneWriter>* writer) = 0;
/// Read a zone by id or name. If both are empty, try to load the
/// cluster's default zone
virtual int read_zone_by_name(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view zone_name,
RGWZoneParams& info,
std::unique_ptr<ZoneWriter>* writer) = 0;
/// Read the realm's default zone
virtual int read_default_zone(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id,
RGWZoneParams& info,
std::unique_ptr<ZoneWriter>* writer) = 0;
/// List up to 'entries.size()' zone names starting from the given marker
virtual int list_zone_names(const DoutPrefixProvider* dpp,
optional_yield y, const std::string& marker,
std::span<std::string> entries,
ListResult<std::string>& result) = 0;
///@}
/// @group PeriodConfig
///@{
/// Read period config object
virtual int read_period_config(const DoutPrefixProvider* dpp,
optional_yield y,
std::string_view realm_id,
RGWPeriodConfig& info) = 0;
/// Write period config object
virtual int write_period_config(const DoutPrefixProvider* dpp,
optional_yield y, bool exclusive,
std::string_view realm_id,
const RGWPeriodConfig& info) = 0;
///@}
}; // ConfigStore
/// A handle to manage the atomic updates of an existing realm object. This
/// is initialized on read, and any subsequent writes through this handle will
/// fail with -ECANCELED if another writer updates the object in the meantime.
class RealmWriter {
public:
virtual ~RealmWriter() {}
/// Overwrite an existing realm. Must not change id or name
virtual int write(const DoutPrefixProvider* dpp,
optional_yield y,
const RGWRealm& info) = 0;
/// Rename an existing realm. Must not change id
virtual int rename(const DoutPrefixProvider* dpp,
optional_yield y,
RGWRealm& info,
std::string_view new_name) = 0;
/// Delete an existing realm
virtual int remove(const DoutPrefixProvider* dpp,
optional_yield y) = 0;
};
/// A handle to manage the atomic updates of an existing zonegroup object. This
/// is initialized on read, and any subsequent writes through this handle will
/// fail with -ECANCELED if another writer updates the object in the meantime.
class ZoneGroupWriter {
public:
virtual ~ZoneGroupWriter() {}
/// Overwrite an existing zonegroup. Must not change id or name
virtual int write(const DoutPrefixProvider* dpp,
optional_yield y,
const RGWZoneGroup& info) = 0;
/// Rename an existing zonegroup. Must not change id
virtual int rename(const DoutPrefixProvider* dpp,
optional_yield y,
RGWZoneGroup& info,
std::string_view new_name) = 0;
/// Delete an existing zonegroup
virtual int remove(const DoutPrefixProvider* dpp,
optional_yield y) = 0;
};
/// A handle to manage the atomic updates of an existing zone object. This
/// is initialized on read, and any subsequent writes through this handle will
/// fail with -ECANCELED if another writer updates the object in the meantime.
class ZoneWriter {
public:
virtual ~ZoneWriter() {}
/// Overwrite an existing zone. Must not change id or name
virtual int write(const DoutPrefixProvider* dpp,
optional_yield y,
const RGWZoneParams& info) = 0;
/// Rename an existing zone. Must not change id
virtual int rename(const DoutPrefixProvider* dpp,
optional_yield y,
RGWZoneParams& info,
std::string_view new_name) = 0;
/// Delete an existing zone
virtual int remove(const DoutPrefixProvider* dpp,
optional_yield y) = 0;
};
} // namespace rgw::sal
| 13,345 | 43.192053 | 83 |
h
|
null |
ceph-main/src/rgw/rgw_sal_daos.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=2 sw=2 expandtab ft=cpp
/*
* Ceph - scalable distributed file system
*
* SAL implementation for the CORTX DAOS backend
*
* Copyright (C) 2022 Seagate Technology LLC and/or its Affiliates
*
* 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_sal_daos.h"
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <filesystem>
#include <system_error>
#include "common/Clock.h"
#include "common/errno.h"
#include "rgw_bucket.h"
#include "rgw_compression.h"
#include "rgw_sal.h"
#define dout_subsys ceph_subsys_rgw
using std::list;
using std::map;
using std::set;
using std::string;
using std::vector;
namespace fs = std::filesystem;
namespace rgw::sal {
using ::ceph::decode;
using ::ceph::encode;
int DaosUser::list_buckets(const DoutPrefixProvider* dpp, const string& marker,
const string& end_marker, uint64_t max,
bool need_stats, BucketList& buckets,
optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: list_user_buckets: marker=" << marker
<< " end_marker=" << end_marker << " max=" << max << dendl;
int ret = 0;
bool is_truncated = false;
buckets.clear();
vector<struct ds3_bucket_info> bucket_infos(max);
daos_size_t bcount = bucket_infos.size();
vector<vector<uint8_t>> values(bcount, vector<uint8_t>(DS3_MAX_ENCODED_LEN));
for (daos_size_t i = 0; i < bcount; i++) {
bucket_infos[i].encoded = values[i].data();
bucket_infos[i].encoded_length = values[i].size();
}
char daos_marker[DS3_MAX_BUCKET_NAME];
std::strncpy(daos_marker, marker.c_str(), sizeof(daos_marker));
ret = ds3_bucket_list(&bcount, bucket_infos.data(), daos_marker,
&is_truncated, store->ds3, nullptr);
ldpp_dout(dpp, 20) << "DEBUG: ds3_bucket_list: bcount=" << bcount
<< " ret=" << ret << dendl;
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: ds3_bucket_list failed!" << ret << dendl;
return ret;
}
bucket_infos.resize(bcount);
values.resize(bcount);
for (const auto& bi : bucket_infos) {
DaosBucketInfo dbinfo;
bufferlist bl;
bl.append(reinterpret_cast<char*>(bi.encoded), bi.encoded_length);
auto iter = bl.cbegin();
dbinfo.decode(iter);
buckets.add(std::make_unique<DaosBucket>(this->store, dbinfo.info, this));
}
buckets.set_truncated(is_truncated);
return 0;
}
int DaosUser::create_bucket(
const DoutPrefixProvider* dpp, const rgw_bucket& b,
const std::string& zonegroup_id, rgw_placement_rule& placement_rule,
std::string& swift_ver_location, const RGWQuotaInfo* pquota_info,
const RGWAccessControlPolicy& policy, Attrs& attrs, RGWBucketInfo& info,
obj_version& ep_objv, bool exclusive, bool obj_lock_enabled, bool* existed,
req_info& req_info, std::unique_ptr<Bucket>* bucket_out, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: create_bucket:" << b.name << dendl;
int ret;
std::unique_ptr<Bucket> bucket;
// Look up the bucket. Create it if it doesn't exist.
ret = this->store->get_bucket(dpp, this, b, &bucket, y);
if (ret != 0 && ret != -ENOENT) {
return ret;
}
if (ret != -ENOENT) {
*existed = true;
if (swift_ver_location.empty()) {
swift_ver_location = bucket->get_info().swift_ver_location;
}
placement_rule.inherit_from(bucket->get_info().placement_rule);
// TODO: ACL policy
// // don't allow changes to the acl policy
// RGWAccessControlPolicy old_policy(ctx());
// int rc = rgw_op_get_bucket_policy_from_attr(
// dpp, this, u, bucket->get_attrs(), &old_policy, y);
// if (rc >= 0 && old_policy != policy) {
// bucket_out->swap(bucket);
// return -EEXIST;
//}
} else {
placement_rule.name = "default";
placement_rule.storage_class = "STANDARD";
bucket = std::make_unique<DaosBucket>(store, b, this);
bucket->set_attrs(attrs);
*existed = false;
}
// TODO: how to handle zone and multi-site.
if (!*existed) {
info.placement_rule = placement_rule;
info.bucket = b;
info.owner = this->get_info().user_id;
info.zonegroup = zonegroup_id;
info.creation_time = ceph::real_clock::now();
if (obj_lock_enabled)
info.flags = BUCKET_VERSIONED | BUCKET_OBJ_LOCK_ENABLED;
bucket->set_version(ep_objv);
bucket->get_info() = info;
// Create a new bucket:
DaosBucket* daos_bucket = static_cast<DaosBucket*>(bucket.get());
bufferlist bl;
std::unique_ptr<struct ds3_bucket_info> bucket_info =
daos_bucket->get_encoded_info(bl, ceph::real_time());
ret = ds3_bucket_create(bucket->get_name().c_str(), bucket_info.get(),
nullptr, store->ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: ds3_bucket_create failed! ret=" << ret
<< dendl;
return ret;
}
} else {
bucket->set_version(ep_objv);
bucket->get_info() = info;
}
bucket_out->swap(bucket);
return ret;
}
int DaosUser::read_attrs(const DoutPrefixProvider* dpp, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosUser::read_stats(const DoutPrefixProvider* dpp, optional_yield y,
RGWStorageStats* stats,
ceph::real_time* last_stats_sync,
ceph::real_time* last_stats_update) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
/* stats - Not for first pass */
int DaosUser::read_stats_async(const DoutPrefixProvider* dpp,
RGWGetUserStats_CB* cb) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosUser::complete_flush_stats(const DoutPrefixProvider* dpp,
optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosUser::read_usage(const DoutPrefixProvider* dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
map<rgw_user_bucket, rgw_usage_log_entry>& usage) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosUser::trim_usage(const DoutPrefixProvider* dpp, uint64_t start_epoch,
uint64_t end_epoch) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosUser::load_user(const DoutPrefixProvider* dpp, optional_yield y) {
const string name = info.user_id.to_str();
ldpp_dout(dpp, 20) << "DEBUG: load_user, name=" << name << dendl;
DaosUserInfo duinfo;
int ret = read_user(dpp, name, &duinfo);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: load_user failed, name=" << name << dendl;
return ret;
}
info = duinfo.info;
attrs = duinfo.attrs;
objv_tracker.read_version = duinfo.user_version;
return 0;
}
int DaosUser::merge_and_store_attrs(const DoutPrefixProvider* dpp,
Attrs& new_attrs, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: merge_and_store_attrs, new_attrs=" << new_attrs
<< dendl;
for (auto& it : new_attrs) {
attrs[it.first] = it.second;
}
return store_user(dpp, y, false);
}
int DaosUser::store_user(const DoutPrefixProvider* dpp, optional_yield y,
bool exclusive, RGWUserInfo* old_info) {
const string name = info.user_id.to_str();
ldpp_dout(dpp, 10) << "DEBUG: Store_user(): User name=" << name << dendl;
// Read user
int ret = 0;
struct DaosUserInfo duinfo;
ret = read_user(dpp, name, &duinfo);
obj_version obj_ver = duinfo.user_version;
std::unique_ptr<struct ds3_user_info> old_user_info;
std::vector<const char*> old_access_ids;
// Check if the user already exists
if (ret == 0 && obj_ver.ver) {
// already exists.
if (old_info) {
*old_info = duinfo.info;
}
if (objv_tracker.read_version.ver != obj_ver.ver) {
// Object version mismatch.. return ECANCELED
ret = -ECANCELED;
ldpp_dout(dpp, 0) << "User Read version mismatch read_version="
<< objv_tracker.read_version.ver
<< " obj_ver=" << obj_ver.ver << dendl;
return ret;
}
if (exclusive) {
// return
return ret;
}
obj_ver.ver++;
for (auto const& [id, key] : duinfo.info.access_keys) {
old_access_ids.push_back(id.c_str());
}
old_user_info.reset(
new ds3_user_info{.name = duinfo.info.user_id.to_str().c_str(),
.email = duinfo.info.user_email.c_str(),
.access_ids = old_access_ids.data(),
.access_ids_nr = old_access_ids.size()});
} else {
obj_ver.ver = 1;
obj_ver.tag = "UserTAG";
}
bufferlist bl;
std::unique_ptr<struct ds3_user_info> user_info =
get_encoded_info(bl, obj_ver);
ret = ds3_user_set(name.c_str(), user_info.get(), old_user_info.get(),
store->ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "Error: ds3_user_set failed, name=" << name
<< " ret=" << ret << dendl;
}
return ret;
}
int DaosUser::read_user(const DoutPrefixProvider* dpp, std::string name,
DaosUserInfo* duinfo) {
// Initialize ds3_user_info
bufferlist bl;
uint64_t size = DS3_MAX_ENCODED_LEN;
struct ds3_user_info user_info = {.encoded = bl.append_hole(size).c_str(),
.encoded_length = size};
int ret = ds3_user_get(name.c_str(), &user_info, store->ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "Error: ds3_user_get failed, name=" << name
<< " ret=" << ret << dendl;
return ret;
}
// Decode
bufferlist& blr = bl;
auto iter = blr.cbegin();
duinfo->decode(iter);
return ret;
}
std::unique_ptr<struct ds3_user_info> DaosUser::get_encoded_info(
bufferlist& bl, obj_version& obj_ver) {
// Encode user data
struct DaosUserInfo duinfo;
duinfo.info = info;
duinfo.attrs = attrs;
duinfo.user_version = obj_ver;
duinfo.encode(bl);
// Initialize ds3_user_info
access_ids.clear();
for (auto const& [id, key] : info.access_keys) {
access_ids.push_back(id.c_str());
}
return std::unique_ptr<struct ds3_user_info>(
new ds3_user_info{.name = info.user_id.to_str().c_str(),
.email = info.user_email.c_str(),
.access_ids = access_ids.data(),
.access_ids_nr = access_ids.size(),
.encoded = bl.c_str(),
.encoded_length = bl.length()});
}
int DaosUser::remove_user(const DoutPrefixProvider* dpp, optional_yield y) {
const string name = info.user_id.to_str();
// TODO: the expectation is that the object version needs to be passed in as a
// method arg see int DB::remove_user(const DoutPrefixProvider *dpp,
// RGWUserInfo& uinfo, RGWObjVersionTracker *pobjv)
obj_version obj_ver;
bufferlist bl;
std::unique_ptr<struct ds3_user_info> user_info =
get_encoded_info(bl, obj_ver);
// Remove user
int ret = ds3_user_remove(name.c_str(), user_info.get(), store->ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "Error: ds3_user_set failed, name=" << name
<< " ret=" << ret << dendl;
}
return ret;
}
DaosBucket::~DaosBucket() { close(nullptr); }
int DaosBucket::open(const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: open, name=" << info.bucket.name.c_str()
<< dendl;
// Idempotent
if (is_open()) {
return 0;
}
int ret = ds3_bucket_open(get_name().c_str(), &ds3b, store->ds3, nullptr);
ldpp_dout(dpp, 20) << "DEBUG: ds3_bucket_open, name=" << get_name()
<< ", ret=" << ret << dendl;
return ret;
}
int DaosBucket::close(const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: close" << dendl;
// Idempotent
if (!is_open()) {
return 0;
}
int ret = ds3_bucket_close(ds3b, nullptr);
ds3b = nullptr;
ldpp_dout(dpp, 20) << "DEBUG: ds3_bucket_close ret=" << ret << dendl;
return ret;
}
std::unique_ptr<struct ds3_bucket_info> DaosBucket::get_encoded_info(
bufferlist& bl, ceph::real_time _mtime) {
DaosBucketInfo dbinfo;
dbinfo.info = info;
dbinfo.bucket_attrs = attrs;
dbinfo.mtime = _mtime;
dbinfo.bucket_version = bucket_version;
dbinfo.encode(bl);
auto bucket_info = std::make_unique<struct ds3_bucket_info>();
bucket_info->encoded = bl.c_str();
bucket_info->encoded_length = bl.length();
std::strncpy(bucket_info->name, get_name().c_str(), sizeof(bucket_info->name));
return bucket_info;
}
int DaosBucket::remove_bucket(const DoutPrefixProvider* dpp,
bool delete_children, bool forward_to_master,
req_info* req_info, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: remove_bucket, delete_children="
<< delete_children
<< " forward_to_master=" << forward_to_master << dendl;
return ds3_bucket_destroy(get_name().c_str(), delete_children, store->ds3,
nullptr);
}
int DaosBucket::remove_bucket_bypass_gc(int concurrent_max,
bool keep_index_consistent,
optional_yield y,
const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: remove_bucket_bypass_gc, concurrent_max="
<< concurrent_max
<< " keep_index_consistent=" << keep_index_consistent
<< dendl;
return ds3_bucket_destroy(get_name().c_str(), true, store->ds3, nullptr);
}
int DaosBucket::put_info(const DoutPrefixProvider* dpp, bool exclusive,
ceph::real_time _mtime) {
ldpp_dout(dpp, 20) << "DEBUG: put_info(): bucket name=" << get_name()
<< dendl;
int ret = open(dpp);
if (ret != 0) {
return ret;
}
bufferlist bl;
std::unique_ptr<struct ds3_bucket_info> bucket_info =
get_encoded_info(bl, ceph::real_time());
ret = ds3_bucket_set_info(bucket_info.get(), ds3b, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: ds3_bucket_set_info failed: " << ret << dendl;
}
return ret;
}
int DaosBucket::load_bucket(const DoutPrefixProvider* dpp, optional_yield y,
bool get_stats) {
ldpp_dout(dpp, 20) << "DEBUG: load_bucket(): bucket name=" << get_name()
<< dendl;
int ret = open(dpp);
if (ret != 0) {
return ret;
}
bufferlist bl;
DaosBucketInfo dbinfo;
uint64_t size = DS3_MAX_ENCODED_LEN;
struct ds3_bucket_info bucket_info = {.encoded = bl.append_hole(size).c_str(),
.encoded_length = size};
ret = ds3_bucket_get_info(&bucket_info, ds3b, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: ds3_bucket_get_info failed: " << ret << dendl;
return ret;
}
auto iter = bl.cbegin();
dbinfo.decode(iter);
info = dbinfo.info;
rgw_placement_rule placement_rule;
placement_rule.name = "default";
placement_rule.storage_class = "STANDARD";
info.placement_rule = placement_rule;
attrs = dbinfo.bucket_attrs;
mtime = dbinfo.mtime;
bucket_version = dbinfo.bucket_version;
return ret;
}
/* stats - Not for first pass */
int DaosBucket::read_stats(const DoutPrefixProvider* dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, std::string* bucket_ver,
std::string* master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string* max_marker, bool* syncstopped) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::read_stats_async(
const DoutPrefixProvider* dpp,
const bucket_index_layout_generation& idx_layout, int shard_id,
RGWGetBucketStats_CB* ctx) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::sync_user_stats(const DoutPrefixProvider* dpp,
optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::update_container_stats(const DoutPrefixProvider* dpp) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::check_bucket_shards(const DoutPrefixProvider* dpp) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::chown(const DoutPrefixProvider* dpp, User& new_user,
optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
/* Make sure to call load_bucket() if you need it first */
bool DaosBucket::is_owner(User* user) {
return (info.owner.compare(user->get_id()) == 0);
}
int DaosBucket::check_empty(const DoutPrefixProvider* dpp, optional_yield y) {
/* XXX: Check if bucket contains any objects */
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::check_quota(const DoutPrefixProvider* dpp, RGWQuota& quota,
uint64_t obj_size, optional_yield y,
bool check_size_only) {
/* Not Handled in the first pass as stats are also needed */
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::merge_and_store_attrs(const DoutPrefixProvider* dpp,
Attrs& new_attrs, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: merge_and_store_attrs, new_attrs=" << new_attrs
<< dendl;
for (auto& it : new_attrs) {
attrs[it.first] = it.second;
}
return put_info(dpp, y, ceph::real_time());
}
int DaosBucket::try_refresh_info(const DoutPrefixProvider* dpp,
ceph::real_time* pmtime) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
/* XXX: usage and stats not supported in the first pass */
int DaosBucket::read_usage(const DoutPrefixProvider* dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
map<rgw_user_bucket, rgw_usage_log_entry>& usage) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::trim_usage(const DoutPrefixProvider* dpp, uint64_t start_epoch,
uint64_t end_epoch) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::remove_objs_from_index(
const DoutPrefixProvider* dpp,
std::list<rgw_obj_index_key>& objs_to_unlink) {
/* XXX: CHECK: Unlike RadosStore, there is no seperate bucket index table.
* Delete all the object in the list from the object table of this
* bucket
*/
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::check_index(
const DoutPrefixProvider* dpp,
std::map<RGWObjCategory, RGWStorageStats>& existing_stats,
std::map<RGWObjCategory, RGWStorageStats>& calculated_stats) {
/* XXX: stats not supported yet */
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::rebuild_index(const DoutPrefixProvider* dpp) {
/* there is no index table in DAOS. Not applicable */
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::set_tag_timeout(const DoutPrefixProvider* dpp,
uint64_t timeout) {
/* XXX: CHECK: set tag timeout for all the bucket objects? */
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::purge_instance(const DoutPrefixProvider* dpp) {
/* XXX: CHECK: for DAOS only single instance supported.
* Remove all the objects for that instance? Anything extra needed?
*/
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosBucket::set_acl(const DoutPrefixProvider* dpp,
RGWAccessControlPolicy& acl, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: set_acl" << dendl;
int ret = 0;
bufferlist aclbl;
acls = acl;
acl.encode(aclbl);
Attrs attrs = get_attrs();
attrs[RGW_ATTR_ACL] = aclbl;
return ret;
}
std::unique_ptr<Object> DaosBucket::get_object(const rgw_obj_key& k) {
return std::make_unique<DaosObject>(this->store, k, this);
}
bool compare_rgw_bucket_dir_entry(rgw_bucket_dir_entry& entry1,
rgw_bucket_dir_entry& entry2) {
return (entry1.key < entry2.key);
}
bool compare_multipart_upload(std::unique_ptr<MultipartUpload>& upload1,
std::unique_ptr<MultipartUpload>& upload2) {
return (upload1->get_key() < upload2->get_key());
}
int DaosBucket::list(const DoutPrefixProvider* dpp, ListParams& params, int max,
ListResults& results, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: list bucket=" << get_name() << " max=" << max
<< " params=" << params << dendl;
// End
if (max == 0) {
return 0;
}
int ret = open(dpp);
if (ret != 0) {
return ret;
}
// Init needed structures
vector<struct ds3_object_info> object_infos(max);
uint32_t nobj = object_infos.size();
vector<vector<uint8_t>> values(nobj, vector<uint8_t>(DS3_MAX_ENCODED_LEN));
for (uint32_t i = 0; i < nobj; i++) {
object_infos[i].encoded = values[i].data();
object_infos[i].encoded_length = values[i].size();
}
vector<struct ds3_common_prefix_info> common_prefixes(max);
uint32_t ncp = common_prefixes.size();
char daos_marker[DS3_MAX_KEY_BUFF];
std::strncpy(daos_marker, params.marker.get_oid().c_str(), sizeof(daos_marker));
ret = ds3_bucket_list_obj(&nobj, object_infos.data(), &ncp,
common_prefixes.data(), params.prefix.c_str(),
params.delim.c_str(), daos_marker,
params.list_versions, &results.is_truncated, ds3b);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: ds3_bucket_list_obj failed, name="
<< get_name() << ", ret=" << ret << dendl;
return ret;
}
object_infos.resize(nobj);
values.resize(nobj);
common_prefixes.resize(ncp);
// Fill common prefixes
for (auto const& cp : common_prefixes) {
results.common_prefixes[cp.prefix] = true;
}
// Decode objs
for (auto const& obj : object_infos) {
bufferlist bl;
rgw_bucket_dir_entry ent;
bl.append(reinterpret_cast<char*>(obj.encoded), obj.encoded_length);
auto iter = bl.cbegin();
ent.decode(iter);
if (params.list_versions || ent.is_visible()) {
results.objs.emplace_back(std::move(ent));
}
}
if (!params.allow_unordered) {
std::sort(results.objs.begin(), results.objs.end(),
compare_rgw_bucket_dir_entry);
}
return ret;
}
int DaosBucket::list_multiparts(
const DoutPrefixProvider* dpp, const string& prefix, string& marker,
const string& delim, const int& max_uploads,
vector<std::unique_ptr<MultipartUpload>>& uploads,
map<string, bool>* common_prefixes, bool* is_truncated) {
ldpp_dout(dpp, 20) << "DEBUG: list_multiparts" << dendl;
// End of uploading
if (max_uploads == 0) {
*is_truncated = false;
return 0;
}
// Init needed structures
vector<struct ds3_multipart_upload_info> multipart_upload_infos(max_uploads);
uint32_t nmp = multipart_upload_infos.size();
vector<vector<uint8_t>> values(nmp, vector<uint8_t>(DS3_MAX_ENCODED_LEN));
for (uint32_t i = 0; i < nmp; i++) {
multipart_upload_infos[i].encoded = values[i].data();
multipart_upload_infos[i].encoded_length = values[i].size();
}
vector<struct ds3_common_prefix_info> cps(max_uploads);
uint32_t ncp = cps.size();
char daos_marker[DS3_MAX_KEY_BUFF];
std::strncpy(daos_marker, marker.c_str(), sizeof(daos_marker));
int ret = ds3_bucket_list_multipart(
get_name().c_str(), &nmp, multipart_upload_infos.data(), &ncp, cps.data(),
prefix.c_str(), delim.c_str(), daos_marker, is_truncated, store->ds3);
multipart_upload_infos.resize(nmp);
values.resize(nmp);
cps.resize(ncp);
// Fill common prefixes
for (auto const& cp : cps) {
(*common_prefixes)[cp.prefix] = true;
}
for (auto const& mp : multipart_upload_infos) {
// Decode the xattr
bufferlist bl;
rgw_bucket_dir_entry ent;
bl.append(reinterpret_cast<char*>(mp.encoded), mp.encoded_length);
auto iter = bl.cbegin();
ent.decode(iter);
string name = ent.key.name;
ACLOwner owner(rgw_user(ent.meta.owner));
owner.set_name(ent.meta.owner_display_name);
uploads.push_back(this->get_multipart_upload(
name, mp.upload_id, std::move(owner), ent.meta.mtime));
}
// Sort uploads
std::sort(uploads.begin(), uploads.end(), compare_multipart_upload);
return ret;
}
int DaosBucket::abort_multiparts(const DoutPrefixProvider* dpp,
CephContext* cct) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
void DaosStore::finalize(void) {
ldout(cctx, 20) << "DEBUG: finalize" << dendl;
int ret;
ret = ds3_disconnect(ds3, nullptr);
if (ret != 0) {
ldout(cctx, 0) << "ERROR: ds3_disconnect() failed: " << ret << dendl;
}
ds3 = nullptr;
ret = ds3_fini();
if (ret != 0) {
ldout(cctx, 0) << "ERROR: daos_fini() failed: " << ret << dendl;
}
}
int DaosStore::initialize(CephContext* cct, const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: initialize" << dendl;
int ret = ds3_init();
// DS3 init failed, allow the case where init is already done
if (ret != 0 && ret != DER_ALREADY) {
ldout(cct, 0) << "ERROR: ds3_init() failed: " << ret << dendl;
return ret;
}
// XXX: these params should be taken from config settings and
// cct somehow?
const auto& daos_pool = cct->_conf.get_val<std::string>("daos_pool");
ldout(cct, 20) << "INFO: daos pool: " << daos_pool << dendl;
ret = ds3_connect(daos_pool.c_str(), nullptr, &ds3, nullptr);
if (ret != 0) {
ldout(cct, 0) << "ERROR: ds3_connect() failed: " << ret << dendl;
ds3_fini();
}
return ret;
}
const std::string& DaosZoneGroup::get_endpoint() const {
if (!group.endpoints.empty()) {
return group.endpoints.front();
} else {
// use zonegroup's master zone endpoints
auto z = group.zones.find(group.master_zone);
if (z != group.zones.end() && !z->second.endpoints.empty()) {
return z->second.endpoints.front();
}
}
return empty;
}
bool DaosZoneGroup::placement_target_exists(std::string& target) const {
return !!group.placement_targets.count(target);
}
int DaosZoneGroup::get_placement_target_names(
std::set<std::string>& names) const {
for (const auto& target : group.placement_targets) {
names.emplace(target.second.name);
}
return 0;
}
int DaosZoneGroup::get_placement_tier(const rgw_placement_rule& rule,
std::unique_ptr<PlacementTier>* tier) {
std::map<std::string, RGWZoneGroupPlacementTarget>::const_iterator titer;
titer = group.placement_targets.find(rule.name);
if (titer == group.placement_targets.end()) {
return -ENOENT;
}
const auto& target_rule = titer->second;
std::map<std::string, RGWZoneGroupPlacementTier>::const_iterator ttier;
ttier = target_rule.tier_targets.find(rule.storage_class);
if (ttier == target_rule.tier_targets.end()) {
// not found
return -ENOENT;
}
PlacementTier* t;
t = new DaosPlacementTier(store, ttier->second);
if (!t) return -ENOMEM;
tier->reset(t);
return 0;
}
ZoneGroup& DaosZone::get_zonegroup() { return zonegroup; }
int DaosZone::get_zonegroup(const std::string& id,
std::unique_ptr<ZoneGroup>* group) {
/* XXX: for now only one zonegroup supported */
ZoneGroup* zg;
zg = new DaosZoneGroup(store, zonegroup.get_group());
group->reset(zg);
return 0;
}
const rgw_zone_id& DaosZone::get_id() { return cur_zone_id; }
const std::string& DaosZone::get_name() const {
return zone_params->get_name();
}
bool DaosZone::is_writeable() { return true; }
bool DaosZone::get_redirect_endpoint(std::string* endpoint) { return false; }
bool DaosZone::has_zonegroup_api(const std::string& api) const { return false; }
const std::string& DaosZone::get_current_period_id() {
return current_period->get_id();
}
std::unique_ptr<LuaManager> DaosStore::get_lua_manager() {
return std::make_unique<DaosLuaManager>(this);
}
int DaosObject::get_obj_state(const DoutPrefixProvider* dpp,
RGWObjState** _state, optional_yield y,
bool follow_olh) {
// Get object's metadata (those stored in rgw_bucket_dir_entry)
ldpp_dout(dpp, 20) << "DEBUG: get_obj_state" << dendl;
rgw_bucket_dir_entry ent;
*_state = &state; // state is required even if a failure occurs
int ret = get_dir_entry_attrs(dpp, &ent);
if (ret != 0) {
return ret;
}
// Set object state.
state.exists = true;
state.size = ent.meta.size;
state.accounted_size = ent.meta.size;
state.mtime = ent.meta.mtime;
state.has_attrs = true;
bufferlist etag_bl;
string& etag = ent.meta.etag;
ldpp_dout(dpp, 20) << __func__ << ": object's etag: " << ent.meta.etag
<< dendl;
etag_bl.append(etag);
state.attrset[RGW_ATTR_ETAG] = etag_bl;
return 0;
}
DaosObject::~DaosObject() { close(nullptr); }
int DaosObject::set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs,
Attrs* delattrs, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: DaosObject::set_obj_attrs()" << dendl;
// TODO handle target_obj
// Get object's metadata (those stored in rgw_bucket_dir_entry)
rgw_bucket_dir_entry ent;
int ret = get_dir_entry_attrs(dpp, &ent);
if (ret != 0) {
return ret;
}
// Update object metadata
Attrs updateattrs = setattrs == nullptr ? attrs : *setattrs;
if (delattrs) {
for (auto const& [attr, attrval] : *delattrs) {
updateattrs.erase(attr);
}
}
ret = set_dir_entry_attrs(dpp, &ent, &updateattrs);
return ret;
}
int DaosObject::get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp,
rgw_obj* target_obj) {
ldpp_dout(dpp, 20) << "DEBUG: DaosObject::get_obj_attrs()" << dendl;
// TODO handle target_obj
// Get object's metadata (those stored in rgw_bucket_dir_entry)
rgw_bucket_dir_entry ent;
int ret = get_dir_entry_attrs(dpp, &ent, &attrs);
return ret;
}
int DaosObject::modify_obj_attrs(const char* attr_name, bufferlist& attr_val,
optional_yield y,
const DoutPrefixProvider* dpp) {
// Get object's metadata (those stored in rgw_bucket_dir_entry)
ldpp_dout(dpp, 20) << "DEBUG: modify_obj_attrs" << dendl;
rgw_bucket_dir_entry ent;
int ret = get_dir_entry_attrs(dpp, &ent, &attrs);
if (ret != 0) {
return ret;
}
// Update object attrs
set_atomic();
attrs[attr_name] = attr_val;
ret = set_dir_entry_attrs(dpp, &ent, &attrs);
return ret;
}
int DaosObject::delete_obj_attrs(const DoutPrefixProvider* dpp,
const char* attr_name, optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: delete_obj_attrs" << dendl;
rgw_obj target = get_obj();
Attrs rmattr;
bufferlist bl;
rmattr[attr_name] = bl;
return set_obj_attrs(dpp, nullptr, &rmattr, y);
}
bool DaosObject::is_expired() {
auto iter = attrs.find(RGW_ATTR_DELETE_AT);
if (iter != attrs.end()) {
utime_t delete_at;
try {
auto bufit = iter->second.cbegin();
decode(delete_at, bufit);
} catch (buffer::error& err) {
ldout(store->ctx(), 0)
<< "ERROR: " << __func__
<< ": failed to decode " RGW_ATTR_DELETE_AT " attr" << dendl;
return false;
}
if (delete_at <= ceph_clock_now() && !delete_at.is_zero()) {
return true;
}
}
return false;
}
// Taken from rgw_rados.cc
void DaosObject::gen_rand_obj_instance_name() {
enum { OBJ_INSTANCE_LEN = 32 };
char buf[OBJ_INSTANCE_LEN + 1];
gen_rand_alphanumeric_no_underscore(store->ctx(), buf, OBJ_INSTANCE_LEN);
state.obj.key.set_instance(buf);
}
int DaosObject::omap_get_vals_by_keys(const DoutPrefixProvider* dpp,
const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosObject::omap_set_val_by_key(const DoutPrefixProvider* dpp,
const std::string& key, bufferlist& val,
bool must_exist, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosObject::chown(User& new_user, const DoutPrefixProvider* dpp, optional_yield y) {
return 0;
}
std::unique_ptr<MPSerializer> DaosObject::get_serializer(
const DoutPrefixProvider* dpp, const std::string& lock_name) {
return std::make_unique<MPDaosSerializer>(dpp, store, this, lock_name);
}
int DaosObject::transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime, uint64_t olh_epoch,
const DoutPrefixProvider* dpp, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosObject::transition_to_cloud(
Bucket* bucket, rgw::sal::PlacementTier* tier, rgw_bucket_dir_entry& o,
std::set<std::string>& cloud_targets, CephContext* cct, bool update_object,
const DoutPrefixProvider* dpp, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
bool DaosObject::placement_rules_match(rgw_placement_rule& r1,
rgw_placement_rule& r2) {
/* XXX: support single default zone and zonegroup for now */
return true;
}
int DaosObject::dump_obj_layout(const DoutPrefixProvider* dpp, optional_yield y,
Formatter* f) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
std::unique_ptr<Object::ReadOp> DaosObject::get_read_op() {
return std::make_unique<DaosObject::DaosReadOp>(this);
}
DaosObject::DaosReadOp::DaosReadOp(DaosObject* _source) : source(_source) {}
int DaosObject::DaosReadOp::prepare(optional_yield y,
const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << __func__
<< ": bucket=" << source->get_bucket()->get_name()
<< dendl;
if (source->get_bucket()->versioned() && !source->have_instance()) {
// If the bucket is versioned and no version is specified, get the latest
// version
source->set_instance(DS3_LATEST_INSTANCE);
}
rgw_bucket_dir_entry ent;
int ret = source->get_dir_entry_attrs(dpp, &ent);
// Set source object's attrs. The attrs is key/value map and is used
// in send_response_data() to set attributes, including etag.
bufferlist etag_bl;
string& etag = ent.meta.etag;
ldpp_dout(dpp, 20) << __func__ << ": object's etag: " << ent.meta.etag
<< dendl;
etag_bl.append(etag.c_str(), etag.size());
source->get_attrs().emplace(std::move(RGW_ATTR_ETAG), std::move(etag_bl));
source->set_key(ent.key);
source->set_obj_size(ent.meta.size);
ldpp_dout(dpp, 20) << __func__ << ": object's size: " << ent.meta.size
<< dendl;
return ret;
}
int DaosObject::DaosReadOp::read(int64_t off, int64_t end, bufferlist& bl,
optional_yield y,
const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << __func__ << ": off=" << off << " end=" << end << dendl;
int ret = source->lookup(dpp);
if (ret != 0) {
return ret;
}
// Calculate size, end is inclusive
uint64_t size = end - off + 1;
// Read
ret = source->read(dpp, bl, off, size);
if (ret != 0) {
return ret;
}
return ret;
}
// RGWGetObj::execute() calls ReadOp::iterate() to read object from 'off' to
// 'end'. The returned data is processed in 'cb' which is a chain of
// post-processing filters such as decompression, de-encryption and sending back
// data to client (RGWGetObj_CB::handle_dta which in turn calls
// RGWGetObj::get_data_cb() to send data back.).
//
// POC implements a simple sync version of iterate() function in which it reads
// a block of data each time and call 'cb' for post-processing.
int DaosObject::DaosReadOp::iterate(const DoutPrefixProvider* dpp, int64_t off,
int64_t end, RGWGetDataCB* cb,
optional_yield y) {
ldpp_dout(dpp, 20) << __func__ << ": off=" << off << " end=" << end << dendl;
int ret = source->lookup(dpp);
if (ret != 0) {
return ret;
}
// Calculate size, end is inclusive
uint64_t size = end - off + 1;
// Reserve buffers and read
bufferlist bl;
ret = source->read(dpp, bl, off, size);
if (ret != 0) {
return ret;
}
// Call cb to process returned data.
ldpp_dout(dpp, 20) << __func__ << ": call cb to process data, actual=" << size
<< dendl;
cb->handle_data(bl, off, size);
return ret;
}
int DaosObject::DaosReadOp::get_attr(const DoutPrefixProvider* dpp,
const char* name, bufferlist& dest,
optional_yield y) {
Attrs attrs;
int ret = source->get_dir_entry_attrs(dpp, nullptr, &attrs);
if (!ret) {
return -ENODATA;
}
auto search = attrs.find(name);
if (search == attrs.end()) {
return -ENODATA;
}
dest = search->second;
return 0;
}
std::unique_ptr<Object::DeleteOp> DaosObject::get_delete_op() {
return std::make_unique<DaosObject::DaosDeleteOp>(this);
}
DaosObject::DaosDeleteOp::DaosDeleteOp(DaosObject* _source) : source(_source) {}
// Implementation of DELETE OBJ also requires DaosObject::get_obj_state()
// to retrieve and set object's state from object's metadata.
//
// TODO:
// 1. The POC only deletes the Daos objects. It doesn't handle the
// DeleteOp::params. Delete::delete_obj() in rgw_rados.cc shows how rados
// backend process the params.
// 2. Delete an object when its versioning is turned on.
// 3. Handle empty directories
// 4. Fail when file doesn't exist
int DaosObject::DaosDeleteOp::delete_obj(const DoutPrefixProvider* dpp,
optional_yield y) {
ldpp_dout(dpp, 20) << "DaosDeleteOp::delete_obj "
<< source->get_key().get_oid() << " from "
<< source->get_bucket()->get_name() << dendl;
if (source->get_instance() == "null") {
source->clear_instance();
}
// Open bucket
int ret = 0;
std::string key = source->get_key().get_oid();
DaosBucket* daos_bucket = source->get_daos_bucket();
ret = daos_bucket->open(dpp);
if (ret != 0) {
return ret;
}
// Remove the daos object
ret = ds3_obj_destroy(key.c_str(), daos_bucket->ds3b);
ldpp_dout(dpp, 20) << "DEBUG: ds3_obj_destroy key=" << key << " ret=" << ret
<< dendl;
// result.delete_marker = parent_op.result.delete_marker;
// result.version_id = parent_op.result.version_id;
return ret;
}
int DaosObject::delete_object(const DoutPrefixProvider* dpp, optional_yield y,
bool prevent_versioning) {
ldpp_dout(dpp, 20) << "DEBUG: delete_object" << dendl;
DaosObject::DaosDeleteOp del_op(this);
del_op.params.bucket_owner = bucket->get_info().owner;
del_op.params.versioning_status = bucket->get_info().versioning_status();
return del_op.delete_obj(dpp, y);
}
int DaosObject::copy_object(
User* user, req_info* info, const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object, rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket, const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime, ceph::real_time* mtime,
const ceph::real_time* mod_ptr, const ceph::real_time* unmod_ptr,
bool high_precision_time, const char* if_match, const char* if_nomatch,
AttrsMod attrs_mod, bool copy_if_newer, Attrs& attrs,
RGWObjCategory category, uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at, std::string* version_id,
std::string* tag, std::string* etag, void (*progress_cb)(off_t, void*),
void* progress_data, const DoutPrefixProvider* dpp, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosObject::swift_versioning_restore(bool& restored,
const DoutPrefixProvider* dpp) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosObject::swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosObject::lookup(const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: lookup" << dendl;
if (is_open()) {
return 0;
}
if (get_instance() == "null") {
clear_instance();
}
int ret = 0;
DaosBucket* daos_bucket = get_daos_bucket();
ret = daos_bucket->open(dpp);
if (ret != 0) {
return ret;
}
ret = ds3_obj_open(get_key().get_oid().c_str(), &ds3o, daos_bucket->ds3b);
if (ret == -ENOENT) {
ldpp_dout(dpp, 20) << "DEBUG: daos object (" << get_bucket()->get_name()
<< ", " << get_key().get_oid()
<< ") does not exist: ret=" << ret << dendl;
} else if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to open daos object ("
<< get_bucket()->get_name() << ", " << get_key().get_oid()
<< "): ret=" << ret << dendl;
}
return ret;
}
int DaosObject::create(const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: create" << dendl;
if (is_open()) {
return 0;
}
if (get_instance() == "null") {
clear_instance();
}
int ret = 0;
DaosBucket* daos_bucket = get_daos_bucket();
ret = daos_bucket->open(dpp);
if (ret != 0) {
return ret;
}
ret = ds3_obj_create(get_key().get_oid().c_str(), &ds3o, daos_bucket->ds3b);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to create daos object ("
<< get_bucket()->get_name() << ", " << get_key().get_oid()
<< "): ret=" << ret << dendl;
}
return ret;
}
int DaosObject::close(const DoutPrefixProvider* dpp) {
ldpp_dout(dpp, 20) << "DEBUG: close" << dendl;
if (!is_open()) {
return 0;
}
int ret = ds3_obj_close(ds3o);
ds3o = nullptr;
ldpp_dout(dpp, 20) << "DEBUG: ds3_obj_close ret=" << ret << dendl;
return ret;
}
int DaosObject::write(const DoutPrefixProvider* dpp, bufferlist&& data,
uint64_t offset) {
ldpp_dout(dpp, 20) << "DEBUG: write" << dendl;
uint64_t size = data.length();
int ret = ds3_obj_write(data.c_str(), offset, &size, get_daos_bucket()->ds3b,
ds3o, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to write into daos object ("
<< get_bucket()->get_name() << ", " << get_key().get_oid()
<< "): ret=" << ret << dendl;
}
return ret;
}
int DaosObject::read(const DoutPrefixProvider* dpp, bufferlist& data,
uint64_t offset, uint64_t& size) {
ldpp_dout(dpp, 20) << "DEBUG: read" << dendl;
int ret = ds3_obj_read(data.append_hole(size).c_str(), offset, &size,
get_daos_bucket()->ds3b, ds3o, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to read from daos object ("
<< get_bucket()->get_name() << ", " << get_key().get_oid()
<< "): ret=" << ret << dendl;
}
return ret;
}
// Get the object's dirent and attrs
int DaosObject::get_dir_entry_attrs(const DoutPrefixProvider* dpp,
rgw_bucket_dir_entry* ent,
Attrs* getattrs) {
ldpp_dout(dpp, 20) << "DEBUG: get_dir_entry_attrs" << dendl;
int ret = 0;
vector<uint8_t> value(DS3_MAX_ENCODED_LEN);
uint32_t size = value.size();
if (get_key().ns == RGW_OBJ_NS_MULTIPART) {
struct ds3_multipart_upload_info ui = {.encoded = value.data(),
.encoded_length = size};
ret = ds3_upload_get_info(&ui, bucket->get_name().c_str(),
get_key().get_oid().c_str(), store->ds3);
} else {
ret = lookup(dpp);
if (ret != 0) {
return ret;
}
auto object_info = std::make_unique<struct ds3_object_info>();
object_info->encoded = value.data();
object_info->encoded_length = size;
ret = ds3_obj_get_info(object_info.get(), get_daos_bucket()->ds3b, ds3o);
size = object_info->encoded_length;
}
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to get info of daos object ("
<< get_bucket()->get_name() << ", " << get_key().get_oid()
<< "): ret=" << ret << dendl;
return ret;
}
rgw_bucket_dir_entry dummy_ent;
if (!ent) {
// if ent is not passed, use a dummy ent
ent = &dummy_ent;
}
bufferlist bl;
bl.append(reinterpret_cast<char*>(value.data()), size);
auto iter = bl.cbegin();
ent->decode(iter);
if (getattrs) {
decode(*getattrs, iter);
}
return ret;
}
// Set the object's dirent and attrs
int DaosObject::set_dir_entry_attrs(const DoutPrefixProvider* dpp,
rgw_bucket_dir_entry* ent,
Attrs* setattrs) {
ldpp_dout(dpp, 20) << "DEBUG: set_dir_entry_attrs" << dendl;
int ret = lookup(dpp);
if (ret != 0) {
return ret;
}
// Set defaults
if (!ent) {
// if ent is not passed, return an error
return -EINVAL;
}
if (!setattrs) {
// if setattrs is not passed, use object attrs
setattrs = &attrs;
}
bufferlist wbl;
ent->encode(wbl);
encode(*setattrs, wbl);
// Write rgw_bucket_dir_entry into object xattr
auto object_info = std::make_unique<struct ds3_object_info>();
object_info->encoded = wbl.c_str();
object_info->encoded_length = wbl.length();
ret = ds3_obj_set_info(object_info.get(), get_daos_bucket()->ds3b, ds3o);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to set info of daos object ("
<< get_bucket()->get_name() << ", " << get_key().get_oid()
<< "): ret=" << ret << dendl;
}
return ret;
}
int DaosObject::mark_as_latest(const DoutPrefixProvider* dpp,
ceph::real_time set_mtime) {
// TODO handle deletion
// TODO understand race conditions
ldpp_dout(dpp, 20) << "DEBUG: mark_as_latest" << dendl;
// Get latest version so far
std::unique_ptr<DaosObject> latest_object = std::make_unique<DaosObject>(
store, rgw_obj_key(get_name(), DS3_LATEST_INSTANCE), get_bucket());
ldpp_dout(dpp, 20) << __func__ << ": key=" << get_key().get_oid()
<< " latest_object_key= "
<< latest_object->get_key().get_oid() << dendl;
int ret = latest_object->lookup(dpp);
if (ret == 0) {
// Get metadata only if file exists
rgw_bucket_dir_entry latest_ent;
Attrs latest_attrs;
ret = latest_object->get_dir_entry_attrs(dpp, &latest_ent, &latest_attrs);
if (ret != 0) {
return ret;
}
// Update flags
latest_ent.flags = rgw_bucket_dir_entry::FLAG_VER;
latest_ent.meta.mtime = set_mtime;
ret = latest_object->set_dir_entry_attrs(dpp, &latest_ent, &latest_attrs);
if (ret != 0) {
return ret;
}
}
// Get or create the link [latest], make it link to the current latest
// version.
ret =
ds3_obj_mark_latest(get_key().get_oid().c_str(), get_daos_bucket()->ds3b);
ldpp_dout(dpp, 20) << "DEBUG: ds3_obj_mark_latest ret=" << ret << dendl;
return ret;
}
DaosAtomicWriter::DaosAtomicWriter(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, DaosStore* _store,
const rgw_user& _owner, const rgw_placement_rule* _ptail_placement_rule,
uint64_t _olh_epoch, const std::string& _unique_tag)
: StoreWriter(dpp, y),
store(_store),
owner(_owner),
ptail_placement_rule(_ptail_placement_rule),
olh_epoch(_olh_epoch),
unique_tag(_unique_tag),
obj(_store, obj->get_key(), obj->get_bucket()) {}
int DaosAtomicWriter::prepare(optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: prepare" << dendl;
int ret = obj.create(dpp);
return ret;
}
// TODO: Handle concurrent writes, a unique object id is a possible solution, or
// use DAOS transactions
// XXX: Do we need to accumulate writes as motr does?
int DaosAtomicWriter::process(bufferlist&& data, uint64_t offset) {
ldpp_dout(dpp, 20) << "DEBUG: process" << dendl;
if (data.length() == 0) {
return 0;
}
int ret = 0;
if (!obj.is_open()) {
ret = obj.lookup(dpp);
if (ret != 0) {
return ret;
}
}
// XXX: Combine multiple streams into one as motr does
uint64_t data_size = data.length();
ret = obj.write(dpp, std::move(data), offset);
if (ret == 0) {
total_data_size += data_size;
}
return ret;
}
int DaosAtomicWriter::complete(
size_t accounted_size, const std::string& etag, ceph::real_time* mtime,
ceph::real_time set_mtime, std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at, const char* if_match, const char* if_nomatch,
const std::string* user_data, rgw_zone_set* zones_trace, bool* canceled,
optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: complete" << dendl;
bufferlist bl;
rgw_bucket_dir_entry ent;
int ret;
// Set rgw_bucet_dir_entry. Some of the members of this structure may not
// apply to daos.
//
// Checkout AtomicObjectProcessor::complete() in rgw_putobj_processor.cc
// and RGWRados::Object::Write::write_meta() in rgw_rados.cc for what and
// how to set the dir entry. Only set the basic ones for POC, no ACLs and
// other attrs.
obj.get_key().get_index_key(&ent.key);
ent.meta.size = total_data_size;
ent.meta.accounted_size = accounted_size;
ent.meta.mtime =
real_clock::is_zero(set_mtime) ? ceph::real_clock::now() : set_mtime;
ent.meta.etag = etag;
ent.meta.owner = owner.to_str();
ent.meta.owner_display_name =
obj.get_bucket()->get_owner()->get_display_name();
bool is_versioned = obj.get_bucket()->versioned();
if (is_versioned)
ent.flags =
rgw_bucket_dir_entry::FLAG_VER | rgw_bucket_dir_entry::FLAG_CURRENT;
ldpp_dout(dpp, 20) << __func__ << ": key=" << obj.get_key().get_oid()
<< " etag: " << etag << dendl;
if (user_data) ent.meta.user_data = *user_data;
RGWBucketInfo& info = obj.get_bucket()->get_info();
if (info.obj_lock_enabled() && info.obj_lock.has_rule()) {
auto iter = attrs.find(RGW_ATTR_OBJECT_RETENTION);
if (iter == attrs.end()) {
real_time lock_until_date =
info.obj_lock.get_lock_until_date(ent.meta.mtime);
string mode = info.obj_lock.get_mode();
RGWObjectRetention obj_retention(mode, lock_until_date);
bufferlist retention_bl;
obj_retention.encode(retention_bl);
attrs[RGW_ATTR_OBJECT_RETENTION] = retention_bl;
}
}
ret = obj.set_dir_entry_attrs(dpp, &ent, &attrs);
if (is_versioned) {
ret = obj.mark_as_latest(dpp, set_mtime);
if (ret != 0) {
return ret;
}
}
return ret;
}
int DaosMultipartUpload::abort(const DoutPrefixProvider* dpp,
CephContext* cct) {
// Remove upload from bucket multipart index
ldpp_dout(dpp, 20) << "DEBUG: abort" << dendl;
return ds3_upload_remove(bucket->get_name().c_str(), get_upload_id().c_str(),
store->ds3);
}
std::unique_ptr<rgw::sal::Object> DaosMultipartUpload::get_meta_obj() {
return bucket->get_object(
rgw_obj_key(get_upload_id(), string(), RGW_OBJ_NS_MULTIPART));
}
int DaosMultipartUpload::init(const DoutPrefixProvider* dpp, optional_yield y,
ACLOwner& _owner,
rgw_placement_rule& dest_placement,
rgw::sal::Attrs& attrs) {
ldpp_dout(dpp, 20) << "DEBUG: init" << dendl;
int ret;
std::string oid = mp_obj.get_key();
// Create an initial entry in the bucket. The entry will be
// updated when multipart upload is completed, for example,
// size, etag etc.
bufferlist bl;
rgw_bucket_dir_entry ent;
ent.key.name = oid;
ent.meta.owner = owner.get_id().to_str();
ent.meta.category = RGWObjCategory::MultiMeta;
ent.meta.mtime = ceph::real_clock::now();
multipart_upload_info upload_info;
upload_info.dest_placement = dest_placement;
ent.encode(bl);
encode(attrs, bl);
encode(upload_info, bl);
struct ds3_multipart_upload_info ui;
std::strcpy(ui.upload_id, MULTIPART_UPLOAD_ID_PREFIX);
std::strncpy(ui.key, oid.c_str(), sizeof(ui.key));
ui.encoded = bl.c_str();
ui.encoded_length = bl.length();
int prefix_length = strlen(ui.upload_id);
do {
gen_rand_alphanumeric(store->ctx(), ui.upload_id + prefix_length,
sizeof(ui.upload_id) - 1 - prefix_length);
mp_obj.init(oid, ui.upload_id);
ret = ds3_upload_init(&ui, bucket->get_name().c_str(), store->ds3);
} while (ret == -EEXIST);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to create multipart upload dir ("
<< bucket->get_name() << "/" << get_upload_id()
<< "): ret=" << ret << dendl;
}
return ret;
}
int DaosMultipartUpload::list_parts(const DoutPrefixProvider* dpp,
CephContext* cct, int num_parts, int marker,
int* next_marker, bool* truncated,
bool assume_unsorted) {
ldpp_dout(dpp, 20) << "DEBUG: list_parts" << dendl;
// Init needed structures
vector<struct ds3_multipart_part_info> multipart_part_infos(num_parts);
uint32_t npart = multipart_part_infos.size();
vector<vector<uint8_t>> values(npart, vector<uint8_t>(DS3_MAX_ENCODED_LEN));
for (uint32_t i = 0; i < npart; i++) {
multipart_part_infos[i].encoded = values[i].data();
multipart_part_infos[i].encoded_length = values[i].size();
}
uint32_t daos_marker = marker;
int ret = ds3_upload_list_parts(
bucket->get_name().c_str(), get_upload_id().c_str(), &npart,
multipart_part_infos.data(), &daos_marker, truncated, store->ds3);
if (ret != 0) {
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
return ret;
}
multipart_part_infos.resize(npart);
values.resize(npart);
parts.clear();
for (auto const& pi : multipart_part_infos) {
bufferlist bl;
bl.append(reinterpret_cast<char*>(pi.encoded), pi.encoded_length);
std::unique_ptr<DaosMultipartPart> part =
std::make_unique<DaosMultipartPart>();
auto iter = bl.cbegin();
decode(part->info, iter);
parts[pi.part_num] = std::move(part);
}
if (next_marker) {
*next_marker = daos_marker;
}
return ret;
}
// Heavily copied from rgw_sal_rados.cc
int DaosMultipartUpload::complete(
const DoutPrefixProvider* dpp, optional_yield y, CephContext* cct,
map<int, string>& part_etags, list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed, RGWCompressionInfo& cs_info,
off_t& off, std::string& tag, ACLOwner& owner, uint64_t olh_epoch,
rgw::sal::Object* target_obj) {
ldpp_dout(dpp, 20) << "DEBUG: complete" << dendl;
char final_etag[CEPH_CRYPTO_MD5_DIGESTSIZE];
char final_etag_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 16];
std::string etag;
bufferlist etag_bl;
MD5 hash;
// Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
bool truncated;
int ret;
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): enter" << dendl;
int total_parts = 0;
int handled_parts = 0;
int max_parts = 1000;
int marker = 0;
uint64_t min_part_size = cct->_conf->rgw_multipart_min_part_size;
auto etags_iter = part_etags.begin();
rgw::sal::Attrs attrs = target_obj->get_attrs();
do {
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): list_parts()"
<< dendl;
ret = list_parts(dpp, cct, max_parts, marker, &marker, &truncated);
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
if (ret != 0) return ret;
total_parts += parts.size();
if (!truncated && total_parts != (int)part_etags.size()) {
ldpp_dout(dpp, 0) << "NOTICE: total parts mismatch: have: " << total_parts
<< " expected: " << part_etags.size() << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): parts.size()="
<< parts.size() << dendl;
for (auto obj_iter = parts.begin();
etags_iter != part_etags.end() && obj_iter != parts.end();
++etags_iter, ++obj_iter, ++handled_parts) {
DaosMultipartPart* part =
dynamic_cast<rgw::sal::DaosMultipartPart*>(obj_iter->second.get());
uint64_t part_size = part->get_size();
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): part_size="
<< part_size << dendl;
if (handled_parts < (int)part_etags.size() - 1 &&
part_size < min_part_size) {
ret = -ERR_TOO_SMALL;
return ret;
}
char petag[CEPH_CRYPTO_MD5_DIGESTSIZE];
if (etags_iter->first != (int)obj_iter->first) {
ldpp_dout(dpp, 0) << "NOTICE: parts num mismatch: next requested: "
<< etags_iter->first
<< " next uploaded: " << obj_iter->first << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
string part_etag = rgw_string_unquote(etags_iter->second);
if (part_etag.compare(part->get_etag()) != 0) {
ldpp_dout(dpp, 0) << "NOTICE: etag mismatch: part: "
<< etags_iter->first
<< " etag: " << etags_iter->second << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
hex_to_buf(part->get_etag().c_str(), petag, CEPH_CRYPTO_MD5_DIGESTSIZE);
hash.Update((const unsigned char*)petag, sizeof(petag));
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): calc etag "
<< dendl;
RGWUploadPartInfo& obj_part = part->info;
string oid = mp_obj.get_part(obj_part.num);
rgw_obj src_obj;
src_obj.init_ns(bucket->get_key(), oid, RGW_OBJ_NS_MULTIPART);
bool part_compressed = (obj_part.cs_info.compression_type != "none");
if ((handled_parts > 0) &&
((part_compressed != compressed) ||
(cs_info.compression_type != obj_part.cs_info.compression_type))) {
ldpp_dout(dpp, 0)
<< "ERROR: compression type was changed during multipart upload ("
<< cs_info.compression_type << ">>"
<< obj_part.cs_info.compression_type << ")" << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): part compression"
<< dendl;
if (part_compressed) {
int64_t new_ofs; // offset in compression data for new part
if (cs_info.blocks.size() > 0)
new_ofs = cs_info.blocks.back().new_ofs + cs_info.blocks.back().len;
else
new_ofs = 0;
for (const auto& block : obj_part.cs_info.blocks) {
compression_block cb;
cb.old_ofs = block.old_ofs + cs_info.orig_size;
cb.new_ofs = new_ofs;
cb.len = block.len;
cs_info.blocks.push_back(cb);
new_ofs = cb.new_ofs + cb.len;
}
if (!compressed)
cs_info.compression_type = obj_part.cs_info.compression_type;
cs_info.orig_size += obj_part.cs_info.orig_size;
compressed = true;
}
// We may not need to do the following as remove_objs are those
// don't show when listing a bucket. As we store in-progress uploaded
// object's metadata in a separate index, they are not shown when
// listing a bucket.
rgw_obj_index_key remove_key;
src_obj.key.get_index_key(&remove_key);
remove_objs.push_back(remove_key);
off += obj_part.size;
accounted_size += obj_part.accounted_size;
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): off=" << off
<< ", accounted_size = " << accounted_size << dendl;
}
} while (truncated);
hash.Final((unsigned char*)final_etag);
buf_to_hex((unsigned char*)final_etag, sizeof(final_etag), final_etag_str);
snprintf(&final_etag_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2],
sizeof(final_etag_str) - CEPH_CRYPTO_MD5_DIGESTSIZE * 2, "-%lld",
(long long)part_etags.size());
etag = final_etag_str;
ldpp_dout(dpp, 10) << "calculated etag: " << etag << dendl;
etag_bl.append(etag);
attrs[RGW_ATTR_ETAG] = etag_bl;
if (compressed) {
// write compression attribute to full object
bufferlist tmp;
encode(cs_info, tmp);
attrs[RGW_ATTR_COMPRESSION] = tmp;
}
// Different from rgw_sal_rados.cc starts here
// Read the object's multipart info
bufferlist bl;
uint64_t size = DS3_MAX_ENCODED_LEN;
struct ds3_multipart_upload_info ui = {
.encoded = bl.append_hole(size).c_str(), .encoded_length = size};
ret = ds3_upload_get_info(&ui, bucket->get_name().c_str(),
get_upload_id().c_str(), store->ds3);
ldpp_dout(dpp, 20) << "DEBUG: ds3_upload_get_info entry="
<< bucket->get_name() << "/" << get_upload_id() << dendl;
if (ret != 0) {
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
return ret;
}
rgw_bucket_dir_entry ent;
auto iter = bl.cbegin();
ent.decode(iter);
// Update entry data and name
target_obj->get_key().get_index_key(&ent.key);
ent.meta.size = off;
ent.meta.accounted_size = accounted_size;
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): obj size="
<< ent.meta.size
<< " obj accounted size=" << ent.meta.accounted_size
<< dendl;
ent.meta.category = RGWObjCategory::Main;
ent.meta.mtime = ceph::real_clock::now();
bool is_versioned = target_obj->get_bucket()->versioned();
if (is_versioned)
ent.flags =
rgw_bucket_dir_entry::FLAG_VER | rgw_bucket_dir_entry::FLAG_CURRENT;
ent.meta.etag = etag;
// Open object
DaosObject* obj = static_cast<DaosObject*>(target_obj);
ret = obj->create(dpp);
if (ret != 0) {
return ret;
}
// Copy data from parts to object
uint64_t write_off = 0;
for (auto const& [part_num, part] : get_parts()) {
ds3_part_t* ds3p;
ret = ds3_part_open(get_bucket_name().c_str(), get_upload_id().c_str(),
part_num, false, &ds3p, store->ds3);
if (ret != 0) {
return ret;
}
// Reserve buffers and read
uint64_t size = part->get_size();
bufferlist bl;
ret = ds3_part_read(bl.append_hole(size).c_str(), 0, &size, ds3p,
store->ds3, nullptr);
if (ret != 0) {
ds3_part_close(ds3p);
return ret;
}
ldpp_dout(dpp, 20) << "DaosMultipartUpload::complete(): part " << part_num
<< " size is " << size << dendl;
// write to obj
obj->write(dpp, std::move(bl), write_off);
ds3_part_close(ds3p);
write_off += part->get_size();
}
// Set attributes
ret = obj->set_dir_entry_attrs(dpp, &ent, &attrs);
if (is_versioned) {
ret = obj->mark_as_latest(dpp, ent.meta.mtime);
if (ret != 0) {
return ret;
}
}
// Remove upload from bucket multipart index
ret = ds3_upload_remove(get_bucket_name().c_str(), get_upload_id().c_str(),
store->ds3);
return ret;
}
int DaosMultipartUpload::get_info(const DoutPrefixProvider* dpp,
optional_yield y, rgw_placement_rule** rule,
rgw::sal::Attrs* attrs) {
ldpp_dout(dpp, 20) << "DaosMultipartUpload::get_info(): enter" << dendl;
if (!rule && !attrs) {
return 0;
}
if (rule) {
if (!placement.empty()) {
*rule = &placement;
if (!attrs) {
// Don't need attrs, done
return 0;
}
} else {
*rule = nullptr;
}
}
// Read the multipart upload dirent from index
bufferlist bl;
uint64_t size = DS3_MAX_ENCODED_LEN;
struct ds3_multipart_upload_info ui = {
.encoded = bl.append_hole(size).c_str(), .encoded_length = size};
int ret = ds3_upload_get_info(&ui, bucket->get_name().c_str(),
get_upload_id().c_str(), store->ds3);
if (ret != 0) {
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
return ret;
}
multipart_upload_info upload_info;
rgw_bucket_dir_entry ent;
Attrs decoded_attrs;
auto iter = bl.cbegin();
ent.decode(iter);
decode(decoded_attrs, iter);
ldpp_dout(dpp, 20) << "DEBUG: decoded_attrs=" << attrs << dendl;
if (attrs) {
*attrs = decoded_attrs;
if (!rule || *rule != nullptr) {
// placement was cached; don't actually read
return 0;
}
}
// Now decode the placement rule
decode(upload_info, iter);
placement = upload_info.dest_placement;
*rule = &placement;
return 0;
}
std::unique_ptr<Writer> DaosMultipartUpload::get_writer(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule, uint64_t part_num,
const std::string& part_num_str) {
ldpp_dout(dpp, 20) << "DaosMultipartUpload::get_writer(): enter part="
<< part_num << " head_obj=" << _head_obj << dendl;
return std::make_unique<DaosMultipartWriter>(
dpp, y, this, obj, store, owner, ptail_placement_rule,
part_num, part_num_str);
}
DaosMultipartWriter::~DaosMultipartWriter() {
if (is_open()) ds3_part_close(ds3p);
}
int DaosMultipartWriter::prepare(optional_yield y) {
ldpp_dout(dpp, 20) << "DaosMultipartWriter::prepare(): enter part="
<< part_num_str << dendl;
int ret = ds3_part_open(get_bucket_name().c_str(), upload_id.c_str(),
part_num, true, &ds3p, store->ds3);
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
return ret;
}
const std::string& DaosMultipartWriter::get_bucket_name() {
return static_cast<DaosMultipartUpload*>(upload)->get_bucket_name();
}
int DaosMultipartWriter::process(bufferlist&& data, uint64_t offset) {
ldpp_dout(dpp, 20) << "DaosMultipartWriter::process(): enter part="
<< part_num_str << " offset=" << offset << dendl;
if (data.length() == 0) {
return 0;
}
uint64_t size = data.length();
int ret =
ds3_part_write(data.c_str(), offset, &size, ds3p, store->ds3, nullptr);
if (ret == 0) {
// XXX: Combine multiple streams into one as motr does
actual_part_size += size;
} else {
ldpp_dout(dpp, 0) << "ERROR: failed to write into part ("
<< get_bucket_name() << ", " << upload_id << ", "
<< part_num << "): ret=" << ret << dendl;
}
return ret;
}
int DaosMultipartWriter::complete(
size_t accounted_size, const std::string& etag, ceph::real_time* mtime,
ceph::real_time set_mtime, std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at, const char* if_match, const char* if_nomatch,
const std::string* user_data, rgw_zone_set* zones_trace, bool* canceled,
optional_yield y) {
ldpp_dout(dpp, 20) << "DaosMultipartWriter::complete(): enter part="
<< part_num_str << dendl;
// Add an entry into part index
bufferlist bl;
RGWUploadPartInfo info;
info.num = part_num;
info.etag = etag;
info.size = actual_part_size;
info.accounted_size = accounted_size;
info.modified = real_clock::now();
bool compressed;
int ret = rgw_compression_info_from_attrset(attrs, compressed, info.cs_info);
ldpp_dout(dpp, 20) << "DaosMultipartWriter::complete(): compression ret="
<< ret << dendl;
if (ret != 0) {
ldpp_dout(dpp, 1) << "cannot get compression info" << dendl;
return ret;
}
encode(info, bl);
encode(attrs, bl);
ldpp_dout(dpp, 20) << "DaosMultipartWriter::complete(): entry size"
<< bl.length() << dendl;
struct ds3_multipart_part_info part_info = {.part_num = part_num,
.encoded = bl.c_str(),
.encoded_length = bl.length()};
ret = ds3_part_set_info(&part_info, ds3p, store->ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to set part info (" << get_bucket_name()
<< ", " << upload_id << ", " << part_num
<< "): ret=" << ret << dendl;
if (ret == ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
}
return ret;
}
std::unique_ptr<RGWRole> DaosStore::get_role(
std::string name, std::string tenant, std::string path,
std::string trust_policy, std::string max_session_duration_str,
std::multimap<std::string, std::string> tags) {
RGWRole* p = nullptr;
return std::unique_ptr<RGWRole>(p);
}
std::unique_ptr<RGWRole> DaosStore::get_role(const RGWRoleInfo& info) {
RGWRole* p = nullptr;
return std::unique_ptr<RGWRole>(p);
}
std::unique_ptr<RGWRole> DaosStore::get_role(std::string id) {
RGWRole* p = nullptr;
return std::unique_ptr<RGWRole>(p);
}
int DaosStore::get_roles(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
vector<std::unique_ptr<RGWRole>>& roles) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
std::unique_ptr<RGWOIDCProvider> DaosStore::get_oidc_provider() {
RGWOIDCProvider* p = nullptr;
return std::unique_ptr<RGWOIDCProvider>(p);
}
int DaosStore::get_oidc_providers(
const DoutPrefixProvider* dpp, const std::string& tenant,
vector<std::unique_ptr<RGWOIDCProvider>>& providers) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
std::unique_ptr<MultipartUpload> DaosBucket::get_multipart_upload(
const std::string& oid, std::optional<std::string> upload_id,
ACLOwner owner, ceph::real_time mtime) {
return std::make_unique<DaosMultipartUpload>(store, this, oid, upload_id,
owner, mtime);
}
std::unique_ptr<Writer> DaosStore::get_append_writer(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule,
const std::string& unique_tag, uint64_t position,
uint64_t* cur_accounted_size) {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return nullptr;
}
std::unique_ptr<Writer> DaosStore::get_atomic_writer(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule, uint64_t olh_epoch,
const std::string& unique_tag) {
ldpp_dout(dpp, 20) << "get_atomic_writer" << dendl;
return std::make_unique<DaosAtomicWriter>(dpp, y, obj, this,
owner, ptail_placement_rule,
olh_epoch, unique_tag);
}
const std::string& DaosStore::get_compression_type(
const rgw_placement_rule& rule) {
return zone.zone_params->get_compression_type(rule);
}
bool DaosStore::valid_placement(const rgw_placement_rule& rule) {
return zone.zone_params->valid_placement(rule);
}
std::unique_ptr<User> DaosStore::get_user(const rgw_user& u) {
ldout(cctx, 20) << "DEBUG: bucket's user: " << u.to_str() << dendl;
return std::make_unique<DaosUser>(this, u);
}
int DaosStore::get_user_by_access_key(const DoutPrefixProvider* dpp,
const std::string& key, optional_yield y,
std::unique_ptr<User>* user) {
// Initialize ds3_user_info
bufferlist bl;
uint64_t size = DS3_MAX_ENCODED_LEN;
struct ds3_user_info user_info = {.encoded = bl.append_hole(size).c_str(),
.encoded_length = size};
int ret = ds3_user_get_by_key(key.c_str(), &user_info, ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "Error: ds3_user_get_by_key failed, key=" << key
<< " ret=" << ret << dendl;
return ret;
}
// Decode
DaosUserInfo duinfo;
bufferlist& blr = bl;
auto iter = blr.cbegin();
duinfo.decode(iter);
User* u = new DaosUser(this, duinfo.info);
if (!u) {
return -ENOMEM;
}
user->reset(u);
return 0;
}
int DaosStore::get_user_by_email(const DoutPrefixProvider* dpp,
const std::string& email, optional_yield y,
std::unique_ptr<User>* user) {
// Initialize ds3_user_info
bufferlist bl;
uint64_t size = DS3_MAX_ENCODED_LEN;
struct ds3_user_info user_info = {.encoded = bl.append_hole(size).c_str(),
.encoded_length = size};
int ret = ds3_user_get_by_email(email.c_str(), &user_info, ds3, nullptr);
if (ret != 0) {
ldpp_dout(dpp, 0) << "Error: ds3_user_get_by_email failed, email=" << email
<< " ret=" << ret << dendl;
return ret;
}
// Decode
DaosUserInfo duinfo;
bufferlist& blr = bl;
auto iter = blr.cbegin();
duinfo.decode(iter);
User* u = new DaosUser(this, duinfo.info);
if (!u) {
return -ENOMEM;
}
user->reset(u);
return 0;
}
int DaosStore::get_user_by_swift(const DoutPrefixProvider* dpp,
const std::string& user_str, optional_yield y,
std::unique_ptr<User>* user) {
/* Swift keys and subusers are not supported for now */
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
std::unique_ptr<Object> DaosStore::get_object(const rgw_obj_key& k) {
return std::make_unique<DaosObject>(this, k);
}
inline std::ostream& operator<<(std::ostream& out, const rgw_user* u) {
std::string s;
if (u != nullptr)
u->to_str(s);
else
s = "(nullptr)";
return out << s;
}
int DaosStore::get_bucket(const DoutPrefixProvider* dpp, User* u,
const rgw_bucket& b, std::unique_ptr<Bucket>* bucket,
optional_yield y) {
ldpp_dout(dpp, 20) << "DEBUG: get_bucket1: User: " << u << dendl;
int ret;
Bucket* bp;
bp = new DaosBucket(this, b, u);
ret = bp->load_bucket(dpp, y);
if (ret != 0) {
delete bp;
return ret;
}
bucket->reset(bp);
return 0;
}
int DaosStore::get_bucket(User* u, const RGWBucketInfo& i,
std::unique_ptr<Bucket>* bucket) {
DaosBucket* bp;
bp = new DaosBucket(this, i, u);
/* Don't need to fetch the bucket info, use the provided one */
bucket->reset(bp);
return 0;
}
int DaosStore::get_bucket(const DoutPrefixProvider* dpp, User* u,
const std::string& tenant, const std::string& name,
std::unique_ptr<Bucket>* bucket, optional_yield y) {
ldpp_dout(dpp, 20) << "get_bucket" << dendl;
rgw_bucket b;
b.tenant = tenant;
b.name = name;
return get_bucket(dpp, u, b, bucket, y);
}
bool DaosStore::is_meta_master() { return true; }
int DaosStore::forward_request_to_master(const DoutPrefixProvider* dpp,
User* user, obj_version* objv,
bufferlist& in_data, JSONParser* jp,
req_info& info, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosStore::forward_iam_request_to_master(const DoutPrefixProvider* dpp,
const RGWAccessKey& key,
obj_version* objv,
bufferlist& in_data,
RGWXMLDecoder::XMLParser* parser,
req_info& info, optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
std::string DaosStore::zone_unique_id(uint64_t unique_num) { return ""; }
std::string DaosStore::zone_unique_trans_id(const uint64_t unique_num) {
return "";
}
int DaosStore::cluster_stat(RGWClusterStat& stats) {
return DAOS_NOT_IMPLEMENTED_LOG(nullptr);
}
std::unique_ptr<Lifecycle> DaosStore::get_lifecycle(void) {
DAOS_NOT_IMPLEMENTED_LOG(nullptr);
return 0;
}
std::unique_ptr<Notification> DaosStore::get_notification(
rgw::sal::Object* obj, rgw::sal::Object* src_obj, struct req_state* s,
rgw::notify::EventType event_type, const std::string* object_name) {
return std::make_unique<DaosNotification>(obj, src_obj, event_type);
}
std::unique_ptr<Notification> DaosStore::get_notification(
const DoutPrefixProvider* dpp, Object* obj, Object* src_obj,
rgw::notify::EventType event_type, rgw::sal::Bucket* _bucket,
std::string& _user_id, std::string& _user_tenant, std::string& _req_id,
optional_yield y) {
ldpp_dout(dpp, 20) << "get_notification" << dendl;
return std::make_unique<DaosNotification>(obj, src_obj, event_type);
}
int DaosStore::log_usage(const DoutPrefixProvider* dpp,
map<rgw_user_bucket, RGWUsageBatch>& usage_info) {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return 0;
}
int DaosStore::log_op(const DoutPrefixProvider* dpp, string& oid,
bufferlist& bl) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosStore::register_to_service_map(const DoutPrefixProvider* dpp,
const string& daemon_type,
const map<string, string>& meta) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
void DaosStore::get_quota(RGWQuota& quota) {
// XXX: Not handled for the first pass
return;
}
void DaosStore::get_ratelimit(RGWRateLimitInfo& bucket_ratelimit,
RGWRateLimitInfo& user_ratelimit,
RGWRateLimitInfo& anon_ratelimit) {
return;
}
int DaosStore::set_buckets_enabled(const DoutPrefixProvider* dpp,
std::vector<rgw_bucket>& buckets,
bool enabled) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosStore::get_sync_policy_handler(const DoutPrefixProvider* dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef* phandler,
optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
RGWDataSyncStatusManager* DaosStore::get_data_sync_manager(
const rgw_zone_id& source_zone) {
DAOS_NOT_IMPLEMENTED_LOG(nullptr);
return 0;
}
int DaosStore::read_all_usage(
const DoutPrefixProvider* dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool* is_truncated, RGWUsageIter& usage_iter,
map<rgw_user_bucket, rgw_usage_log_entry>& usage) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosStore::trim_all_usage(const DoutPrefixProvider* dpp,
uint64_t start_epoch, uint64_t end_epoch) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosStore::get_config_key_val(string name, bufferlist* bl) {
return DAOS_NOT_IMPLEMENTED_LOG(nullptr);
}
int DaosStore::meta_list_keys_init(const DoutPrefixProvider* dpp,
const string& section, const string& marker,
void** phandle) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
int DaosStore::meta_list_keys_next(const DoutPrefixProvider* dpp, void* handle,
int max, list<string>& keys,
bool* truncated) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
void DaosStore::meta_list_keys_complete(void* handle) { return; }
std::string DaosStore::meta_get_marker(void* handle) { return ""; }
int DaosStore::meta_remove(const DoutPrefixProvider* dpp, string& metadata_key,
optional_yield y) {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
std::string DaosStore::get_cluster_id(const DoutPrefixProvider* dpp,
optional_yield y) {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return "";
}
} // namespace rgw::sal
extern "C" {
void* newDaosStore(CephContext* cct) {
return new rgw::sal::DaosStore(cct);
}
}
| 80,679 | 31.917177 | 88 |
cc
|
null |
ceph-main/src/rgw/rgw_sal_daos.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=2 sw=2 expandtab ft=cpp
/*
* Ceph - scalable distributed file system
*
* SAL implementation for the CORTX Daos backend
*
* Copyright (C) 2022 Seagate Technology LLC and/or its Affiliates
*
* 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 <daos.h>
#include <daos_s3.h>
#include <uuid/uuid.h>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "rgw_multi.h"
#include "rgw_notify.h"
#include "rgw_oidc_provider.h"
#include "rgw_putobj_processor.h"
#include "rgw_rados.h"
#include "rgw_role.h"
#include "rgw_sal_store.h"
inline bool IsDebuggerAttached() {
#ifdef DEBUG
char buf[4096];
const int status_fd = ::open("/proc/self/status", O_RDONLY);
if (status_fd == -1) return false;
const ssize_t num_read = ::read(status_fd, buf, sizeof(buf) - 1);
::close(status_fd);
if (num_read <= 0) return false;
buf[num_read] = '\0';
constexpr char tracerPidString[] = "TracerPid:";
const auto tracer_pid_ptr = ::strstr(buf, tracerPidString);
if (!tracer_pid_ptr) return false;
for (const char* characterPtr = tracer_pid_ptr + sizeof(tracerPidString) - 1;
characterPtr <= buf + num_read; ++characterPtr) {
if (::isspace(*characterPtr))
continue;
else
return ::isdigit(*characterPtr) != 0 && *characterPtr != '0';
}
#endif // DEBUG
return false;
}
inline void DebugBreak() {
#ifdef DEBUG
// only break into the debugger if the debugger is attached
if (IsDebuggerAttached())
raise(SIGINT); // breaks into GDB and stops, can be continued
#endif // DEBUG
}
inline int NotImplementedLog(const DoutPrefixProvider* ldpp,
const char* filename, int linenumber,
const char* functionname) {
if (ldpp)
ldpp_dout(ldpp, 20) << filename << "(" << linenumber << ") " << functionname
<< ": Not implemented" << dendl;
return 0;
}
inline int NotImplementedGdbBreak(const DoutPrefixProvider* ldpp,
const char* filename, int linenumber,
const char* functionname) {
NotImplementedLog(ldpp, filename, linenumber, functionname);
DebugBreak();
return 0;
}
#define DAOS_NOT_IMPLEMENTED_GDB_BREAK(ldpp) \
NotImplementedGdbBreak(ldpp, __FILE__, __LINE__, __FUNCTION__)
#define DAOS_NOT_IMPLEMENTED_LOG(ldpp) \
NotImplementedLog(ldpp, __FILE__, __LINE__, __FUNCTION__)
namespace rgw::sal {
class DaosStore;
class DaosObject;
#ifdef DEBUG
// Prepends each log entry with the "filename(source_line) function_name". Makes
// it simple to
// associate log entries with the source that generated the log entry
#undef ldpp_dout
#define ldpp_dout(dpp, v) \
if (decltype(auto) pdpp = (dpp); \
pdpp) /* workaround -Wnonnull-compare for 'this' */ \
dout_impl(pdpp->get_cct(), ceph::dout::need_dynamic(pdpp->get_subsys()), v) \
pdpp->gen_prefix(*_dout) \
<< __FILE__ << "(" << __LINE__ << ") " << __FUNCTION__ << " - "
#endif // DEBUG
struct DaosUserInfo {
RGWUserInfo info;
obj_version user_version;
rgw::sal::Attrs attrs;
void encode(bufferlist& bl) const {
ENCODE_START(3, 3, bl);
encode(info, bl);
encode(user_version, bl);
encode(attrs, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(3, bl);
decode(info, bl);
decode(user_version, bl);
decode(attrs, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(DaosUserInfo);
class DaosNotification : public StoreNotification {
public:
DaosNotification(Object* _obj, Object* _src_obj, rgw::notify::EventType _type)
: StoreNotification(_obj, _src_obj, _type) {}
~DaosNotification() = default;
virtual int publish_reserve(const DoutPrefixProvider* dpp,
RGWObjTags* obj_tags = nullptr) override {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
virtual int publish_commit(const DoutPrefixProvider* dpp, uint64_t size,
const ceph::real_time& mtime,
const std::string& etag,
const std::string& version) override {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
};
class DaosUser : public StoreUser {
private:
DaosStore* store;
std::vector<const char*> access_ids;
public:
DaosUser(DaosStore* _st, const rgw_user& _u) : StoreUser(_u), store(_st) {}
DaosUser(DaosStore* _st, const RGWUserInfo& _i) : StoreUser(_i), store(_st) {}
DaosUser(DaosStore* _st) : store(_st) {}
DaosUser(DaosUser& _o) = default;
DaosUser() {}
virtual std::unique_ptr<User> clone() override {
return std::make_unique<DaosUser>(*this);
}
int list_buckets(const DoutPrefixProvider* dpp, const std::string& marker,
const std::string& end_marker, uint64_t max, bool need_stats,
BucketList& buckets, optional_yield y) override;
virtual int create_bucket(
const DoutPrefixProvider* dpp, const rgw_bucket& b,
const std::string& zonegroup_id, rgw_placement_rule& placement_rule,
std::string& swift_ver_location, const RGWQuotaInfo* pquota_info,
const RGWAccessControlPolicy& policy, Attrs& attrs, RGWBucketInfo& info,
obj_version& ep_objv, bool exclusive, bool obj_lock_enabled,
bool* existed, req_info& req_info, std::unique_ptr<Bucket>* bucket,
optional_yield y) override;
virtual int read_attrs(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp,
Attrs& new_attrs,
optional_yield y) override;
virtual int read_stats(const DoutPrefixProvider* dpp, optional_yield y,
RGWStorageStats* stats,
ceph::real_time* last_stats_sync = nullptr,
ceph::real_time* last_stats_update = nullptr) override;
virtual int read_stats_async(const DoutPrefixProvider* dpp,
RGWGetUserStats_CB* cb) override;
virtual int complete_flush_stats(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int read_usage(
const DoutPrefixProvider* dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_usage(const DoutPrefixProvider* dpp, uint64_t start_epoch,
uint64_t end_epoch) override;
virtual int load_user(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int store_user(const DoutPrefixProvider* dpp, optional_yield y,
bool exclusive,
RGWUserInfo* old_info = nullptr) override;
virtual int remove_user(const DoutPrefixProvider* dpp,
optional_yield y) override;
/** Read user info without loading it */
int read_user(const DoutPrefixProvider* dpp, std::string name,
DaosUserInfo* duinfo);
std::unique_ptr<struct ds3_user_info> get_encoded_info(bufferlist& bl,
obj_version& obj_ver);
friend class DaosBucket;
};
// RGWBucketInfo and other information that are shown when listing a bucket is
// represented in struct DaosBucketInfo. The structure is encoded and stored
// as the value of the global bucket instance index.
// TODO: compare pros and cons of separating the bucket_attrs (ACLs, tag etc.)
// into a different index.
struct DaosBucketInfo {
RGWBucketInfo info;
obj_version bucket_version;
ceph::real_time mtime;
rgw::sal::Attrs bucket_attrs;
void encode(bufferlist& bl) const {
ENCODE_START(4, 4, bl);
encode(info, bl);
encode(bucket_version, bl);
encode(mtime, bl);
encode(bucket_attrs, bl); // rgw_cache.h example for a map
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(4, bl);
decode(info, bl);
decode(bucket_version, bl);
decode(mtime, bl);
decode(bucket_attrs, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(DaosBucketInfo);
class DaosBucket : public StoreBucket {
private:
DaosStore* store;
RGWAccessControlPolicy acls;
public:
/** Container ds3b handle */
ds3_bucket_t* ds3b = nullptr;
DaosBucket(DaosStore* _st) : store(_st), acls() {}
DaosBucket(const DaosBucket& _daos_bucket)
: store(_daos_bucket.store), acls(), ds3b(nullptr) {
// TODO: deep copy all objects
}
DaosBucket(DaosStore* _st, User* _u) : StoreBucket(_u), store(_st), acls() {}
DaosBucket(DaosStore* _st, const rgw_bucket& _b)
: StoreBucket(_b), store(_st), acls() {}
DaosBucket(DaosStore* _st, const RGWBucketEnt& _e)
: StoreBucket(_e), store(_st), acls() {}
DaosBucket(DaosStore* _st, const RGWBucketInfo& _i)
: StoreBucket(_i), store(_st), acls() {}
DaosBucket(DaosStore* _st, const rgw_bucket& _b, User* _u)
: StoreBucket(_b, _u), store(_st), acls() {}
DaosBucket(DaosStore* _st, const RGWBucketEnt& _e, User* _u)
: StoreBucket(_e, _u), store(_st), acls() {}
DaosBucket(DaosStore* _st, const RGWBucketInfo& _i, User* _u)
: StoreBucket(_i, _u), store(_st), acls() {}
~DaosBucket();
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& k) override;
virtual int list(const DoutPrefixProvider* dpp, ListParams&, int,
ListResults&, optional_yield y) override;
virtual int remove_bucket(const DoutPrefixProvider* dpp, bool delete_children,
bool forward_to_master, req_info* req_info,
optional_yield y) override;
virtual int remove_bucket_bypass_gc(int concurrent_max,
bool keep_index_consistent,
optional_yield y,
const DoutPrefixProvider* dpp) override;
virtual RGWAccessControlPolicy& get_acl(void) override { return acls; }
virtual int set_acl(const DoutPrefixProvider* dpp,
RGWAccessControlPolicy& acl, optional_yield y) override;
virtual int load_bucket(const DoutPrefixProvider* dpp, optional_yield y,
bool get_stats = false) override;
virtual int read_stats(const DoutPrefixProvider* dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, std::string* bucket_ver,
std::string* master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string* max_marker = nullptr,
bool* syncstopped = nullptr) override;
virtual int read_stats_async(const DoutPrefixProvider* dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id,
RGWGetBucketStats_CB* ctx) override;
virtual int sync_user_stats(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int update_container_stats(const DoutPrefixProvider* dpp) override;
virtual int check_bucket_shards(const DoutPrefixProvider* dpp) override;
virtual int chown(const DoutPrefixProvider* dpp, User& new_user,
optional_yield y) override;
virtual int put_info(const DoutPrefixProvider* dpp, bool exclusive,
ceph::real_time mtime) override;
virtual bool is_owner(User* user) override;
virtual int check_empty(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int check_quota(const DoutPrefixProvider* dpp, RGWQuota& quota,
uint64_t obj_size, optional_yield y,
bool check_size_only = false) override;
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp, Attrs& attrs,
optional_yield y) override;
virtual int try_refresh_info(const DoutPrefixProvider* dpp,
ceph::real_time* pmtime) override;
virtual int read_usage(
const DoutPrefixProvider* dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_usage(const DoutPrefixProvider* dpp, uint64_t start_epoch,
uint64_t end_epoch) override;
virtual int remove_objs_from_index(
const DoutPrefixProvider* dpp,
std::list<rgw_obj_index_key>& objs_to_unlink) override;
virtual int check_index(
const DoutPrefixProvider* dpp,
std::map<RGWObjCategory, RGWStorageStats>& existing_stats,
std::map<RGWObjCategory, RGWStorageStats>& calculated_stats) override;
virtual int rebuild_index(const DoutPrefixProvider* dpp) override;
virtual int set_tag_timeout(const DoutPrefixProvider* dpp,
uint64_t timeout) override;
virtual int purge_instance(const DoutPrefixProvider* dpp) override;
virtual std::unique_ptr<Bucket> clone() override {
return std::make_unique<DaosBucket>(*this);
}
virtual std::unique_ptr<MultipartUpload> get_multipart_upload(
const std::string& oid,
std::optional<std::string> upload_id = std::nullopt, ACLOwner owner = {},
ceph::real_time mtime = real_clock::now()) override;
virtual int list_multiparts(
const DoutPrefixProvider* dpp, const std::string& prefix,
std::string& marker, const std::string& delim, const int& max_uploads,
std::vector<std::unique_ptr<MultipartUpload>>& uploads,
std::map<std::string, bool>* common_prefixes,
bool* is_truncated) override;
virtual int abort_multiparts(const DoutPrefixProvider* dpp,
CephContext* cct) override;
int open(const DoutPrefixProvider* dpp);
int close(const DoutPrefixProvider* dpp);
bool is_open() { return ds3b != nullptr; }
std::unique_ptr<struct ds3_bucket_info> get_encoded_info(
bufferlist& bl, ceph::real_time mtime);
friend class DaosStore;
};
class DaosPlacementTier : public StorePlacementTier {
DaosStore* store;
RGWZoneGroupPlacementTier tier;
public:
DaosPlacementTier(DaosStore* _store, const RGWZoneGroupPlacementTier& _tier)
: store(_store), tier(_tier) {}
virtual ~DaosPlacementTier() = default;
virtual const std::string& get_tier_type() { return tier.tier_type; }
virtual const std::string& get_storage_class() { return tier.storage_class; }
virtual bool retain_head_object() { return tier.retain_head_object; }
RGWZoneGroupPlacementTier& get_rt() { return tier; }
};
class DaosZoneGroup : public StoreZoneGroup {
DaosStore* store;
const RGWZoneGroup group;
std::string empty;
public:
DaosZoneGroup(DaosStore* _store) : store(_store), group() {}
DaosZoneGroup(DaosStore* _store, const RGWZoneGroup& _group)
: store(_store), group(_group) {}
virtual ~DaosZoneGroup() = default;
virtual const std::string& get_id() const override { return group.get_id(); };
virtual const std::string& get_name() const override {
return group.get_name();
};
virtual int equals(const std::string& other_zonegroup) const override {
return group.equals(other_zonegroup);
};
/** Get the endpoint from zonegroup, or from master zone if not set */
virtual const std::string& get_endpoint() const override;
virtual bool placement_target_exists(std::string& target) const override;
virtual bool is_master_zonegroup() const override {
return group.is_master_zonegroup();
};
virtual const std::string& get_api_name() const override {
return group.api_name;
};
virtual int get_placement_target_names(
std::set<std::string>& names) const override;
virtual const std::string& get_default_placement_name() const override {
return group.default_placement.name;
};
virtual int get_hostnames(std::list<std::string>& names) const override {
names = group.hostnames;
return 0;
};
virtual int get_s3website_hostnames(
std::list<std::string>& names) const override {
names = group.hostnames_s3website;
return 0;
};
virtual int get_zone_count() const override { return group.zones.size(); }
virtual int get_placement_tier(const rgw_placement_rule& rule,
std::unique_ptr<PlacementTier>* tier);
virtual std::unique_ptr<ZoneGroup> clone() override {
return std::make_unique<DaosZoneGroup>(store, group);
}
const RGWZoneGroup& get_group() { return group; }
};
class DaosZone : public StoreZone {
protected:
DaosStore* store;
RGWRealm* realm{nullptr};
DaosZoneGroup zonegroup;
RGWZone* zone_public_config{
nullptr}; /* external zone params, e.g., entrypoints, log flags, etc. */
RGWZoneParams* zone_params{
nullptr}; /* internal zone params, e.g., rados pools */
RGWPeriod* current_period{nullptr};
rgw_zone_id cur_zone_id;
public:
DaosZone(DaosStore* _store) : store(_store), zonegroup(_store) {
realm = new RGWRealm();
zone_public_config = new RGWZone();
zone_params = new RGWZoneParams();
current_period = new RGWPeriod();
cur_zone_id = rgw_zone_id(zone_params->get_id());
// XXX: only default and STANDARD supported for now
RGWZonePlacementInfo info;
RGWZoneStorageClasses sc;
sc.set_storage_class("STANDARD", nullptr, nullptr);
info.storage_classes = sc;
zone_params->placement_pools["default"] = info;
}
DaosZone(DaosStore* _store, DaosZoneGroup _zg)
: store(_store), zonegroup(_zg) {
realm = new RGWRealm();
zone_public_config = new RGWZone();
zone_params = new RGWZoneParams();
current_period = new RGWPeriod();
cur_zone_id = rgw_zone_id(zone_params->get_id());
// XXX: only default and STANDARD supported for now
RGWZonePlacementInfo info;
RGWZoneStorageClasses sc;
sc.set_storage_class("STANDARD", nullptr, nullptr);
info.storage_classes = sc;
zone_params->placement_pools["default"] = info;
}
~DaosZone() = default;
virtual std::unique_ptr<Zone> clone() override {
return std::make_unique<DaosZone>(store);
}
virtual ZoneGroup& get_zonegroup() override;
virtual int get_zonegroup(const std::string& id,
std::unique_ptr<ZoneGroup>* zonegroup) override;
virtual const rgw_zone_id& get_id() override;
virtual const std::string& get_name() const override;
virtual bool is_writeable() override;
virtual bool get_redirect_endpoint(std::string* endpoint) override;
virtual bool has_zonegroup_api(const std::string& api) const override;
virtual const std::string& get_current_period_id() override;
virtual const RGWAccessKey& get_system_key() {
return zone_params->system_key;
}
virtual const std::string& get_realm_name() { return realm->get_name(); }
virtual const std::string& get_realm_id() { return realm->get_id(); }
virtual const std::string_view get_tier_type() { return "rgw"; }
friend class DaosStore;
};
class DaosLuaManager : public StoreLuaManager {
DaosStore* store;
public:
DaosLuaManager(DaosStore* _s) : store(_s) {}
virtual ~DaosLuaManager() = default;
virtual int get_script(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& key, std::string& script) override {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return -ENOENT;
};
virtual int put_script(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& key,
const std::string& script) override {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return -ENOENT;
};
virtual int del_script(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& key) override {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return -ENOENT;
};
virtual int add_package(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& package_name) override {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return -ENOENT;
};
virtual int remove_package(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& package_name) override {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return -ENOENT;
};
virtual int list_packages(const DoutPrefixProvider* dpp, optional_yield y,
rgw::lua::packages_t& packages) override {
DAOS_NOT_IMPLEMENTED_LOG(dpp);
return -ENOENT;
};
};
class DaosObject : public StoreObject {
private:
DaosStore* store;
RGWAccessControlPolicy acls;
public:
struct DaosReadOp : public StoreReadOp {
private:
DaosObject* source;
public:
DaosReadOp(DaosObject* _source);
virtual int prepare(optional_yield y,
const DoutPrefixProvider* dpp) override;
/*
* Both `read` and `iterate` read up through index `end`
* *inclusive*. The number of bytes that could be returned is
* `end - ofs + 1`.
*/
virtual int read(int64_t off, int64_t end, bufferlist& bl, optional_yield y,
const DoutPrefixProvider* dpp) override;
virtual int iterate(const DoutPrefixProvider* dpp, int64_t off, int64_t end,
RGWGetDataCB* cb, optional_yield y) override;
virtual int get_attr(const DoutPrefixProvider* dpp, const char* name,
bufferlist& dest, optional_yield y) override;
};
struct DaosDeleteOp : public StoreDeleteOp {
private:
DaosObject* source;
public:
DaosDeleteOp(DaosObject* _source);
virtual int delete_obj(const DoutPrefixProvider* dpp,
optional_yield y) override;
};
ds3_obj_t* ds3o = nullptr;
DaosObject() = default;
DaosObject(DaosStore* _st, const rgw_obj_key& _k)
: StoreObject(_k), store(_st), acls() {}
DaosObject(DaosStore* _st, const rgw_obj_key& _k, Bucket* _b)
: StoreObject(_k, _b), store(_st), acls() {}
DaosObject(DaosObject& _o) = default;
virtual ~DaosObject();
virtual int delete_object(const DoutPrefixProvider* dpp, optional_yield y,
bool prevent_versioning = false) override;
virtual int copy_object(
User* user, req_info* info, const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object, rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket, const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime, ceph::real_time* mtime,
const ceph::real_time* mod_ptr, const ceph::real_time* unmod_ptr,
bool high_precision_time, const char* if_match, const char* if_nomatch,
AttrsMod attrs_mod, bool copy_if_newer, Attrs& attrs,
RGWObjCategory category, uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at, std::string* version_id,
std::string* tag, std::string* etag, void (*progress_cb)(off_t, void*),
void* progress_data, const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual RGWAccessControlPolicy& get_acl(void) override { return acls; }
virtual int set_acl(const RGWAccessControlPolicy& acl) override {
acls = acl;
return 0;
}
virtual int get_obj_state(const DoutPrefixProvider* dpp, RGWObjState** state,
optional_yield y, bool follow_olh = true) override;
virtual int set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs,
Attrs* delattrs, optional_yield y) override;
virtual int get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp,
rgw_obj* target_obj = NULL) override;
virtual int modify_obj_attrs(const char* attr_name, bufferlist& attr_val,
optional_yield y,
const DoutPrefixProvider* dpp) override;
virtual int delete_obj_attrs(const DoutPrefixProvider* dpp,
const char* attr_name,
optional_yield y) override;
virtual bool is_expired() override;
virtual void gen_rand_obj_instance_name() override;
virtual std::unique_ptr<Object> clone() override {
return std::make_unique<DaosObject>(*this);
}
virtual std::unique_ptr<MPSerializer> get_serializer(
const DoutPrefixProvider* dpp, const std::string& lock_name) override;
virtual int transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime, uint64_t olh_epoch,
const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int transition_to_cloud(Bucket* bucket, rgw::sal::PlacementTier* tier,
rgw_bucket_dir_entry& o,
std::set<std::string>& cloud_targets,
CephContext* cct, bool update_object,
const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual bool placement_rules_match(rgw_placement_rule& r1,
rgw_placement_rule& r2) override;
virtual int dump_obj_layout(const DoutPrefixProvider* dpp, optional_yield y,
Formatter* f) override;
/* Swift versioning */
virtual int swift_versioning_restore(bool& restored,
const DoutPrefixProvider* dpp) override;
virtual int swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y) override;
/* OPs */
virtual std::unique_ptr<ReadOp> get_read_op() override;
virtual std::unique_ptr<DeleteOp> get_delete_op() override;
/* OMAP */
virtual int omap_get_vals_by_keys(const DoutPrefixProvider* dpp,
const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals) override;
virtual int omap_set_val_by_key(const DoutPrefixProvider* dpp,
const std::string& key, bufferlist& val,
bool must_exist, optional_yield y) override;
virtual int chown(User& new_user, const DoutPrefixProvider* dpp,
optional_yield y) override;
bool is_open() { return ds3o != nullptr; };
// Only lookup the object, do not create
int lookup(const DoutPrefixProvider* dpp);
// Create the object, truncate if exists
int create(const DoutPrefixProvider* dpp);
// Release the daos resources
int close(const DoutPrefixProvider* dpp);
// Write to object starting from offset
int write(const DoutPrefixProvider* dpp, bufferlist&& data, uint64_t offset);
// Read size bytes from object starting from offset
int read(const DoutPrefixProvider* dpp, bufferlist& data, uint64_t offset,
uint64_t& size);
// Get the object's dirent and attrs
int get_dir_entry_attrs(const DoutPrefixProvider* dpp,
rgw_bucket_dir_entry* ent, Attrs* getattrs = nullptr);
// Set the object's dirent and attrs
int set_dir_entry_attrs(const DoutPrefixProvider* dpp,
rgw_bucket_dir_entry* ent, Attrs* setattrs = nullptr);
// Marks this DAOS object as being the latest version and unmarks all other
// versions as latest
int mark_as_latest(const DoutPrefixProvider* dpp, ceph::real_time set_mtime);
// get_bucket casted as DaosBucket*
DaosBucket* get_daos_bucket() {
return static_cast<DaosBucket*>(get_bucket());
}
};
// A placeholder locking class for multipart upload.
class MPDaosSerializer : public StoreMPSerializer {
public:
MPDaosSerializer(const DoutPrefixProvider* dpp, DaosStore* store,
DaosObject* obj, const std::string& lock_name) {}
virtual int try_lock(const DoutPrefixProvider* dpp, utime_t dur,
optional_yield y) override {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
virtual int unlock() override { return DAOS_NOT_IMPLEMENTED_LOG(nullptr); }
};
class DaosAtomicWriter : public StoreWriter {
protected:
rgw::sal::DaosStore* store;
const rgw_user& owner;
const rgw_placement_rule* ptail_placement_rule;
uint64_t olh_epoch;
const std::string& unique_tag;
DaosObject obj;
uint64_t total_data_size = 0; // for total data being uploaded
public:
DaosAtomicWriter(const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj,
DaosStore* _store, const rgw_user& _owner,
const rgw_placement_rule* _ptail_placement_rule,
uint64_t _olh_epoch, const std::string& _unique_tag);
~DaosAtomicWriter() = default;
// prepare to start processing object data
virtual int prepare(optional_yield y) override;
// Process a bufferlist
virtual int process(bufferlist&& data, uint64_t offset) override;
// complete the operation and make its result visible to clients
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time* mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at, const char* if_match,
const char* if_nomatch, const std::string* user_data,
rgw_zone_set* zones_trace, bool* canceled,
optional_yield y) override;
};
class DaosMultipartWriter : public StoreWriter {
protected:
rgw::sal::DaosStore* store;
MultipartUpload* upload;
std::string upload_id;
// Part parameters.
const uint64_t part_num;
const std::string part_num_str;
uint64_t actual_part_size = 0;
ds3_part_t* ds3p = nullptr;
bool is_open() { return ds3p != nullptr; };
public:
DaosMultipartWriter(const DoutPrefixProvider* dpp, optional_yield y,
MultipartUpload* _upload,
rgw::sal::Object* obj,
DaosStore* _store, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule,
uint64_t _part_num, const std::string& part_num_str)
: StoreWriter(dpp, y),
store(_store),
upload(_upload),
upload_id(_upload->get_upload_id()),
part_num(_part_num),
part_num_str(part_num_str) {}
virtual ~DaosMultipartWriter();
// prepare to start processing object data
virtual int prepare(optional_yield y) override;
// Process a bufferlist
virtual int process(bufferlist&& data, uint64_t offset) override;
// complete the operation and make its result visible to clients
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time* mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at, const char* if_match,
const char* if_nomatch, const std::string* user_data,
rgw_zone_set* zones_trace, bool* canceled,
optional_yield y) override;
const std::string& get_bucket_name();
};
class DaosMultipartPart : public StoreMultipartPart {
protected:
RGWUploadPartInfo info;
public:
DaosMultipartPart() = default;
virtual ~DaosMultipartPart() = default;
virtual uint32_t get_num() { return info.num; }
virtual uint64_t get_size() { return info.accounted_size; }
virtual const std::string& get_etag() { return info.etag; }
virtual ceph::real_time& get_mtime() { return info.modified; }
friend class DaosMultipartUpload;
};
class DaosMultipartUpload : public StoreMultipartUpload {
DaosStore* store;
RGWMPObj mp_obj;
ACLOwner owner;
ceph::real_time mtime;
rgw_placement_rule placement;
RGWObjManifest manifest;
public:
DaosMultipartUpload(DaosStore* _store, Bucket* _bucket,
const std::string& oid,
std::optional<std::string> upload_id, ACLOwner _owner,
ceph::real_time _mtime)
: StoreMultipartUpload(_bucket),
store(_store),
mp_obj(oid, upload_id),
owner(_owner),
mtime(_mtime) {}
virtual ~DaosMultipartUpload() = default;
virtual const std::string& get_meta() const { return mp_obj.get_meta(); }
virtual const std::string& get_key() const { return mp_obj.get_key(); }
virtual const std::string& get_upload_id() const {
return mp_obj.get_upload_id();
}
virtual const ACLOwner& get_owner() const override { return owner; }
virtual ceph::real_time& get_mtime() { return mtime; }
virtual std::unique_ptr<rgw::sal::Object> get_meta_obj() override;
virtual int init(const DoutPrefixProvider* dpp, optional_yield y,
ACLOwner& owner, rgw_placement_rule& dest_placement,
rgw::sal::Attrs& attrs) override;
virtual int list_parts(const DoutPrefixProvider* dpp, CephContext* cct,
int num_parts, int marker, int* next_marker,
bool* truncated,
bool assume_unsorted = false) override;
virtual int abort(const DoutPrefixProvider* dpp, CephContext* cct) override;
virtual int complete(const DoutPrefixProvider* dpp, optional_yield y,
CephContext* cct, std::map<int, std::string>& part_etags,
std::list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed,
RGWCompressionInfo& cs_info, off_t& off,
std::string& tag, ACLOwner& owner, uint64_t olh_epoch,
rgw::sal::Object* target_obj) override;
virtual int get_info(const DoutPrefixProvider* dpp, optional_yield y,
rgw_placement_rule** rule,
rgw::sal::Attrs* attrs = nullptr) override;
virtual std::unique_ptr<Writer> get_writer(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule, uint64_t part_num,
const std::string& part_num_str) override;
const std::string& get_bucket_name() { return bucket->get_name(); }
};
class DaosStore : public StoreDriver {
private:
DaosZone zone;
RGWSyncModuleInstanceRef sync_module;
public:
ds3_t* ds3 = nullptr;
CephContext* cctx;
DaosStore(CephContext* c) : zone(this), cctx(c) {}
~DaosStore() = default;
virtual const std::string get_name() const override { return "daos"; }
virtual std::unique_ptr<User> get_user(const rgw_user& u) override;
virtual std::string get_cluster_id(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int get_user_by_access_key(const DoutPrefixProvider* dpp,
const std::string& key, optional_yield y,
std::unique_ptr<User>* user) override;
virtual int get_user_by_email(const DoutPrefixProvider* dpp,
const std::string& email, optional_yield y,
std::unique_ptr<User>* user) override;
virtual int get_user_by_swift(const DoutPrefixProvider* dpp,
const std::string& user_str, optional_yield y,
std::unique_ptr<User>* user) override;
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& k) override;
virtual int get_bucket(const DoutPrefixProvider* dpp, User* u,
const rgw_bucket& b, std::unique_ptr<Bucket>* bucket,
optional_yield y) override;
virtual int get_bucket(User* u, const RGWBucketInfo& i,
std::unique_ptr<Bucket>* bucket) override;
virtual int get_bucket(const DoutPrefixProvider* dpp, User* u,
const std::string& tenant, const std::string& name,
std::unique_ptr<Bucket>* bucket,
optional_yield y) override;
virtual bool is_meta_master() override;
virtual int forward_request_to_master(const DoutPrefixProvider* dpp,
User* user, obj_version* objv,
bufferlist& in_data, JSONParser* jp,
req_info& info,
optional_yield y) override;
virtual int forward_iam_request_to_master(
const DoutPrefixProvider* dpp, const RGWAccessKey& key, obj_version* objv,
bufferlist& in_data, RGWXMLDecoder::XMLParser* parser, req_info& info,
optional_yield y) override;
virtual Zone* get_zone() { return &zone; }
virtual std::string zone_unique_id(uint64_t unique_num) override;
virtual std::string zone_unique_trans_id(const uint64_t unique_num) override;
virtual int cluster_stat(RGWClusterStat& stats) override;
virtual std::unique_ptr<Lifecycle> get_lifecycle(void) override;
virtual std::unique_ptr<Notification> get_notification(
rgw::sal::Object* obj, rgw::sal::Object* src_obj, struct req_state* s,
rgw::notify::EventType event_type, optional_yield y,
const std::string* object_name = nullptr) override;
virtual std::unique_ptr<Notification> get_notification(
const DoutPrefixProvider* dpp, rgw::sal::Object* obj,
rgw::sal::Object* src_obj, rgw::notify::EventType event_type,
rgw::sal::Bucket* _bucket, std::string& _user_id,
std::string& _user_tenant, std::string& _req_id,
optional_yield y) override;
virtual RGWLC* get_rgwlc(void) override { return NULL; }
virtual RGWCoroutinesManagerRegistry* get_cr_registry() override {
return NULL;
}
virtual int log_usage(
const DoutPrefixProvider* dpp,
std::map<rgw_user_bucket, RGWUsageBatch>& usage_info) override;
virtual int log_op(const DoutPrefixProvider* dpp, std::string& oid,
bufferlist& bl) override;
virtual int register_to_service_map(
const DoutPrefixProvider* dpp, const std::string& daemon_type,
const std::map<std::string, std::string>& meta) override;
virtual void get_quota(RGWQuota& quota) override;
virtual void get_ratelimit(RGWRateLimitInfo& bucket_ratelimit,
RGWRateLimitInfo& user_ratelimit,
RGWRateLimitInfo& anon_ratelimit) override;
virtual int set_buckets_enabled(const DoutPrefixProvider* dpp,
std::vector<rgw_bucket>& buckets,
bool enabled) override;
virtual uint64_t get_new_req_id() override {
return DAOS_NOT_IMPLEMENTED_LOG(nullptr);
}
virtual int get_sync_policy_handler(const DoutPrefixProvider* dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef* phandler,
optional_yield y) override;
virtual RGWDataSyncStatusManager* get_data_sync_manager(
const rgw_zone_id& source_zone) override;
virtual void wakeup_meta_sync_shards(std::set<int>& shard_ids) override {
return;
}
virtual void wakeup_data_sync_shards(
const DoutPrefixProvider* dpp, const rgw_zone_id& source_zone,
boost::container::flat_map<
int, boost::container::flat_set<rgw_data_notify_entry>>& shard_ids)
override {
return;
}
virtual int clear_usage(const DoutPrefixProvider* dpp) override {
return DAOS_NOT_IMPLEMENTED_LOG(dpp);
}
virtual int read_all_usage(
const DoutPrefixProvider* dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_all_usage(const DoutPrefixProvider* dpp,
uint64_t start_epoch, uint64_t end_epoch) override;
virtual int get_config_key_val(std::string name, bufferlist* bl) override;
virtual int meta_list_keys_init(const DoutPrefixProvider* dpp,
const std::string& section,
const std::string& marker,
void** phandle) override;
virtual int meta_list_keys_next(const DoutPrefixProvider* dpp, void* handle,
int max, std::list<std::string>& keys,
bool* truncated) override;
virtual void meta_list_keys_complete(void* handle) override;
virtual std::string meta_get_marker(void* handle) override;
virtual int meta_remove(const DoutPrefixProvider* dpp,
std::string& metadata_key, optional_yield y) override;
virtual const RGWSyncModuleInstanceRef& get_sync_module() {
return sync_module;
}
virtual std::string get_host_id() { return ""; }
virtual std::unique_ptr<LuaManager> get_lua_manager() override;
virtual std::unique_ptr<RGWRole> get_role(
std::string name, std::string tenant, std::string path = "",
std::string trust_policy = "", std::string max_session_duration_str = "",
std::multimap<std::string, std::string> tags = {}) override;
virtual std::unique_ptr<RGWRole> get_role(const RGWRoleInfo& info) override;
virtual std::unique_ptr<RGWRole> get_role(std::string id) override;
virtual int get_roles(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
std::vector<std::unique_ptr<RGWRole>>& roles) override;
virtual std::unique_ptr<RGWOIDCProvider> get_oidc_provider() override;
virtual int get_oidc_providers(
const DoutPrefixProvider* dpp, const std::string& tenant,
std::vector<std::unique_ptr<RGWOIDCProvider>>& providers) override;
virtual std::unique_ptr<Writer> get_append_writer(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule,
const std::string& unique_tag, uint64_t position,
uint64_t* cur_accounted_size) override;
virtual std::unique_ptr<Writer> get_atomic_writer(
const DoutPrefixProvider* dpp, optional_yield y,
rgw::sal::Object* obj, const rgw_user& owner,
const rgw_placement_rule* ptail_placement_rule, uint64_t olh_epoch,
const std::string& unique_tag) override;
virtual const std::string& get_compression_type(
const rgw_placement_rule& rule) override;
virtual bool valid_placement(const rgw_placement_rule& rule) override;
virtual void finalize(void) override;
virtual CephContext* ctx(void) override { return cctx; }
virtual int initialize(CephContext* cct,
const DoutPrefixProvider* dpp) override;
};
} // namespace rgw::sal
| 43,550 | 40.835735 | 80 |
h
|
null |
ceph-main/src/rgw/rgw_sal_dbstore.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) 2021 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <errno.h>
#include <stdlib.h>
#include <system_error>
#include <unistd.h>
#include <sstream>
#include "common/Clock.h"
#include "common/errno.h"
#include "rgw_sal.h"
#include "rgw_sal_dbstore.h"
#include "rgw_bucket.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw::sal {
int DBUser::list_buckets(const DoutPrefixProvider *dpp, const string& marker,
const string& end_marker, uint64_t max, bool need_stats,
BucketList &buckets, optional_yield y)
{
RGWUserBuckets ulist;
bool is_truncated = false;
int ret;
buckets.clear();
ret = store->getDB()->list_buckets(dpp, "", info.user_id, marker, end_marker, max,
need_stats, &ulist, &is_truncated);
if (ret < 0)
return ret;
buckets.set_truncated(is_truncated);
for (const auto& ent : ulist.get_buckets()) {
buckets.add(std::make_unique<DBBucket>(this->store, ent.second, this));
}
return 0;
}
int DBUser::create_bucket(const DoutPrefixProvider *dpp,
const rgw_bucket& b,
const string& zonegroup_id,
rgw_placement_rule& placement_rule,
string& swift_ver_location,
const RGWQuotaInfo * pquota_info,
const RGWAccessControlPolicy& policy,
Attrs& attrs,
RGWBucketInfo& info,
obj_version& ep_objv,
bool exclusive,
bool obj_lock_enabled,
bool *existed,
req_info& req_info,
std::unique_ptr<Bucket>* bucket_out,
optional_yield y)
{
int ret;
bufferlist in_data;
RGWBucketInfo master_info;
rgw_bucket *pmaster_bucket = nullptr;
uint32_t *pmaster_num_shards = nullptr;
real_time creation_time;
std::unique_ptr<Bucket> bucket;
obj_version objv, *pobjv = NULL;
/* If it exists, look it up; otherwise create it */
ret = store->get_bucket(dpp, this, b, &bucket, y);
if (ret < 0 && ret != -ENOENT)
return ret;
if (ret != -ENOENT) {
RGWAccessControlPolicy old_policy(store->ctx());
*existed = true;
if (swift_ver_location.empty()) {
swift_ver_location = bucket->get_info().swift_ver_location;
}
placement_rule.inherit_from(bucket->get_info().placement_rule);
// don't allow changes to the acl policy
/* int r = rgw_op_get_bucket_policy_from_attr(dpp, this, this, bucket->get_attrs(),
&old_policy, y);
if (r >= 0 && old_policy != policy) {
bucket_out->swap(bucket);
return -EEXIST;
}*/
} else {
bucket = std::make_unique<DBBucket>(store, b, this);
*existed = false;
bucket->set_attrs(attrs);
// XXX: For now single default zone and STANDARD storage class
// supported.
placement_rule.name = "default";
placement_rule.storage_class = "STANDARD";
}
/*
* XXX: If not master zone, fwd the request to master zone.
* For now DBStore has single zone.
*/
std::string zid = zonegroup_id;
/* if (zid.empty()) {
zid = svc()->zone->get_zonegroup().get_id();
} */
if (*existed) {
rgw_placement_rule selected_placement_rule;
/* XXX: Handle this when zone is implemented
ret = svc()->zone->select_bucket_placement(this.get_info(),
zid, placement_rule,
&selected_placement_rule, nullptr, y);
if (selected_placement_rule != info.placement_rule) {
ret = -EEXIST;
bucket_out->swap(bucket);
return ret;
} */
} else {
/* XXX: We may not need to send all these params. Cleanup the unused ones */
ret = store->getDB()->create_bucket(dpp, this->get_info(), bucket->get_key(),
zid, placement_rule, swift_ver_location, pquota_info,
attrs, info, pobjv, &ep_objv, creation_time,
pmaster_bucket, pmaster_num_shards, y, exclusive);
if (ret == -EEXIST) {
*existed = true;
ret = 0;
} else if (ret != 0) {
return ret;
}
}
bucket->set_version(ep_objv);
bucket->get_info() = info;
bucket_out->swap(bucket);
return ret;
}
int DBUser::read_attrs(const DoutPrefixProvider* dpp, optional_yield y)
{
int ret;
ret = store->getDB()->get_user(dpp, string("user_id"), get_id().id, info, &attrs,
&objv_tracker);
return ret;
}
int DBUser::read_stats(const DoutPrefixProvider *dpp,
optional_yield y, RGWStorageStats* stats,
ceph::real_time *last_stats_sync,
ceph::real_time *last_stats_update)
{
return 0;
}
/* stats - Not for first pass */
int DBUser::read_stats_async(const DoutPrefixProvider *dpp, RGWGetUserStats_CB *cb)
{
return 0;
}
int DBUser::complete_flush_stats(const DoutPrefixProvider *dpp, optional_yield y)
{
return 0;
}
int DBUser::read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, uint32_t max_entries,
bool *is_truncated, RGWUsageIter& usage_iter,
map<rgw_user_bucket, rgw_usage_log_entry>& usage)
{
return 0;
}
int DBUser::trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y)
{
return 0;
}
int DBUser::load_user(const DoutPrefixProvider *dpp, optional_yield y)
{
int ret = 0;
ret = store->getDB()->get_user(dpp, string("user_id"), get_id().id, info, &attrs,
&objv_tracker);
return ret;
}
int DBUser::merge_and_store_attrs(const DoutPrefixProvider* dpp, Attrs& new_attrs, optional_yield y)
{
for(auto& it : new_attrs) {
attrs[it.first] = it.second;
}
return store_user(dpp, y, false);
}
int DBUser::store_user(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, RGWUserInfo* old_info)
{
int ret = 0;
ret = store->getDB()->store_user(dpp, info, exclusive, &attrs, &objv_tracker, old_info);
return ret;
}
int DBUser::remove_user(const DoutPrefixProvider* dpp, optional_yield y)
{
int ret = 0;
ret = store->getDB()->remove_user(dpp, info, &objv_tracker);
return ret;
}
int DBUser::verify_mfa(const std::string& mfa_str, bool* verified, const DoutPrefixProvider *dpp, optional_yield y)
{
*verified = false;
return 0;
}
int DBBucket::remove_bucket(const DoutPrefixProvider *dpp, bool delete_children, bool forward_to_master, req_info* req_info, optional_yield y)
{
int ret;
ret = load_bucket(dpp, y);
if (ret < 0)
return ret;
/* XXX: handle delete_children */
if (!delete_children) {
/* Check if there are any objects */
rgw::sal::Bucket::ListParams params;
params.list_versions = true;
params.allow_unordered = true;
rgw::sal::Bucket::ListResults results;
results.objs.clear();
ret = list(dpp, params, 2, results, null_yield);
if (ret < 0) {
ldpp_dout(dpp, 20) << __func__ << ": Bucket list objects returned " <<
ret << dendl;
return ret;
}
if (!results.objs.empty()) {
ret = -ENOTEMPTY;
ldpp_dout(dpp, -1) << __func__ << ": Bucket Not Empty.. returning " <<
ret << dendl;
return ret;
}
}
ret = store->getDB()->remove_bucket(dpp, info);
return ret;
}
int DBBucket::remove_bucket_bypass_gc(int concurrent_max, bool
keep_index_consistent,
optional_yield y, const
DoutPrefixProvider *dpp) {
return 0;
}
int DBBucket::load_bucket(const DoutPrefixProvider *dpp, optional_yield y, bool get_stats)
{
int ret = 0;
ret = store->getDB()->get_bucket_info(dpp, string("name"), "", info, &attrs,
&mtime, &bucket_version);
return ret;
}
/* stats - Not for first pass */
int DBBucket::read_stats(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id,
std::string *bucket_ver, std::string *master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string *max_marker, bool *syncstopped)
{
return 0;
}
int DBBucket::read_stats_async(const DoutPrefixProvider *dpp, const bucket_index_layout_generation& idx_layout, int shard_id, RGWGetBucketStats_CB *ctx)
{
return 0;
}
int DBBucket::sync_user_stats(const DoutPrefixProvider *dpp, optional_yield y)
{
return 0;
}
int DBBucket::update_container_stats(const DoutPrefixProvider *dpp, optional_yield y)
{
return 0;
}
int DBBucket::check_bucket_shards(const DoutPrefixProvider *dpp, optional_yield y)
{
return 0;
}
int DBBucket::chown(const DoutPrefixProvider *dpp, User& new_user, optional_yield y)
{
int ret;
ret = store->getDB()->update_bucket(dpp, "owner", info, false, &(new_user.get_id()), nullptr, nullptr, nullptr);
return ret;
}
int DBBucket::put_info(const DoutPrefixProvider *dpp, bool exclusive, ceph::real_time _mtime, optional_yield y)
{
int ret;
ret = store->getDB()->update_bucket(dpp, "info", info, exclusive, nullptr, nullptr, &_mtime, &info.objv_tracker);
return ret;
}
/* Make sure to call get_bucket_info() if you need it first */
bool DBBucket::is_owner(User* user)
{
return (info.owner.compare(user->get_id()) == 0);
}
int DBBucket::check_empty(const DoutPrefixProvider *dpp, optional_yield y)
{
/* XXX: Check if bucket contains any objects */
return 0;
}
int DBBucket::check_quota(const DoutPrefixProvider *dpp, RGWQuota& quota, uint64_t obj_size,
optional_yield y, bool check_size_only)
{
/* Not Handled in the first pass as stats are also needed */
return 0;
}
int DBBucket::merge_and_store_attrs(const DoutPrefixProvider *dpp, Attrs& new_attrs, optional_yield y)
{
int ret = 0;
for(auto& it : new_attrs) {
attrs[it.first] = it.second;
}
/* XXX: handle has_instance_obj like in set_bucket_instance_attrs() */
ret = store->getDB()->update_bucket(dpp, "attrs", info, false, nullptr, &new_attrs, nullptr, &get_info().objv_tracker);
return ret;
}
int DBBucket::try_refresh_info(const DoutPrefixProvider *dpp, ceph::real_time *pmtime, optional_yield y)
{
int ret = 0;
ret = store->getDB()->get_bucket_info(dpp, string("name"), "", info, &attrs,
pmtime, &bucket_version);
return ret;
}
/* XXX: usage and stats not supported in the first pass */
int DBBucket::read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool *is_truncated,
RGWUsageIter& usage_iter,
map<rgw_user_bucket, rgw_usage_log_entry>& usage)
{
return 0;
}
int DBBucket::trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y)
{
return 0;
}
int DBBucket::remove_objs_from_index(const DoutPrefixProvider *dpp, std::list<rgw_obj_index_key>& objs_to_unlink)
{
/* XXX: CHECK: Unlike RadosStore, there is no seperate bucket index table.
* Delete all the object in the list from the object table of this
* bucket
*/
return 0;
}
int DBBucket::check_index(const DoutPrefixProvider *dpp, std::map<RGWObjCategory, RGWStorageStats>& existing_stats, std::map<RGWObjCategory, RGWStorageStats>& calculated_stats)
{
/* XXX: stats not supported yet */
return 0;
}
int DBBucket::rebuild_index(const DoutPrefixProvider *dpp)
{
/* there is no index table in dbstore. Not applicable */
return 0;
}
int DBBucket::set_tag_timeout(const DoutPrefixProvider *dpp, uint64_t timeout)
{
/* XXX: CHECK: set tag timeout for all the bucket objects? */
return 0;
}
int DBBucket::purge_instance(const DoutPrefixProvider *dpp, optional_yield y)
{
/* XXX: CHECK: for dbstore only single instance supported.
* Remove all the objects for that instance? Anything extra needed?
*/
return 0;
}
int DBBucket::set_acl(const DoutPrefixProvider *dpp, RGWAccessControlPolicy &acl, optional_yield y)
{
int ret = 0;
bufferlist aclbl;
acls = acl;
acl.encode(aclbl);
Attrs attrs = get_attrs();
attrs[RGW_ATTR_ACL] = aclbl;
ret = store->getDB()->update_bucket(dpp, "attrs", info, false, &(acl.get_owner().get_id()), &attrs, nullptr, nullptr);
return ret;
}
std::unique_ptr<Object> DBBucket::get_object(const rgw_obj_key& k)
{
return std::make_unique<DBObject>(this->store, k, this);
}
int DBBucket::list(const DoutPrefixProvider *dpp, ListParams& params, int max, ListResults& results, optional_yield y)
{
int ret = 0;
results.objs.clear();
DB::Bucket target(store->getDB(), get_info());
DB::Bucket::List list_op(&target);
list_op.params.prefix = params.prefix;
list_op.params.delim = params.delim;
list_op.params.marker = params.marker;
list_op.params.ns = params.ns;
list_op.params.end_marker = params.end_marker;
list_op.params.ns = params.ns;
list_op.params.enforce_ns = params.enforce_ns;
list_op.params.access_list_filter = params.access_list_filter;
list_op.params.force_check_filter = params.force_check_filter;
list_op.params.list_versions = params.list_versions;
list_op.params.allow_unordered = params.allow_unordered;
results.objs.clear();
ret = list_op.list_objects(dpp, max, &results.objs, &results.common_prefixes, &results.is_truncated);
if (ret >= 0) {
results.next_marker = list_op.get_next_marker();
params.marker = results.next_marker;
}
return ret;
}
std::unique_ptr<MultipartUpload> DBBucket::get_multipart_upload(
const std::string& oid,
std::optional<std::string> upload_id,
ACLOwner owner, ceph::real_time mtime) {
return std::make_unique<DBMultipartUpload>(this->store, this, oid, upload_id,
std::move(owner), mtime);
}
int DBBucket::list_multiparts(const DoutPrefixProvider *dpp,
const string& prefix,
string& marker,
const string& delim,
const int& max_uploads,
vector<std::unique_ptr<MultipartUpload>>& uploads,
map<string, bool> *common_prefixes,
bool *is_truncated, optional_yield y) {
return 0;
}
int DBBucket::abort_multiparts(const DoutPrefixProvider* dpp,
CephContext* cct, optional_yield y) {
return 0;
}
void DBStore::finalize(void)
{
if (dbsm)
dbsm->destroyAllHandles();
}
const std::string& DBZoneGroup::get_endpoint() const {
if (!group->endpoints.empty()) {
return group->endpoints.front();
} else {
// use zonegroup's master zone endpoints
auto z = group->zones.find(group->master_zone);
if (z != group->zones.end() && !z->second.endpoints.empty()) {
return z->second.endpoints.front();
}
}
return empty;
}
bool DBZoneGroup::placement_target_exists(std::string& target) const {
return !!group->placement_targets.count(target);
}
int DBZoneGroup::get_placement_target_names(std::set<std::string>& names) const {
for (const auto& target : group->placement_targets) {
names.emplace(target.second.name);
}
return 0;
}
ZoneGroup& DBZone::get_zonegroup()
{
return *zonegroup;
}
const RGWZoneParams& DBZone::get_rgw_params()
{
return *zone_params;
}
const std::string& DBZone::get_id()
{
return zone_params->get_id();
}
const std::string& DBZone::get_name() const
{
return zone_params->get_name();
}
bool DBZone::is_writeable()
{
return true;
}
bool DBZone::get_redirect_endpoint(std::string* endpoint)
{
return false;
}
bool DBZone::has_zonegroup_api(const std::string& api) const
{
return false;
}
const std::string& DBZone::get_current_period_id()
{
return current_period->get_id();
}
const RGWAccessKey& DBZone::get_system_key()
{
return zone_params->system_key;
}
const std::string& DBZone::get_realm_name()
{
return realm->get_name();
}
const std::string& DBZone::get_realm_id()
{
return realm->get_id();
}
RGWBucketSyncPolicyHandlerRef DBZone::get_sync_policy_handler()
{
return nullptr;
}
std::unique_ptr<LuaManager> DBStore::get_lua_manager()
{
return std::make_unique<DBLuaManager>(this);
}
int DBObject::get_obj_state(const DoutPrefixProvider* dpp, RGWObjState **pstate, optional_yield y, bool follow_olh)
{
RGWObjState* astate;
DB::Object op_target(store->getDB(), get_bucket()->get_info(), get_obj());
int ret = op_target.get_obj_state(dpp, get_bucket()->get_info(), get_obj(), follow_olh, &astate);
if (ret < 0) {
return ret;
}
/* Don't overwrite obj, atomic, or prefetch */
rgw_obj obj = get_obj();
bool is_atomic = state.is_atomic;
bool prefetch_data = state.prefetch_data;
state = *astate;
*pstate = &state;
state.obj = obj;
state.is_atomic = is_atomic;
state.prefetch_data = prefetch_data;
return ret;
}
int DBObject::read_attrs(const DoutPrefixProvider* dpp, DB::Object::Read &read_op, optional_yield y, rgw_obj* target_obj)
{
read_op.params.attrs = &state.attrset;
read_op.params.target_obj = target_obj;
read_op.params.obj_size = &state.size;
read_op.params.lastmod = &state.mtime;
return read_op.prepare(dpp);
}
int DBObject::set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs, Attrs* delattrs, optional_yield y)
{
Attrs empty;
DB::Object op_target(store->getDB(),
get_bucket()->get_info(), get_obj());
return op_target.set_attrs(dpp, setattrs ? *setattrs : empty, delattrs);
}
int DBObject::get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp, rgw_obj* target_obj)
{
DB::Object op_target(store->getDB(), get_bucket()->get_info(), get_obj());
DB::Object::Read read_op(&op_target);
return read_attrs(dpp, read_op, y, target_obj);
}
int DBObject::modify_obj_attrs(const char* attr_name, bufferlist& attr_val, optional_yield y, const DoutPrefixProvider* dpp)
{
rgw_obj target = get_obj();
int r = get_obj_attrs(y, dpp, &target);
if (r < 0) {
return r;
}
set_atomic();
state.attrset[attr_name] = attr_val;
return set_obj_attrs(dpp, &state.attrset, nullptr, y);
}
int DBObject::delete_obj_attrs(const DoutPrefixProvider* dpp, const char* attr_name, optional_yield y)
{
Attrs rmattr;
bufferlist bl;
set_atomic();
rmattr[attr_name] = bl;
return set_obj_attrs(dpp, nullptr, &rmattr, y);
}
bool DBObject::is_expired() {
return false;
}
void DBObject::gen_rand_obj_instance_name()
{
store->getDB()->gen_rand_obj_instance_name(&state.obj.key);
}
int DBObject::omap_get_vals_by_keys(const DoutPrefixProvider *dpp, const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals)
{
DB::Object op_target(store->getDB(),
get_bucket()->get_info(), get_obj());
return op_target.obj_omap_get_vals_by_keys(dpp, oid, keys, vals);
}
int DBObject::omap_set_val_by_key(const DoutPrefixProvider *dpp, const std::string& key, bufferlist& val,
bool must_exist, optional_yield y)
{
DB::Object op_target(store->getDB(),
get_bucket()->get_info(), get_obj());
return op_target.obj_omap_set_val_by_key(dpp, key, val, must_exist);
}
int DBObject::chown(User& new_user, const DoutPrefixProvider* dpp, optional_yield y)
{
return 0;
}
std::unique_ptr<MPSerializer> DBObject::get_serializer(const DoutPrefixProvider *dpp,
const std::string& lock_name)
{
return std::make_unique<MPDBSerializer>(dpp, store, this, lock_name);
}
int DBObject::transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime,
uint64_t olh_epoch,
const DoutPrefixProvider* dpp,
optional_yield y)
{
DB::Object op_target(store->getDB(),
get_bucket()->get_info(), get_obj());
return op_target.transition(dpp, placement_rule, mtime, olh_epoch);
}
bool DBObject::placement_rules_match(rgw_placement_rule& r1, rgw_placement_rule& r2)
{
/* XXX: support single default zone and zonegroup for now */
return true;
}
int DBObject::dump_obj_layout(const DoutPrefixProvider *dpp, optional_yield y, Formatter* f)
{
return 0;
}
std::unique_ptr<Object::ReadOp> DBObject::get_read_op()
{
return std::make_unique<DBObject::DBReadOp>(this, nullptr);
}
DBObject::DBReadOp::DBReadOp(DBObject *_source, RGWObjectCtx *_rctx) :
source(_source),
rctx(_rctx),
op_target(_source->store->getDB(),
_source->get_bucket()->get_info(),
_source->get_obj()),
parent_op(&op_target)
{ }
int DBObject::DBReadOp::prepare(optional_yield y, const DoutPrefixProvider* dpp)
{
uint64_t obj_size;
parent_op.conds.mod_ptr = params.mod_ptr;
parent_op.conds.unmod_ptr = params.unmod_ptr;
parent_op.conds.high_precision_time = params.high_precision_time;
parent_op.conds.mod_zone_id = params.mod_zone_id;
parent_op.conds.mod_pg_ver = params.mod_pg_ver;
parent_op.conds.if_match = params.if_match;
parent_op.conds.if_nomatch = params.if_nomatch;
parent_op.params.lastmod = params.lastmod;
parent_op.params.target_obj = params.target_obj;
parent_op.params.obj_size = &obj_size;
parent_op.params.attrs = &source->get_attrs();
int ret = parent_op.prepare(dpp);
if (ret < 0)
return ret;
source->set_key(parent_op.state.obj.key);
source->set_obj_size(obj_size);
return ret;
}
int DBObject::DBReadOp::read(int64_t ofs, int64_t end, bufferlist& bl, optional_yield y, const DoutPrefixProvider* dpp)
{
return parent_op.read(ofs, end, bl, dpp);
}
int DBObject::DBReadOp::get_attr(const DoutPrefixProvider* dpp, const char* name, bufferlist& dest, optional_yield y)
{
return parent_op.get_attr(dpp, name, dest);
}
std::unique_ptr<Object::DeleteOp> DBObject::get_delete_op()
{
return std::make_unique<DBObject::DBDeleteOp>(this);
}
DBObject::DBDeleteOp::DBDeleteOp(DBObject *_source) :
source(_source),
op_target(_source->store->getDB(),
_source->get_bucket()->get_info(),
_source->get_obj()),
parent_op(&op_target)
{ }
int DBObject::DBDeleteOp::delete_obj(const DoutPrefixProvider* dpp, optional_yield y)
{
parent_op.params.bucket_owner = params.bucket_owner.get_id();
parent_op.params.versioning_status = params.versioning_status;
parent_op.params.obj_owner = params.obj_owner;
parent_op.params.olh_epoch = params.olh_epoch;
parent_op.params.marker_version_id = params.marker_version_id;
parent_op.params.bilog_flags = params.bilog_flags;
parent_op.params.remove_objs = params.remove_objs;
parent_op.params.expiration_time = params.expiration_time;
parent_op.params.unmod_since = params.unmod_since;
parent_op.params.mtime = params.mtime;
parent_op.params.high_precision_time = params.high_precision_time;
parent_op.params.zones_trace = params.zones_trace;
parent_op.params.abortmp = params.abortmp;
parent_op.params.parts_accounted_size = params.parts_accounted_size;
int ret = parent_op.delete_obj(dpp);
if (ret < 0)
return ret;
result.delete_marker = parent_op.result.delete_marker;
result.version_id = parent_op.result.version_id;
return ret;
}
int DBObject::delete_object(const DoutPrefixProvider* dpp, optional_yield y, bool prevent_versioning)
{
DB::Object del_target(store->getDB(), bucket->get_info(), get_obj());
DB::Object::Delete del_op(&del_target);
del_op.params.bucket_owner = bucket->get_info().owner;
del_op.params.versioning_status = bucket->get_info().versioning_status();
return del_op.delete_obj(dpp);
}
int DBObject::copy_object(User* user,
req_info* info,
const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object,
rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket,
const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime,
ceph::real_time* mtime,
const ceph::real_time* mod_ptr,
const ceph::real_time* unmod_ptr,
bool high_precision_time,
const char* if_match,
const char* if_nomatch,
AttrsMod attrs_mod,
bool copy_if_newer,
Attrs& attrs,
RGWObjCategory category,
uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at,
std::string* version_id,
std::string* tag,
std::string* etag,
void (*progress_cb)(off_t, void *),
void* progress_data,
const DoutPrefixProvider* dpp,
optional_yield y)
{
return 0;
}
int DBObject::DBReadOp::iterate(const DoutPrefixProvider* dpp, int64_t ofs, int64_t end, RGWGetDataCB* cb, optional_yield y)
{
return parent_op.iterate(dpp, ofs, end, cb);
}
int DBObject::swift_versioning_restore(bool& restored,
const DoutPrefixProvider* dpp, optional_yield y)
{
return 0;
}
int DBObject::swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y)
{
return 0;
}
int DBMultipartUpload::abort(const DoutPrefixProvider *dpp, CephContext *cct, optional_yield y)
{
std::unique_ptr<rgw::sal::Object> meta_obj = get_meta_obj();
meta_obj->set_in_extra_data(true);
meta_obj->set_hash_source(mp_obj.get_key());
int ret;
std::unique_ptr<rgw::sal::Object::DeleteOp> del_op = meta_obj->get_delete_op();
del_op->params.bucket_owner = bucket->get_acl_owner();
del_op->params.versioning_status = 0;
// Since the data objects are associated with meta obj till
// MultipartUpload::Complete() is done, removing the metadata obj
// should remove all the uploads so far.
ret = del_op->delete_obj(dpp, null_yield);
if (ret < 0) {
ldpp_dout(dpp, 20) << __func__ << ": del_op.delete_obj returned " <<
ret << dendl;
}
return (ret == -ENOENT) ? -ERR_NO_SUCH_UPLOAD : ret;
}
static string mp_ns = RGW_OBJ_NS_MULTIPART;
std::unique_ptr<rgw::sal::Object> DBMultipartUpload::get_meta_obj()
{
return bucket->get_object(rgw_obj_key(get_meta(), string(), mp_ns));
}
int DBMultipartUpload::init(const DoutPrefixProvider *dpp, optional_yield y, ACLOwner& owner, rgw_placement_rule& dest_placement, rgw::sal::Attrs& attrs)
{
int ret;
std::string oid = mp_obj.get_key();
char buf[33];
std::unique_ptr<rgw::sal::Object> obj; // create meta obj
gen_rand_alphanumeric(store->ctx(), buf, sizeof(buf) - 1);
std::string upload_id = MULTIPART_UPLOAD_ID_PREFIX; /* v2 upload id */
upload_id.append(buf);
mp_obj.init(oid, upload_id);
obj = get_meta_obj();
DB::Object op_target(store->getDB(), obj->get_bucket()->get_info(),
obj->get_obj());
DB::Object::Write obj_op(&op_target);
/* Create meta object */
obj_op.meta.owner = owner.get_id();
obj_op.meta.category = RGWObjCategory::MultiMeta;
obj_op.meta.flags = PUT_OBJ_CREATE_EXCL;
obj_op.meta.mtime = &mtime;
multipart_upload_info upload_info;
upload_info.dest_placement = dest_placement;
bufferlist bl;
encode(upload_info, bl);
obj_op.meta.data = &bl;
ret = obj_op.prepare(dpp);
if (ret < 0)
return ret;
ret = obj_op.write_meta(dpp, bl.length(), bl.length(), attrs);
return ret;
}
int DBMultipartUpload::list_parts(const DoutPrefixProvider *dpp, CephContext *cct,
int num_parts, int marker,
int *next_marker, bool *truncated, optional_yield y,
bool assume_unsorted)
{
std::list<RGWUploadPartInfo> parts_map;
std::unique_ptr<rgw::sal::Object> obj = get_meta_obj();
parts.clear();
int ret;
DB::Object op_target(store->getDB(),
obj->get_bucket()->get_info(), obj->get_obj());
ret = op_target.get_mp_parts_list(dpp, parts_map);
if (ret < 0) {
return ret;
}
int last_num = 0;
while (!parts_map.empty()) {
std::unique_ptr<DBMultipartPart> part = std::make_unique<DBMultipartPart>();
RGWUploadPartInfo &pinfo = parts_map.front();
part->set_info(pinfo);
if ((int)pinfo.num > marker) {
last_num = pinfo.num;
parts[pinfo.num] = std::move(part);
}
parts_map.pop_front();
}
/* rebuild a map with only num_parts entries */
std::map<uint32_t, std::unique_ptr<MultipartPart>> new_parts;
std::map<uint32_t, std::unique_ptr<MultipartPart>>::iterator piter;
int i;
for (i = 0, piter = parts.begin();
i < num_parts && piter != parts.end();
++i, ++piter) {
last_num = piter->first;
new_parts[piter->first] = std::move(piter->second);
}
if (truncated) {
*truncated = (piter != parts.end());
}
parts.swap(new_parts);
if (next_marker) {
*next_marker = last_num;
}
return 0;
}
int DBMultipartUpload::complete(const DoutPrefixProvider *dpp,
optional_yield y, CephContext* cct,
map<int, string>& part_etags,
list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed,
RGWCompressionInfo& cs_info, off_t& ofs,
std::string& tag, ACLOwner& owner,
uint64_t olh_epoch,
rgw::sal::Object* target_obj)
{
char final_etag[CEPH_CRYPTO_MD5_DIGESTSIZE];
char final_etag_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 16];
std::string etag;
bufferlist etag_bl;
MD5 hash;
bool truncated;
int ret;
int total_parts = 0;
int handled_parts = 0;
int max_parts = 1000;
int marker = 0;
uint64_t min_part_size = cct->_conf->rgw_multipart_min_part_size;
auto etags_iter = part_etags.begin();
rgw::sal::Attrs attrs = target_obj->get_attrs();
ofs = 0;
accounted_size = 0;
do {
ret = list_parts(dpp, cct, max_parts, marker, &marker, &truncated, y);
if (ret == -ENOENT) {
ret = -ERR_NO_SUCH_UPLOAD;
}
if (ret < 0)
return ret;
total_parts += parts.size();
if (!truncated && total_parts != (int)part_etags.size()) {
ldpp_dout(dpp, 0) << "NOTICE: total parts mismatch: have: " << total_parts
<< " expected: " << part_etags.size() << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
for (auto obj_iter = parts.begin(); etags_iter != part_etags.end() && obj_iter != parts.end(); ++etags_iter, ++obj_iter, ++handled_parts) {
DBMultipartPart* part = dynamic_cast<rgw::sal::DBMultipartPart*>(obj_iter->second.get());
uint64_t part_size = part->get_size();
if (handled_parts < (int)part_etags.size() - 1 &&
part_size < min_part_size) {
ret = -ERR_TOO_SMALL;
return ret;
}
char petag[CEPH_CRYPTO_MD5_DIGESTSIZE];
if (etags_iter->first != (int)obj_iter->first) {
ldpp_dout(dpp, 0) << "NOTICE: parts num mismatch: next requested: "
<< etags_iter->first << " next uploaded: "
<< obj_iter->first << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
string part_etag = rgw_string_unquote(etags_iter->second);
if (part_etag.compare(part->get_etag()) != 0) {
ldpp_dout(dpp, 0) << "NOTICE: etag mismatch: part: " << etags_iter->first
<< " etag: " << etags_iter->second << dendl;
ret = -ERR_INVALID_PART;
return ret;
}
hex_to_buf(part->get_etag().c_str(), petag,
CEPH_CRYPTO_MD5_DIGESTSIZE);
hash.Update((const unsigned char *)petag, sizeof(petag));
RGWUploadPartInfo& obj_part = part->get_info();
ofs += obj_part.size;
accounted_size += obj_part.accounted_size;
}
} while (truncated);
hash.Final((unsigned char *)final_etag);
buf_to_hex((unsigned char *)final_etag, sizeof(final_etag), final_etag_str);
snprintf(&final_etag_str[CEPH_CRYPTO_MD5_DIGESTSIZE * 2],
sizeof(final_etag_str) - CEPH_CRYPTO_MD5_DIGESTSIZE * 2,
"-%lld", (long long)part_etags.size());
etag = final_etag_str;
ldpp_dout(dpp, 10) << "calculated etag: " << etag << dendl;
etag_bl.append(etag);
attrs[RGW_ATTR_ETAG] = etag_bl;
/* XXX: handle compression ? */
/* Rename all the object data entries with original object name (i.e
* from 'head_obj.name + "." + upload_id' to head_obj.name) */
/* Original head object */
DB::Object op_target(store->getDB(),
target_obj->get_bucket()->get_info(),
target_obj->get_obj(), get_upload_id());
DB::Object::Write obj_op(&op_target);
ret = obj_op.prepare(dpp);
obj_op.meta.owner = owner.get_id();
obj_op.meta.flags = PUT_OBJ_CREATE;
obj_op.meta.category = RGWObjCategory::Main;
obj_op.meta.modify_tail = true;
obj_op.meta.completeMultipart = true;
ret = obj_op.write_meta(dpp, ofs, accounted_size, attrs);
if (ret < 0)
return ret;
/* No need to delete Meta obj here. It is deleted from sal */
return ret;
}
int DBMultipartUpload::get_info(const DoutPrefixProvider *dpp, optional_yield y, rgw_placement_rule** rule, rgw::sal::Attrs* attrs)
{
if (!rule && !attrs) {
return 0;
}
if (rule) {
if (!placement.empty()) {
*rule = &placement;
if (!attrs) {
/* Don't need attrs, done */
return 0;
}
} else {
*rule = nullptr;
}
}
/* We need either attributes or placement, so we need a read */
std::unique_ptr<rgw::sal::Object> meta_obj;
meta_obj = get_meta_obj();
meta_obj->set_in_extra_data(true);
multipart_upload_info upload_info;
bufferlist headbl;
/* Read the obj head which contains the multipart_upload_info */
std::unique_ptr<rgw::sal::Object::ReadOp> read_op = meta_obj->get_read_op();
int ret = read_op->prepare(y, dpp);
if (ret < 0) {
if (ret == -ENOENT) {
return -ERR_NO_SUCH_UPLOAD;
}
return ret;
}
if (attrs) {
/* Attrs are filled in by prepare */
*attrs = meta_obj->get_attrs();
if (!rule || *rule != nullptr) {
/* placement was cached; don't actually read */
return 0;
}
}
/* Now read the placement from the head */
ret = read_op->read(0, store->getDB()->get_max_head_size(), headbl, y, dpp);
if (ret < 0) {
if (ret == -ENOENT) {
return -ERR_NO_SUCH_UPLOAD;
}
return ret;
}
if (headbl.length() <= 0) {
return -ERR_NO_SUCH_UPLOAD;
}
/* Decode multipart_upload_info */
auto hiter = headbl.cbegin();
try {
decode(upload_info, hiter);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: failed to decode multipart upload info" << dendl;
return -EIO;
}
placement = upload_info.dest_placement;
*rule = &placement;
return 0;
}
std::unique_ptr<Writer> DBMultipartUpload::get_writer(
const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t part_num,
const std::string& part_num_str)
{
return std::make_unique<DBMultipartWriter>(dpp, y, this, obj, store, owner,
ptail_placement_rule, part_num, part_num_str);
}
DBMultipartWriter::DBMultipartWriter(const DoutPrefixProvider *dpp,
optional_yield y,
MultipartUpload* upload,
rgw::sal::Object* obj,
DBStore* _driver,
const rgw_user& _owner,
const rgw_placement_rule *_ptail_placement_rule,
uint64_t _part_num, const std::string& _part_num_str):
StoreWriter(dpp, y),
store(_driver),
owner(_owner),
ptail_placement_rule(_ptail_placement_rule),
head_obj(obj),
upload_id(upload->get_upload_id()),
part_num(_part_num),
oid(head_obj->get_name() + "." + upload_id +
"." + std::to_string(part_num)),
meta_obj(((DBMultipartUpload*)upload)->get_meta_obj()),
op_target(_driver->getDB(), head_obj->get_bucket()->get_info(), head_obj->get_obj(), upload_id),
parent_op(&op_target),
part_num_str(_part_num_str) {}
int DBMultipartWriter::prepare(optional_yield y)
{
parent_op.prepare(NULL);
parent_op.set_mp_part_str(upload_id + "." + std::to_string(part_num));
// XXX: do we need to handle part_num_str??
return 0;
}
int DBMultipartWriter::process(bufferlist&& data, uint64_t offset)
{
/* XXX: same as AtomicWriter..consolidate code */
total_data_size += data.length();
/* XXX: Optimize all bufferlist copies in this function */
/* copy head_data into meta. But for multipart we do not
* need to write head_data */
uint64_t max_chunk_size = store->getDB()->get_max_chunk_size();
int excess_size = 0;
/* Accumulate tail_data till max_chunk_size or flush op */
bufferlist tail_data;
if (data.length() != 0) {
parent_op.meta.data = &head_data; /* Null data ?? */
/* handle tail )parts.
* First accumulate and write data into dbstore in its chunk_size
* parts
*/
if (!tail_part_size) { /* new tail part */
tail_part_offset = offset;
}
data.begin(0).copy(data.length(), tail_data);
tail_part_size += tail_data.length();
tail_part_data.append(tail_data);
if (tail_part_size < max_chunk_size) {
return 0;
} else {
int write_ofs = 0;
while (tail_part_size >= max_chunk_size) {
excess_size = tail_part_size - max_chunk_size;
bufferlist tmp;
tail_part_data.begin(write_ofs).copy(max_chunk_size, tmp);
/* write tail objects data */
int ret = parent_op.write_data(dpp, tmp, tail_part_offset);
if (ret < 0) {
return ret;
}
tail_part_size -= max_chunk_size;
write_ofs += max_chunk_size;
tail_part_offset += max_chunk_size;
}
/* reset tail parts or update if excess data */
if (excess_size > 0) { /* wrote max_chunk_size data */
tail_part_size = excess_size;
bufferlist tmp;
tail_part_data.begin(write_ofs).copy(excess_size, tmp);
tail_part_data = tmp;
} else {
tail_part_size = 0;
tail_part_data.clear();
tail_part_offset = 0;
}
}
} else {
if (tail_part_size == 0) {
return 0; /* nothing more to write */
}
/* flush watever tail data is present */
int ret = parent_op.write_data(dpp, tail_part_data, tail_part_offset);
if (ret < 0) {
return ret;
}
tail_part_size = 0;
tail_part_data.clear();
tail_part_offset = 0;
}
return 0;
}
int DBMultipartWriter::complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y)
{
int ret = 0;
/* XXX: same as AtomicWriter..consolidate code */
parent_op.meta.mtime = mtime;
parent_op.meta.delete_at = delete_at;
parent_op.meta.if_match = if_match;
parent_op.meta.if_nomatch = if_nomatch;
parent_op.meta.user_data = user_data;
parent_op.meta.zones_trace = zones_trace;
/* XXX: handle accounted size */
accounted_size = total_data_size;
if (ret < 0)
return ret;
RGWUploadPartInfo info;
info.num = part_num;
info.etag = etag;
info.size = total_data_size;
info.accounted_size = accounted_size;
info.modified = real_clock::now();
//info.manifest = manifest;
DB::Object op_target(store->getDB(),
meta_obj->get_bucket()->get_info(), meta_obj->get_obj());
ret = op_target.add_mp_part(dpp, info);
if (ret < 0) {
return ret == -ENOENT ? -ERR_NO_SUCH_UPLOAD : ret;
}
return 0;
}
DBAtomicWriter::DBAtomicWriter(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* _obj,
DBStore* _driver,
const rgw_user& _owner,
const rgw_placement_rule *_ptail_placement_rule,
uint64_t _olh_epoch,
const std::string& _unique_tag) :
StoreWriter(dpp, y),
store(_driver),
owner(_owner),
ptail_placement_rule(_ptail_placement_rule),
olh_epoch(_olh_epoch),
unique_tag(_unique_tag),
obj(_driver, _obj->get_key(), _obj->get_bucket()),
op_target(_driver->getDB(), obj.get_bucket()->get_info(), obj.get_obj()),
parent_op(&op_target) {}
int DBAtomicWriter::prepare(optional_yield y)
{
return parent_op.prepare(NULL); /* send dpp */
}
int DBAtomicWriter::process(bufferlist&& data, uint64_t offset)
{
total_data_size += data.length();
/* XXX: Optimize all bufferlist copies in this function */
/* copy head_data into meta. */
uint64_t head_size = store->getDB()->get_max_head_size();
unsigned head_len = 0;
uint64_t max_chunk_size = store->getDB()->get_max_chunk_size();
int excess_size = 0;
/* Accumulate tail_data till max_chunk_size or flush op */
bufferlist tail_data;
if (data.length() != 0) {
if (offset < head_size) {
/* XXX: handle case (if exists) where offset > 0 & < head_size */
head_len = std::min((uint64_t)data.length(),
head_size - offset);
bufferlist tmp;
data.begin(0).copy(head_len, tmp);
head_data.append(tmp);
parent_op.meta.data = &head_data;
if (head_len == data.length()) {
return 0;
}
/* Move offset by copy_len */
offset = head_len;
}
/* handle tail parts.
* First accumulate and write data into dbstore in its chunk_size
* parts
*/
if (!tail_part_size) { /* new tail part */
tail_part_offset = offset;
}
data.begin(head_len).copy(data.length() - head_len, tail_data);
tail_part_size += tail_data.length();
tail_part_data.append(tail_data);
if (tail_part_size < max_chunk_size) {
return 0;
} else {
int write_ofs = 0;
while (tail_part_size >= max_chunk_size) {
excess_size = tail_part_size - max_chunk_size;
bufferlist tmp;
tail_part_data.begin(write_ofs).copy(max_chunk_size, tmp);
/* write tail objects data */
int ret = parent_op.write_data(dpp, tmp, tail_part_offset);
if (ret < 0) {
return ret;
}
tail_part_size -= max_chunk_size;
write_ofs += max_chunk_size;
tail_part_offset += max_chunk_size;
}
/* reset tail parts or update if excess data */
if (excess_size > 0) { /* wrote max_chunk_size data */
tail_part_size = excess_size;
bufferlist tmp;
tail_part_data.begin(write_ofs).copy(excess_size, tmp);
tail_part_data = tmp;
} else {
tail_part_size = 0;
tail_part_data.clear();
tail_part_offset = 0;
}
}
} else {
if (tail_part_size == 0) {
return 0; /* nothing more to write */
}
/* flush watever tail data is present */
int ret = parent_op.write_data(dpp, tail_part_data, tail_part_offset);
if (ret < 0) {
return ret;
}
tail_part_size = 0;
tail_part_data.clear();
tail_part_offset = 0;
}
return 0;
}
int DBAtomicWriter::complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y)
{
parent_op.meta.mtime = mtime;
parent_op.meta.delete_at = delete_at;
parent_op.meta.if_match = if_match;
parent_op.meta.if_nomatch = if_nomatch;
parent_op.meta.user_data = user_data;
parent_op.meta.zones_trace = zones_trace;
parent_op.meta.category = RGWObjCategory::Main;
/* XXX: handle accounted size */
accounted_size = total_data_size;
int ret = parent_op.write_meta(dpp, total_data_size, accounted_size, attrs);
if (canceled) {
*canceled = parent_op.meta.canceled;
}
return ret;
}
std::unique_ptr<RGWRole> DBStore::get_role(std::string name,
std::string tenant,
std::string path,
std::string trust_policy,
std::string max_session_duration_str,
std::multimap<std::string,std::string> tags)
{
RGWRole* p = nullptr;
return std::unique_ptr<RGWRole>(p);
}
std::unique_ptr<RGWRole> DBStore::get_role(std::string id)
{
RGWRole* p = nullptr;
return std::unique_ptr<RGWRole>(p);
}
std::unique_ptr<RGWRole> DBStore::get_role(const RGWRoleInfo& info)
{
RGWRole* p = nullptr;
return std::unique_ptr<RGWRole>(p);
}
int DBStore::get_roles(const DoutPrefixProvider *dpp,
optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
vector<std::unique_ptr<RGWRole>>& roles)
{
return 0;
}
std::unique_ptr<RGWOIDCProvider> DBStore::get_oidc_provider()
{
RGWOIDCProvider* p = nullptr;
return std::unique_ptr<RGWOIDCProvider>(p);
}
int DBStore::get_oidc_providers(const DoutPrefixProvider *dpp,
const std::string& tenant,
vector<std::unique_ptr<RGWOIDCProvider>>& providers, optional_yield y)
{
return 0;
}
std::unique_ptr<Writer> DBStore::get_append_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
const std::string& unique_tag,
uint64_t position,
uint64_t *cur_accounted_size) {
return nullptr;
}
std::unique_ptr<Writer> DBStore::get_atomic_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t olh_epoch,
const std::string& unique_tag) {
return std::make_unique<DBAtomicWriter>(dpp, y, obj, this, owner,
ptail_placement_rule, olh_epoch, unique_tag);
}
const std::string& DBStore::get_compression_type(const rgw_placement_rule& rule) {
return zone.get_rgw_params().get_compression_type(rule);
}
bool DBStore::valid_placement(const rgw_placement_rule& rule)
{
// XXX: Till zonegroup, zone and storage-classes can be configured
// for dbstore return true
return true; //zone.get_rgw_params().valid_placement(rule);
}
std::unique_ptr<User> DBStore::get_user(const rgw_user &u)
{
return std::make_unique<DBUser>(this, u);
}
int DBStore::get_user_by_access_key(const DoutPrefixProvider *dpp, const std::string& key, optional_yield y, std::unique_ptr<User>* user)
{
RGWUserInfo uinfo;
User *u;
int ret = 0;
RGWObjVersionTracker objv_tracker;
ret = getDB()->get_user(dpp, string("access_key"), key, uinfo, nullptr,
&objv_tracker);
if (ret < 0)
return ret;
u = new DBUser(this, uinfo);
if (!u)
return -ENOMEM;
u->get_version_tracker() = objv_tracker;
user->reset(u);
return 0;
}
int DBStore::get_user_by_email(const DoutPrefixProvider *dpp, const std::string& email, optional_yield y, std::unique_ptr<User>* user)
{
RGWUserInfo uinfo;
User *u;
int ret = 0;
RGWObjVersionTracker objv_tracker;
ret = getDB()->get_user(dpp, string("email"), email, uinfo, nullptr,
&objv_tracker);
if (ret < 0)
return ret;
u = new DBUser(this, uinfo);
if (!u)
return -ENOMEM;
u->get_version_tracker() = objv_tracker;
user->reset(u);
return ret;
}
int DBStore::get_user_by_swift(const DoutPrefixProvider *dpp, const std::string& user_str, optional_yield y, std::unique_ptr<User>* user)
{
/* Swift keys and subusers are not supported for now */
return -ENOTSUP;
}
std::string DBStore::get_cluster_id(const DoutPrefixProvider* dpp, optional_yield y)
{
return "PLACEHOLDER"; // for instance unique identifier
}
std::unique_ptr<Object> DBStore::get_object(const rgw_obj_key& k)
{
return std::make_unique<DBObject>(this, k);
}
int DBStore::get_bucket(const DoutPrefixProvider *dpp, User* u, const rgw_bucket& b, std::unique_ptr<Bucket>* bucket, optional_yield y)
{
int ret;
Bucket* bp;
bp = new DBBucket(this, b, u);
ret = bp->load_bucket(dpp, y);
if (ret < 0) {
delete bp;
return ret;
}
bucket->reset(bp);
return 0;
}
int DBStore::get_bucket(User* u, const RGWBucketInfo& i, std::unique_ptr<Bucket>* bucket)
{
Bucket* bp;
bp = new DBBucket(this, i, u);
/* Don't need to fetch the bucket info, use the provided one */
bucket->reset(bp);
return 0;
}
int DBStore::get_bucket(const DoutPrefixProvider *dpp, User* u, const std::string& tenant, const std::string& name, std::unique_ptr<Bucket>* bucket, optional_yield y)
{
rgw_bucket b;
b.tenant = tenant;
b.name = name;
return get_bucket(dpp, u, b, bucket, y);
}
bool DBStore::is_meta_master()
{
return true;
}
int DBStore::forward_request_to_master(const DoutPrefixProvider *dpp, User* user, obj_version *objv,
bufferlist& in_data,
JSONParser *jp, req_info& info,
optional_yield y)
{
return 0;
}
int DBStore::forward_iam_request_to_master(const DoutPrefixProvider *dpp, const RGWAccessKey& key, obj_version* objv,
bufferlist& in_data,
RGWXMLDecoder::XMLParser* parser, req_info& info,
optional_yield y)
{
return 0;
}
std::string DBStore::zone_unique_id(uint64_t unique_num)
{
return "";
}
std::string DBStore::zone_unique_trans_id(const uint64_t unique_num)
{
return "";
}
int DBStore::get_zonegroup(const std::string& id, std::unique_ptr<ZoneGroup>* zg)
{
/* XXX: for now only one zonegroup supported */
ZoneGroup* group = new DBZoneGroup(this, std::make_unique<RGWZoneGroup>());
if (!group)
return -ENOMEM;
zg->reset(group);
return 0;
}
int DBStore::list_all_zones(const DoutPrefixProvider* dpp,
std::list<std::string>& zone_ids)
{
zone_ids.push_back(zone.get_id());
return 0;
}
int DBStore::cluster_stat(RGWClusterStat& stats)
{
return 0;
}
std::unique_ptr<Lifecycle> DBStore::get_lifecycle(void)
{
return std::make_unique<DBLifecycle>(this);
}
int DBLifecycle::get_entry(const std::string& oid, const std::string& marker,
std::unique_ptr<LCEntry>* entry)
{
return store->getDB()->get_entry(oid, marker, entry);
}
int DBLifecycle::get_next_entry(const std::string& oid, const std::string& marker,
std::unique_ptr<LCEntry>* entry)
{
return store->getDB()->get_next_entry(oid, marker, entry);
}
int DBLifecycle::set_entry(const std::string& oid, LCEntry& entry)
{
return store->getDB()->set_entry(oid, entry);
}
int DBLifecycle::list_entries(const std::string& oid, const std::string& marker,
uint32_t max_entries, vector<std::unique_ptr<LCEntry>>& entries)
{
return store->getDB()->list_entries(oid, marker, max_entries, entries);
}
int DBLifecycle::rm_entry(const std::string& oid, LCEntry& entry)
{
return store->getDB()->rm_entry(oid, entry);
}
int DBLifecycle::get_head(const std::string& oid, std::unique_ptr<LCHead>* head)
{
return store->getDB()->get_head(oid, head);
}
int DBLifecycle::put_head(const std::string& oid, LCHead& head)
{
return store->getDB()->put_head(oid, head);
}
std::unique_ptr<LCSerializer> DBLifecycle::get_serializer(const std::string& lock_name,
const std::string& oid,
const std::string& cookie)
{
return std::make_unique<LCDBSerializer>(store, oid, lock_name, cookie);
}
std::unique_ptr<Notification> DBStore::get_notification(
rgw::sal::Object* obj, rgw::sal::Object* src_obj, req_state* s,
rgw::notify::EventType event_type, optional_yield y,
const std::string* object_name)
{
return std::make_unique<DBNotification>(obj, src_obj, event_type);
}
std::unique_ptr<Notification> DBStore::get_notification(
const DoutPrefixProvider* dpp, rgw::sal::Object* obj,
rgw::sal::Object* src_obj,
rgw::notify::EventType event_type, rgw::sal::Bucket* _bucket,
std::string& _user_id, std::string& _user_tenant, std::string& _req_id,
optional_yield y)
{
return std::make_unique<DBNotification>(obj, src_obj, event_type);
}
RGWLC* DBStore::get_rgwlc(void) {
return lc;
}
int DBStore::log_usage(const DoutPrefixProvider *dpp, map<rgw_user_bucket, RGWUsageBatch>& usage_info, optional_yield y)
{
return 0;
}
int DBStore::log_op(const DoutPrefixProvider *dpp, string& oid, bufferlist& bl)
{
return 0;
}
int DBStore::register_to_service_map(const DoutPrefixProvider *dpp, const string& daemon_type,
const map<string, string>& meta)
{
return 0;
}
void DBStore::get_ratelimit(RGWRateLimitInfo& bucket_ratelimit, RGWRateLimitInfo& user_ratelimit, RGWRateLimitInfo& anon_ratelimit)
{
return;
}
void DBStore::get_quota(RGWQuota& quota)
{
// XXX: Not handled for the first pass
return;
}
int DBStore::set_buckets_enabled(const DoutPrefixProvider *dpp, vector<rgw_bucket>& buckets, bool enabled, optional_yield y)
{
int ret = 0;
vector<rgw_bucket>::iterator iter;
for (iter = buckets.begin(); iter != buckets.end(); ++iter) {
rgw_bucket& bucket = *iter;
if (enabled) {
ldpp_dout(dpp, 20) << "enabling bucket name=" << bucket.name << dendl;
} else {
ldpp_dout(dpp, 20) << "disabling bucket name=" << bucket.name << dendl;
}
RGWBucketInfo info;
map<string, bufferlist> attrs;
int r = getDB()->get_bucket_info(dpp, string("name"), "", info, &attrs,
nullptr, nullptr);
if (r < 0) {
ldpp_dout(dpp, 0) << "NOTICE: get_bucket_info on bucket=" << bucket.name << " returned err=" << r << ", skipping bucket" << dendl;
ret = r;
continue;
}
if (enabled) {
info.flags &= ~BUCKET_SUSPENDED;
} else {
info.flags |= BUCKET_SUSPENDED;
}
r = getDB()->update_bucket(dpp, "info", info, false, nullptr, &attrs, nullptr, &info.objv_tracker);
if (r < 0) {
ldpp_dout(dpp, 0) << "NOTICE: put_bucket_info on bucket=" << bucket.name << " returned err=" << r << ", skipping bucket" << dendl;
ret = r;
continue;
}
}
return ret;
}
int DBStore::get_sync_policy_handler(const DoutPrefixProvider *dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef *phandler,
optional_yield y)
{
return 0;
}
RGWDataSyncStatusManager* DBStore::get_data_sync_manager(const rgw_zone_id& source_zone)
{
return 0;
}
int DBStore::read_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool *is_truncated,
RGWUsageIter& usage_iter,
map<rgw_user_bucket, rgw_usage_log_entry>& usage)
{
return 0;
}
int DBStore::trim_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y)
{
return 0;
}
int DBStore::get_config_key_val(string name, bufferlist *bl)
{
return -ENOTSUP;
}
int DBStore::meta_list_keys_init(const DoutPrefixProvider *dpp, const string& section, const string& marker, void** phandle)
{
return 0;
}
int DBStore::meta_list_keys_next(const DoutPrefixProvider *dpp, void* handle, int max, list<string>& keys, bool* truncated)
{
return 0;
}
void DBStore::meta_list_keys_complete(void* handle)
{
return;
}
std::string DBStore::meta_get_marker(void* handle)
{
return "";
}
int DBStore::meta_remove(const DoutPrefixProvider *dpp, string& metadata_key, optional_yield y)
{
return 0;
}
int DBStore::initialize(CephContext *_cct, const DoutPrefixProvider *_dpp) {
int ret = 0;
cct = _cct;
dpp = _dpp;
lc = new RGWLC();
lc->initialize(cct, this);
if (use_lc_thread) {
ret = db->createLCTables(dpp);
lc->start_processor();
}
ret = db->createGC(dpp);
if (ret < 0) {
ldpp_dout(dpp, 0) <<"GC thread creation failed: ret = " << ret << dendl;
}
return ret;
}
int DBLuaManager::get_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, std::string& script)
{
return -ENOENT;
}
int DBLuaManager::put_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, const std::string& script)
{
return -ENOENT;
}
int DBLuaManager::del_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key)
{
return -ENOENT;
}
int DBLuaManager::add_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name)
{
return -ENOENT;
}
int DBLuaManager::remove_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name)
{
return -ENOENT;
}
int DBLuaManager::list_packages(const DoutPrefixProvider* dpp, optional_yield y, rgw::lua::packages_t& packages)
{
return -ENOENT;
}
} // namespace rgw::sal
extern "C" {
void *newDBStore(CephContext *cct)
{
rgw::sal::DBStore *driver = new rgw::sal::DBStore();
DBStoreManager *dbsm = new DBStoreManager(cct);
DB *db = dbsm->getDB();
if (!db) {
delete dbsm;
delete driver;
return nullptr;
}
driver->setDBStoreManager(dbsm);
driver->setDB(db);
db->set_driver((rgw::sal::Driver*)driver);
db->set_context(cct);
return driver;
}
}
| 58,908 | 28.191774 | 178 |
cc
|
null |
ceph-main/src/rgw/rgw_sal_dbstore.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) 2021 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include "rgw_sal_store.h"
#include "rgw_oidc_provider.h"
#include "rgw_role.h"
#include "rgw_lc.h"
#include "rgw_multi.h"
#include "driver/dbstore/common/dbstore.h"
#include "driver/dbstore/dbstore_mgr.h"
namespace rgw { namespace sal {
class DBStore;
class LCDBSerializer : public StoreLCSerializer {
public:
LCDBSerializer(DBStore* store, const std::string& oid, const std::string& lock_name, const std::string& cookie) {}
virtual int try_lock(const DoutPrefixProvider *dpp, utime_t dur, optional_yield y) override { return 0; }
virtual int unlock() override {
return 0;
}
};
class DBLifecycle : public StoreLifecycle {
DBStore* store;
public:
DBLifecycle(DBStore* _st) : store(_st) {}
using StoreLifecycle::get_entry;
virtual int get_entry(const std::string& oid, const std::string& marker, std::unique_ptr<LCEntry>* entry) override;
virtual int get_next_entry(const std::string& oid, const std::string& marker, std::unique_ptr<LCEntry>* entry) override;
virtual int set_entry(const std::string& oid, LCEntry& entry) override;
virtual int list_entries(const std::string& oid, const std::string& marker,
uint32_t max_entries,
std::vector<std::unique_ptr<LCEntry>>& entries) override;
virtual int rm_entry(const std::string& oid, LCEntry& entry) override;
virtual int get_head(const std::string& oid, std::unique_ptr<LCHead>* head) override;
virtual int put_head(const std::string& oid, LCHead& head) override;
virtual std::unique_ptr<LCSerializer> get_serializer(const std::string& lock_name,
const std::string& oid,
const std::string& cookie) override;
};
class DBNotification : public StoreNotification {
protected:
public:
DBNotification(Object* _obj, Object* _src_obj, rgw::notify::EventType _type)
: StoreNotification(_obj, _src_obj, _type) {}
~DBNotification() = default;
virtual int publish_reserve(const DoutPrefixProvider *dpp, RGWObjTags* obj_tags = nullptr) override { return 0;}
virtual int publish_commit(const DoutPrefixProvider* dpp, uint64_t size,
const ceph::real_time& mtime, const std::string& etag, const std::string& version) override { return 0; }
};
class DBUser : public StoreUser {
private:
DBStore *store;
public:
DBUser(DBStore *_st, const rgw_user& _u) : StoreUser(_u), store(_st) { }
DBUser(DBStore *_st, const RGWUserInfo& _i) : StoreUser(_i), store(_st) { }
DBUser(DBStore *_st) : store(_st) { }
DBUser(DBUser& _o) = default;
DBUser() {}
virtual std::unique_ptr<User> clone() override {
return std::unique_ptr<User>(new DBUser(*this));
}
int list_buckets(const DoutPrefixProvider *dpp, const std::string& marker, const std::string& end_marker,
uint64_t max, bool need_stats, BucketList& buckets, optional_yield y) override;
virtual int create_bucket(const DoutPrefixProvider* dpp,
const rgw_bucket& b,
const std::string& zonegroup_id,
rgw_placement_rule& placement_rule,
std::string& swift_ver_location,
const RGWQuotaInfo* pquota_info,
const RGWAccessControlPolicy& policy,
Attrs& attrs,
RGWBucketInfo& info,
obj_version& ep_objv,
bool exclusive,
bool obj_lock_enabled,
bool* existed,
req_info& req_info,
std::unique_ptr<Bucket>* bucket,
optional_yield y) override;
virtual int read_attrs(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int read_stats(const DoutPrefixProvider *dpp,
optional_yield y, RGWStorageStats* stats,
ceph::real_time *last_stats_sync = nullptr,
ceph::real_time *last_stats_update = nullptr) override;
virtual int read_stats_async(const DoutPrefixProvider *dpp, RGWGetUserStats_CB* cb) override;
virtual int complete_flush_stats(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y) override;
/* Placeholders */
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp, Attrs& new_attrs, optional_yield y) override;
virtual int load_user(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int store_user(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, RGWUserInfo* old_info = nullptr) override;
virtual int remove_user(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int verify_mfa(const std::string& mfa_str, bool* verified, const DoutPrefixProvider* dpp, optional_yield y) override;
friend class DBBucket;
};
class DBBucket : public StoreBucket {
private:
DBStore *store;
RGWAccessControlPolicy acls;
public:
DBBucket(DBStore *_st)
: store(_st),
acls() {
}
DBBucket(DBStore *_st, User* _u)
: StoreBucket(_u),
store(_st),
acls() {
}
DBBucket(DBStore *_st, const rgw_bucket& _b)
: StoreBucket(_b),
store(_st),
acls() {
}
DBBucket(DBStore *_st, const RGWBucketEnt& _e)
: StoreBucket(_e),
store(_st),
acls() {
}
DBBucket(DBStore *_st, const RGWBucketInfo& _i)
: StoreBucket(_i),
store(_st),
acls() {
}
DBBucket(DBStore *_st, const rgw_bucket& _b, User* _u)
: StoreBucket(_b, _u),
store(_st),
acls() {
}
DBBucket(DBStore *_st, const RGWBucketEnt& _e, User* _u)
: StoreBucket(_e, _u),
store(_st),
acls() {
}
DBBucket(DBStore *_st, const RGWBucketInfo& _i, User* _u)
: StoreBucket(_i, _u),
store(_st),
acls() {
}
~DBBucket() { }
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& k) override;
virtual int list(const DoutPrefixProvider *dpp, ListParams&, int, ListResults&, optional_yield y) override;
virtual int remove_bucket(const DoutPrefixProvider *dpp, bool delete_children, bool forward_to_master, req_info* req_info, optional_yield y) override;
virtual int remove_bucket_bypass_gc(int concurrent_max, bool
keep_index_consistent,
optional_yield y, const
DoutPrefixProvider *dpp) override;
virtual RGWAccessControlPolicy& get_acl(void) override { return acls; }
virtual int set_acl(const DoutPrefixProvider *dpp, RGWAccessControlPolicy& acl, optional_yield y) override;
virtual int load_bucket(const DoutPrefixProvider *dpp, optional_yield y, bool get_stats = false) override;
virtual int read_stats(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id,
std::string *bucket_ver, std::string *master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string *max_marker = nullptr,
bool *syncstopped = nullptr) override;
virtual int read_stats_async(const DoutPrefixProvider *dpp, const bucket_index_layout_generation& idx_layout, int shard_id, RGWGetBucketStats_CB* ctx) override;
virtual int sync_user_stats(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int update_container_stats(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int check_bucket_shards(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int chown(const DoutPrefixProvider *dpp, User& new_user, optional_yield y) override;
virtual int put_info(const DoutPrefixProvider *dpp, bool exclusive, ceph::real_time mtime, optional_yield y) override;
virtual bool is_owner(User* user) override;
virtual int check_empty(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int check_quota(const DoutPrefixProvider *dpp, RGWQuota& quota, uint64_t obj_size, optional_yield y, bool check_size_only = false) override;
virtual int merge_and_store_attrs(const DoutPrefixProvider *dpp, Attrs& attrs, optional_yield y) override;
virtual int try_refresh_info(const DoutPrefixProvider *dpp, ceph::real_time *pmtime, optional_yield y) override;
virtual int read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, uint32_t max_entries,
bool *is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y) override;
virtual int remove_objs_from_index(const DoutPrefixProvider *dpp, std::list<rgw_obj_index_key>& objs_to_unlink) override;
virtual int check_index(const DoutPrefixProvider *dpp, std::map<RGWObjCategory, RGWStorageStats>& existing_stats, std::map<RGWObjCategory, RGWStorageStats>& calculated_stats) override;
virtual int rebuild_index(const DoutPrefixProvider *dpp) override;
virtual int set_tag_timeout(const DoutPrefixProvider *dpp, uint64_t timeout) override;
virtual int purge_instance(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual std::unique_ptr<Bucket> clone() override {
return std::make_unique<DBBucket>(*this);
}
virtual std::unique_ptr<MultipartUpload> get_multipart_upload(
const std::string& oid, std::optional<std::string> upload_id,
ACLOwner owner={}, ceph::real_time mtime=ceph::real_clock::now()) override;
virtual int list_multiparts(const DoutPrefixProvider *dpp,
const std::string& prefix,
std::string& marker,
const std::string& delim,
const int& max_uploads,
std::vector<std::unique_ptr<MultipartUpload>>& uploads,
std::map<std::string, bool> *common_prefixes,
bool *is_truncated, optional_yield y) override;
virtual int abort_multiparts(const DoutPrefixProvider* dpp,
CephContext* cct, optional_yield y) override;
friend class DBStore;
};
class DBPlacementTier: public StorePlacementTier {
DBStore* store;
RGWZoneGroupPlacementTier tier;
public:
DBPlacementTier(DBStore* _store, const RGWZoneGroupPlacementTier& _tier) : store(_store), tier(_tier) {}
virtual ~DBPlacementTier() = default;
virtual const std::string& get_tier_type() { return tier.tier_type; }
virtual const std::string& get_storage_class() { return tier.storage_class; }
virtual bool retain_head_object() { return tier.retain_head_object; }
RGWZoneGroupPlacementTier& get_rt() { return tier; }
};
class DBZoneGroup : public StoreZoneGroup {
DBStore* store;
std::unique_ptr<RGWZoneGroup> group;
std::string empty;
public:
DBZoneGroup(DBStore* _store, std::unique_ptr<RGWZoneGroup> _group) : store(_store), group(std::move(_group)) {}
virtual ~DBZoneGroup() = default;
virtual const std::string& get_id() const override { return group->get_id(); };
virtual const std::string& get_name() const override { return group->get_name(); };
virtual int equals(const std::string& other_zonegroup) const override {
return group->equals(other_zonegroup);
};
/** Get the endpoint from zonegroup, or from master zone if not set */
virtual const std::string& get_endpoint() const override;
virtual bool placement_target_exists(std::string& target) const override;
virtual bool is_master_zonegroup() const override {
return group->is_master_zonegroup();
};
virtual const std::string& get_api_name() const override { return group->api_name; };
virtual int get_placement_target_names(std::set<std::string>& names) const override;
virtual const std::string& get_default_placement_name() const override {
return group->default_placement.name; };
virtual int get_hostnames(std::list<std::string>& names) const override {
names = group->hostnames;
return 0;
};
virtual int get_s3website_hostnames(std::list<std::string>& names) const override {
names = group->hostnames_s3website;
return 0;
};
virtual int get_zone_count() const override {
/* currently only 1 zone supported */
return 1;
}
virtual int get_placement_tier(const rgw_placement_rule& rule,
std::unique_ptr<PlacementTier>* tier) {
return -1;
}
virtual int get_zone_by_id(const std::string& id, std::unique_ptr<Zone>* zone) override {
return -1;
}
virtual int get_zone_by_name(const std::string& name, std::unique_ptr<Zone>* zone) override {
return -1;
}
virtual int list_zones(std::list<std::string>& zone_ids) override {
zone_ids.clear();
return 0;
}
virtual std::unique_ptr<ZoneGroup> clone() override {
std::unique_ptr<RGWZoneGroup>zg = std::make_unique<RGWZoneGroup>(*group.get());
return std::make_unique<DBZoneGroup>(store, std::move(zg));
}
};
class DBZone : public StoreZone {
protected:
DBStore* store;
RGWRealm *realm{nullptr};
DBZoneGroup *zonegroup{nullptr};
RGWZone *zone_public_config{nullptr}; /* external zone params, e.g., entrypoints, log flags, etc. */
RGWZoneParams *zone_params{nullptr}; /* internal zone params, e.g., rados pools */
RGWPeriod *current_period{nullptr};
public:
DBZone(DBStore* _store) : store(_store) {
realm = new RGWRealm();
zonegroup = new DBZoneGroup(store, std::make_unique<RGWZoneGroup>());
zone_public_config = new RGWZone();
zone_params = new RGWZoneParams();
current_period = new RGWPeriod();
// XXX: only default and STANDARD supported for now
RGWZonePlacementInfo info;
RGWZoneStorageClasses sc;
sc.set_storage_class("STANDARD", nullptr, nullptr);
info.storage_classes = sc;
zone_params->placement_pools["default"] = info;
}
~DBZone() {
delete realm;
delete zonegroup;
delete zone_public_config;
delete zone_params;
delete current_period;
}
virtual std::unique_ptr<Zone> clone() override {
return std::make_unique<DBZone>(store);
}
virtual ZoneGroup& get_zonegroup() override;
const RGWZoneParams& get_rgw_params();
virtual const std::string& get_id() override;
virtual const std::string& get_name() const override;
virtual bool is_writeable() override;
virtual bool get_redirect_endpoint(std::string* endpoint) override;
virtual bool has_zonegroup_api(const std::string& api) const override;
virtual const std::string& get_current_period_id() override;
virtual const RGWAccessKey& get_system_key() override;
virtual const std::string& get_realm_name() override;
virtual const std::string& get_realm_id() override;
virtual const std::string_view get_tier_type() override { return "rgw"; }
virtual RGWBucketSyncPolicyHandlerRef get_sync_policy_handler() override;
};
class DBLuaManager : public StoreLuaManager {
DBStore* store;
public:
DBLuaManager(DBStore* _s) : store(_s)
{
}
virtual ~DBLuaManager() = default;
/** Get a script named with the given key from the backing store */
virtual int get_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, std::string& script) override;
/** Put a script named with the given key to the backing store */
virtual int put_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, const std::string& script) override;
/** Delete a script named with the given key from the backing store */
virtual int del_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key) override;
/** Add a lua package */
virtual int add_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name) override;
/** Remove a lua package */
virtual int remove_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name) override;
/** List lua packages */
virtual int list_packages(const DoutPrefixProvider* dpp, optional_yield y, rgw::lua::packages_t& packages) override;
};
class DBOIDCProvider : public RGWOIDCProvider {
DBStore* store;
public:
DBOIDCProvider(DBStore* _store) : store(_store) {}
~DBOIDCProvider() = default;
virtual int store_url(const DoutPrefixProvider *dpp, const std::string& url, bool exclusive, optional_yield y) override { return 0; }
virtual int read_url(const DoutPrefixProvider *dpp, const std::string& url, const std::string& tenant, optional_yield y) override { return 0; }
virtual int delete_obj(const DoutPrefixProvider *dpp, optional_yield y) override { return 0;}
void encode(bufferlist& bl) const {
RGWOIDCProvider::encode(bl);
}
void decode(bufferlist::const_iterator& bl) {
RGWOIDCProvider::decode(bl);
}
};
/*
* For multipart upload, below is the process flow -
*
* MultipartUpload::Init - create head object of meta obj (src_obj_name + "." + upload_id)
* [ Meta object stores all the parts upload info]
* MultipartWriter::process - create all data/tail objects with obj_name same as
* meta obj (so that they can all be identified & deleted
* during abort)
* MultipartUpload::Abort - Just delete meta obj .. that will indirectly delete all the
* uploads associated with that upload id / meta obj so far.
* MultipartUpload::Complete - create head object of the original object (if not exists) &
* rename all data/tail objects to orig object name and update
* metadata of the orig object.
*/
class DBMultipartPart : public StoreMultipartPart {
protected:
RGWUploadPartInfo info; /* XXX: info contains manifest also which is not needed */
public:
DBMultipartPart() = default;
virtual ~DBMultipartPart() = default;
virtual RGWUploadPartInfo& get_info() { return info; }
virtual void set_info(const RGWUploadPartInfo& _info) { info = _info; }
virtual uint32_t get_num() { return info.num; }
virtual uint64_t get_size() { return info.accounted_size; }
virtual const std::string& get_etag() { return info.etag; }
virtual ceph::real_time& get_mtime() { return info.modified; }
};
class DBMPObj {
std::string oid; // object name
std::string upload_id;
std::string meta; // multipart meta object = <oid>.<upload_id>
public:
DBMPObj() {}
DBMPObj(const std::string& _oid, const std::string& _upload_id) {
init(_oid, _upload_id, _upload_id);
}
DBMPObj(const std::string& _oid, std::optional<std::string> _upload_id) {
if (_upload_id) {
init(_oid, *_upload_id, *_upload_id);
} else {
from_meta(_oid);
}
}
void init(const std::string& _oid, const std::string& _upload_id) {
init(_oid, _upload_id, _upload_id);
}
void init(const std::string& _oid, const std::string& _upload_id, const std::string& part_unique_str) {
if (_oid.empty()) {
clear();
return;
}
oid = _oid;
upload_id = _upload_id;
meta = oid + "." + upload_id;
}
const std::string& get_upload_id() const {
return upload_id;
}
const std::string& get_key() const {
return oid;
}
const std::string& get_meta() const { return meta; }
bool from_meta(const std::string& meta) {
int end_pos = meta.length();
int mid_pos = meta.rfind('.', end_pos - 1); // <key>.<upload_id>
if (mid_pos < 0)
return false;
oid = meta.substr(0, mid_pos);
upload_id = meta.substr(mid_pos + 1, end_pos - mid_pos - 1);
init(oid, upload_id, upload_id);
return true;
}
void clear() {
oid = "";
meta = "";
upload_id = "";
}
};
class DBMultipartUpload : public StoreMultipartUpload {
DBStore* store;
DBMPObj mp_obj;
ACLOwner owner;
ceph::real_time mtime;
rgw_placement_rule placement;
public:
DBMultipartUpload(DBStore* _store, Bucket* _bucket, const std::string& oid, std::optional<std::string> upload_id, ACLOwner _owner, ceph::real_time _mtime) : StoreMultipartUpload(_bucket), store(_store), mp_obj(oid, upload_id), owner(_owner), mtime(_mtime) {}
virtual ~DBMultipartUpload() = default;
virtual const std::string& get_meta() const { return mp_obj.get_meta(); }
virtual const std::string& get_key() const { return mp_obj.get_key(); }
virtual const std::string& get_upload_id() const { return mp_obj.get_upload_id(); }
virtual const ACLOwner& get_owner() const override { return owner; }
virtual ceph::real_time& get_mtime() { return mtime; }
virtual std::unique_ptr<rgw::sal::Object> get_meta_obj() override;
virtual int init(const DoutPrefixProvider* dpp, optional_yield y, ACLOwner& owner, rgw_placement_rule& dest_placement, rgw::sal::Attrs& attrs) override;
virtual int list_parts(const DoutPrefixProvider* dpp, CephContext* cct,
int num_parts, int marker,
int* next_marker, bool* truncated, optional_yield y,
bool assume_unsorted = false) override;
virtual int abort(const DoutPrefixProvider* dpp, CephContext* cct, optional_yield y) override;
virtual int complete(const DoutPrefixProvider* dpp,
optional_yield y, CephContext* cct,
std::map<int, std::string>& part_etags,
std::list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed,
RGWCompressionInfo& cs_info, off_t& ofs,
std::string& tag, ACLOwner& owner,
uint64_t olh_epoch,
rgw::sal::Object* target_obj) override;
virtual int get_info(const DoutPrefixProvider *dpp, optional_yield y, rgw_placement_rule** rule, rgw::sal::Attrs* attrs = nullptr) override;
virtual std::unique_ptr<Writer> get_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t part_num,
const std::string& part_num_str) override;
};
class DBObject : public StoreObject {
private:
DBStore* store;
RGWAccessControlPolicy acls;
public:
struct DBReadOp : public ReadOp {
private:
DBObject* source;
RGWObjectCtx* rctx;
DB::Object op_target;
DB::Object::Read parent_op;
public:
DBReadOp(DBObject *_source, RGWObjectCtx *_rctx);
virtual int prepare(optional_yield y, const DoutPrefixProvider* dpp) override;
/*
* Both `read` and `iterate` read up through index `end`
* *inclusive*. The number of bytes that could be returned is
* `end - ofs + 1`.
*/
virtual int read(int64_t ofs, int64_t end, bufferlist& bl,
optional_yield y,
const DoutPrefixProvider* dpp) override;
virtual int iterate(const DoutPrefixProvider* dpp, int64_t ofs,
int64_t end, RGWGetDataCB* cb,
optional_yield y) override;
virtual int get_attr(const DoutPrefixProvider* dpp, const char* name, bufferlist& dest, optional_yield y) override;
};
struct DBDeleteOp : public DeleteOp {
private:
DBObject* source;
DB::Object op_target;
DB::Object::Delete parent_op;
public:
DBDeleteOp(DBObject* _source);
virtual int delete_obj(const DoutPrefixProvider* dpp, optional_yield y) override;
};
DBObject() = default;
DBObject(DBStore *_st, const rgw_obj_key& _k)
: StoreObject(_k),
store(_st),
acls() {}
DBObject(DBStore *_st, const rgw_obj_key& _k, Bucket* _b)
: StoreObject(_k, _b),
store(_st),
acls() {}
DBObject(DBObject& _o) = default;
virtual int delete_object(const DoutPrefixProvider* dpp,
optional_yield y,
bool prevent_versioning = false) override;
virtual int copy_object(User* user,
req_info* info, const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object, rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket,
const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime, ceph::real_time* mtime,
const ceph::real_time* mod_ptr, const ceph::real_time* unmod_ptr,
bool high_precision_time,
const char* if_match, const char* if_nomatch,
AttrsMod attrs_mod, bool copy_if_newer, Attrs& attrs,
RGWObjCategory category, uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at,
std::string* version_id, std::string* tag, std::string* etag,
void (*progress_cb)(off_t, void *), void* progress_data,
const DoutPrefixProvider* dpp, optional_yield y) override;
virtual RGWAccessControlPolicy& get_acl(void) override { return acls; }
virtual int set_acl(const RGWAccessControlPolicy& acl) override { acls = acl; return 0; }
virtual int get_obj_state(const DoutPrefixProvider* dpp, RGWObjState **state, optional_yield y, bool follow_olh = true) override;
virtual int set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs, Attrs* delattrs, optional_yield y) override;
virtual int get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp, rgw_obj* target_obj = NULL) override;
virtual int modify_obj_attrs(const char* attr_name, bufferlist& attr_val, optional_yield y, const DoutPrefixProvider* dpp) override;
virtual int delete_obj_attrs(const DoutPrefixProvider* dpp, const char* attr_name, optional_yield y) override;
virtual bool is_expired() override;
virtual void gen_rand_obj_instance_name() override;
virtual std::unique_ptr<Object> clone() override {
return std::unique_ptr<Object>(new DBObject(*this));
}
virtual std::unique_ptr<MPSerializer> get_serializer(const DoutPrefixProvider *dpp,
const std::string& lock_name) override;
virtual int transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime,
uint64_t olh_epoch,
const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual bool placement_rules_match(rgw_placement_rule& r1, rgw_placement_rule& r2) override;
virtual int dump_obj_layout(const DoutPrefixProvider *dpp, optional_yield y, Formatter* f) override;
/* Swift versioning */
virtual int swift_versioning_restore(bool& restored,
const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y) override;
/* OPs */
virtual std::unique_ptr<ReadOp> get_read_op() override;
virtual std::unique_ptr<DeleteOp> get_delete_op() override;
/* OMAP */
virtual int omap_get_vals_by_keys(const DoutPrefixProvider *dpp, const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals) override;
virtual int omap_set_val_by_key(const DoutPrefixProvider *dpp, const std::string& key, bufferlist& val,
bool must_exist, optional_yield y) override;
virtual int chown(User& new_user, const DoutPrefixProvider* dpp, optional_yield y) override;
private:
int read_attrs(const DoutPrefixProvider* dpp, DB::Object::Read &read_op, optional_yield y, rgw_obj* target_obj = nullptr);
};
class MPDBSerializer : public StoreMPSerializer {
public:
MPDBSerializer(const DoutPrefixProvider *dpp, DBStore* store, DBObject* obj, const std::string& lock_name) {}
virtual int try_lock(const DoutPrefixProvider *dpp, utime_t dur, optional_yield y) override {return 0; }
virtual int unlock() override { return 0;}
};
class DBAtomicWriter : public StoreWriter {
protected:
rgw::sal::DBStore* store;
const rgw_user& owner;
const rgw_placement_rule *ptail_placement_rule;
uint64_t olh_epoch;
const std::string& unique_tag;
DBObject obj;
DB::Object op_target;
DB::Object::Write parent_op;
uint64_t total_data_size = 0; /* for total data being uploaded */
bufferlist head_data;
bufferlist tail_part_data;
uint64_t tail_part_offset;
uint64_t tail_part_size = 0; /* corresponds to each tail part being
written to dbstore */
public:
DBAtomicWriter(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
DBStore* _store,
const rgw_user& _owner,
const rgw_placement_rule *_ptail_placement_rule,
uint64_t _olh_epoch,
const std::string& _unique_tag);
~DBAtomicWriter() = default;
// prepare to start processing object data
virtual int prepare(optional_yield y) override;
// Process a bufferlist
virtual int process(bufferlist&& data, uint64_t offset) override;
// complete the operation and make its result visible to clients
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y) override;
};
class DBMultipartWriter : public StoreWriter {
protected:
rgw::sal::DBStore* store;
const rgw_user& owner;
const rgw_placement_rule *ptail_placement_rule;
uint64_t olh_epoch;
rgw::sal::Object* head_obj;
std::string upload_id;
int part_num;
std::string oid; /* object->name() + "." + "upload_id" + "." + part_num */
std::unique_ptr<rgw::sal::Object> meta_obj;
DB::Object op_target;
DB::Object::Write parent_op;
std::string part_num_str;
uint64_t total_data_size = 0; /* for total data being uploaded */
bufferlist head_data;
bufferlist tail_part_data;
uint64_t tail_part_offset;
uint64_t tail_part_size = 0; /* corresponds to each tail part being
written to dbstore */
public:
DBMultipartWriter(const DoutPrefixProvider *dpp,
optional_yield y, MultipartUpload* upload,
rgw::sal::Object* obj,
DBStore* _store,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t part_num, const std::string& part_num_str);
~DBMultipartWriter() = default;
// prepare to start processing object data
virtual int prepare(optional_yield y) override;
// Process a bufferlist
virtual int process(bufferlist&& data, uint64_t offset) override;
// complete the operation and make its result visible to clients
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y) override;
};
class DBStore : public StoreDriver {
private:
/* DBStoreManager is used in case multiple
* connections are needed one for each tenant.
*/
DBStoreManager *dbsm;
/* default db (single connection). If needed
* multiple db handles (for eg., one for each tenant),
* use dbsm->getDB(tenant) */
DB *db;
DBZone zone;
RGWSyncModuleInstanceRef sync_module;
RGWLC* lc;
CephContext *cct;
const DoutPrefixProvider *dpp;
bool use_lc_thread;
public:
DBStore(): dbsm(nullptr), zone(this), cct(nullptr), dpp(nullptr),
use_lc_thread(false) {}
~DBStore() { delete dbsm; }
DBStore& set_run_lc_thread(bool _use_lc_thread) {
use_lc_thread = _use_lc_thread;
return *this;
}
virtual int initialize(CephContext *cct, const DoutPrefixProvider *dpp) override;
virtual const std::string get_name() const override {
return "dbstore";
}
virtual std::unique_ptr<User> get_user(const rgw_user& u) override;
virtual int get_user_by_access_key(const DoutPrefixProvider *dpp, const std::string& key, optional_yield y, std::unique_ptr<User>* user) override;
virtual int get_user_by_email(const DoutPrefixProvider *dpp, const std::string& email, optional_yield y, std::unique_ptr<User>* user) override;
virtual int get_user_by_swift(const DoutPrefixProvider *dpp, const std::string& user_str, optional_yield y, std::unique_ptr<User>* user) override;
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& k) override;
virtual std::string get_cluster_id(const DoutPrefixProvider* dpp, optional_yield y);
virtual int get_bucket(const DoutPrefixProvider *dpp, User* u, const rgw_bucket& b, std::unique_ptr<Bucket>* bucket, optional_yield y) override;
virtual int get_bucket(User* u, const RGWBucketInfo& i, std::unique_ptr<Bucket>* bucket) override;
virtual int get_bucket(const DoutPrefixProvider *dpp, User* u, const std::string& tenant, const std::string&name, std::unique_ptr<Bucket>* bucket, optional_yield y) override;
virtual bool is_meta_master() override;
virtual int forward_request_to_master(const DoutPrefixProvider *dpp, User* user, obj_version* objv,
bufferlist& in_data, JSONParser *jp, req_info& info,
optional_yield y) override;
virtual int forward_iam_request_to_master(const DoutPrefixProvider *dpp, const RGWAccessKey& key, obj_version* objv,
bufferlist& in_data,
RGWXMLDecoder::XMLParser* parser, req_info& info,
optional_yield y) override;
virtual Zone* get_zone() { return &zone; }
virtual std::string zone_unique_id(uint64_t unique_num) override;
virtual std::string zone_unique_trans_id(const uint64_t unique_num) override;
virtual int get_zonegroup(const std::string& id, std::unique_ptr<ZoneGroup>* zonegroup) override;
virtual int list_all_zones(const DoutPrefixProvider* dpp, std::list<std::string>& zone_ids) override;
virtual int cluster_stat(RGWClusterStat& stats) override;
virtual std::unique_ptr<Lifecycle> get_lifecycle(void) override;
virtual std::unique_ptr<Notification> get_notification(
rgw::sal::Object* obj, rgw::sal::Object* src_obj, req_state* s,
rgw::notify::EventType event_type, optional_yield y, const std::string* object_name) override;
virtual std::unique_ptr<Notification> get_notification(
const DoutPrefixProvider* dpp, rgw::sal::Object* obj,
rgw::sal::Object* src_obj,
rgw::notify::EventType event_type, rgw::sal::Bucket* _bucket,
std::string& _user_id, std::string& _user_tenant, std::string& _req_id,
optional_yield y) override;
virtual RGWLC* get_rgwlc(void) override;
virtual RGWCoroutinesManagerRegistry* get_cr_registry() override { return NULL; }
virtual int log_usage(const DoutPrefixProvider *dpp, std::map<rgw_user_bucket, RGWUsageBatch>& usage_info, optional_yield y) override;
virtual int log_op(const DoutPrefixProvider *dpp, std::string& oid, bufferlist& bl) override;
virtual int register_to_service_map(const DoutPrefixProvider *dpp, const std::string& daemon_type,
const std::map<std::string, std::string>& meta) override;
virtual void get_ratelimit(RGWRateLimitInfo& bucket_ratelimit, RGWRateLimitInfo& user_ratelimit, RGWRateLimitInfo& anon_ratelimit) override;
virtual void get_quota(RGWQuota& quota) override;
virtual int set_buckets_enabled(const DoutPrefixProvider *dpp, std::vector<rgw_bucket>& buckets, bool enabled, optional_yield y) override;
virtual int get_sync_policy_handler(const DoutPrefixProvider *dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef *phandler,
optional_yield y) override;
virtual RGWDataSyncStatusManager* get_data_sync_manager(const rgw_zone_id& source_zone) override;
virtual void wakeup_meta_sync_shards(std::set<int>& shard_ids) override { return; }
virtual void wakeup_data_sync_shards(const DoutPrefixProvider *dpp,
const rgw_zone_id& source_zone,
boost::container::flat_map<
int,
boost::container::flat_set<rgw_data_notify_entry>>& shard_ids) override { return; }
virtual int clear_usage(const DoutPrefixProvider *dpp, optional_yield y) override { return 0; }
virtual int read_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool *is_truncated,
RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch, uint64_t end_epoch, optional_yield y) override;
virtual int get_config_key_val(std::string name, bufferlist* bl) override;
virtual int meta_list_keys_init(const DoutPrefixProvider *dpp, const std::string& section, const std::string& marker, void** phandle) override;
virtual int meta_list_keys_next(const DoutPrefixProvider *dpp, void* handle, int max, std::list<std::string>& keys, bool* truncated) override;
virtual void meta_list_keys_complete(void* handle) override;
virtual std::string meta_get_marker(void *handle) override;
virtual int meta_remove(const DoutPrefixProvider *dpp, std::string& metadata_key, optional_yield y) override;
virtual const RGWSyncModuleInstanceRef& get_sync_module() { return sync_module; }
virtual std::string get_host_id() { return ""; }
virtual std::unique_ptr<LuaManager> get_lua_manager() override;
virtual std::unique_ptr<RGWRole> get_role(std::string name,
std::string tenant,
std::string path="",
std::string trust_policy="",
std::string max_session_duration_str="",
std::multimap<std::string,std::string> tags={}) override;
virtual std::unique_ptr<RGWRole> get_role(std::string id) override;
virtual std::unique_ptr<RGWRole> get_role(const RGWRoleInfo& info) override;
virtual int get_roles(const DoutPrefixProvider *dpp,
optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
std::vector<std::unique_ptr<RGWRole>>& roles) override;
virtual std::unique_ptr<RGWOIDCProvider> get_oidc_provider() override;
virtual int get_oidc_providers(const DoutPrefixProvider *dpp,
const std::string& tenant,
std::vector<std::unique_ptr<RGWOIDCProvider>>& providers, optional_yield y) override;
virtual std::unique_ptr<Writer> get_append_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
const std::string& unique_tag,
uint64_t position,
uint64_t *cur_accounted_size) override;
virtual std::unique_ptr<Writer> get_atomic_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t olh_epoch,
const std::string& unique_tag) override;
virtual const std::string& get_compression_type(const rgw_placement_rule& rule) override;
virtual bool valid_placement(const rgw_placement_rule& rule) override;
virtual void finalize(void) override;
virtual CephContext *ctx(void) override {
return db->ctx();
}
virtual void register_admin_apis(RGWRESTMgr* mgr) override { };
/* Unique to DBStore */
void setDBStoreManager(DBStoreManager *stm) { dbsm = stm; }
DBStoreManager *getDBStoreManager(void) { return dbsm; }
void setDB(DB * st) { db = st; }
DB *getDB(void) { return db; }
DB *getDB(std::string tenant) { return dbsm->getDB(tenant, false); }
};
} } // namespace rgw::sal
| 41,175 | 44.198683 | 262 |
h
|
null |
ceph-main/src/rgw/rgw_sal_filter.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) 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.
*
*/
#include "rgw_sal_filter.h"
namespace rgw { namespace sal {
/* These are helpers for getting 'next' out of an object, handling nullptr */
static inline PlacementTier* nextPlacementTier(PlacementTier* t)
{
if (!t)
return nullptr;
return dynamic_cast<FilterPlacementTier*>(t)->get_next();
}
static inline User* nextUser(User* t)
{
if (!t)
return nullptr;
return dynamic_cast<FilterUser*>(t)->get_next();
}
static inline Bucket* nextBucket(Bucket* t)
{
if (!t)
return nullptr;
return dynamic_cast<FilterBucket*>(t)->get_next();
}
static inline Object* nextObject(Object* t)
{
if (!t)
return nullptr;
return dynamic_cast<FilterObject*>(t)->get_next();
}
int FilterZoneGroup::get_placement_tier(const rgw_placement_rule& rule,
std::unique_ptr<PlacementTier>* tier)
{
std::unique_ptr<PlacementTier> nt;
int ret;
ret = next->get_placement_tier(rule, &nt);
if (ret != 0)
return ret;
PlacementTier* t = new FilterPlacementTier(std::move(nt));
tier->reset(t);
return 0;
}
int FilterZoneGroup::get_zone_by_id(const std::string& id, std::unique_ptr<Zone>* zone)
{
std::unique_ptr<Zone> nz;
int ret = next->get_zone_by_id(id, &nz);
if (ret < 0)
return ret;
Zone *z = new FilterZone(std::move(nz));
zone->reset(z);
return 0;
}
int FilterZoneGroup::get_zone_by_name(const std::string& name, std::unique_ptr<Zone>* zone)
{
std::unique_ptr<Zone> nz;
int ret = next->get_zone_by_name(name, &nz);
if (ret < 0)
return ret;
Zone *z = new FilterZone(std::move(nz));
zone->reset(z);
return 0;
}
int FilterDriver::initialize(CephContext *cct, const DoutPrefixProvider *dpp)
{
zone = std::make_unique<FilterZone>(next->get_zone()->clone());
return 0;
}
const std::string FilterDriver::get_name() const
{
std::string name = "filter<" + next->get_name() + ">";
return name;
}
std::string FilterDriver::get_cluster_id(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->get_cluster_id(dpp, y);
}
std::unique_ptr<User> FilterDriver::get_user(const rgw_user &u)
{
std::unique_ptr<User> user = next->get_user(u);
return std::make_unique<FilterUser>(std::move(user));
}
int FilterDriver::get_user_by_access_key(const DoutPrefixProvider* dpp, const std::string& key, optional_yield y, std::unique_ptr<User>* user)
{
std::unique_ptr<User> nu;
int ret;
ret = next->get_user_by_access_key(dpp, key, y, &nu);
if (ret != 0)
return ret;
User* u = new FilterUser(std::move(nu));
user->reset(u);
return 0;
}
int FilterDriver::get_user_by_email(const DoutPrefixProvider* dpp, const std::string& email, optional_yield y, std::unique_ptr<User>* user)
{
std::unique_ptr<User> nu;
int ret;
ret = next->get_user_by_email(dpp, email, y, &nu);
if (ret != 0)
return ret;
User* u = new FilterUser(std::move(nu));
user->reset(u);
return 0;
}
int FilterDriver::get_user_by_swift(const DoutPrefixProvider* dpp, const std::string& user_str, optional_yield y, std::unique_ptr<User>* user)
{
std::unique_ptr<User> nu;
int ret;
ret = next->get_user_by_swift(dpp, user_str, y, &nu);
if (ret != 0)
return ret;
User* u = new FilterUser(std::move(nu));
user->reset(u);
return 0;
}
std::unique_ptr<Object> FilterDriver::get_object(const rgw_obj_key& k)
{
std::unique_ptr<Object> o = next->get_object(k);
return std::make_unique<FilterObject>(std::move(o));
}
int FilterDriver::get_bucket(const DoutPrefixProvider* dpp, User* u, const rgw_bucket& b, std::unique_ptr<Bucket>* bucket, optional_yield y)
{
std::unique_ptr<Bucket> nb;
int ret;
User* nu = nextUser(u);
ret = next->get_bucket(dpp, nu, b, &nb, y);
if (ret != 0)
return ret;
Bucket* fb = new FilterBucket(std::move(nb), u);
bucket->reset(fb);
return 0;
}
int FilterDriver::get_bucket(User* u, const RGWBucketInfo& i, std::unique_ptr<Bucket>* bucket)
{
std::unique_ptr<Bucket> nb;
int ret;
User* nu = nextUser(u);
ret = next->get_bucket(nu, i, &nb);
if (ret != 0)
return ret;
Bucket* fb = new FilterBucket(std::move(nb), u);
bucket->reset(fb);
return 0;
}
int FilterDriver::get_bucket(const DoutPrefixProvider* dpp, User* u, const std::string& tenant, const std::string& name, std::unique_ptr<Bucket>* bucket, optional_yield y)
{
std::unique_ptr<Bucket> nb;
int ret;
User* nu = nextUser(u);
ret = next->get_bucket(dpp, nu, tenant, name, &nb, y);
if (ret != 0)
return ret;
Bucket* fb = new FilterBucket(std::move(nb), u);
bucket->reset(fb);
return 0;
}
bool FilterDriver::is_meta_master()
{
return next->is_meta_master();
}
int FilterDriver::forward_request_to_master(const DoutPrefixProvider *dpp,
User* user, obj_version* objv,
bufferlist& in_data,
JSONParser* jp, req_info& info,
optional_yield y)
{
return next->forward_request_to_master(dpp, user, objv, in_data, jp, info, y);
}
int FilterDriver::forward_iam_request_to_master(const DoutPrefixProvider *dpp,
const RGWAccessKey& key,
obj_version* objv,
bufferlist& in_data,
RGWXMLDecoder::XMLParser* parser,
req_info& info,
optional_yield y)
{
return next->forward_iam_request_to_master(dpp, key, objv, in_data, parser, info, y);
}
std::string FilterDriver::zone_unique_id(uint64_t unique_num)
{
return next->zone_unique_id(unique_num);
}
std::string FilterDriver::zone_unique_trans_id(uint64_t unique_num)
{
return next->zone_unique_trans_id(unique_num);
}
int FilterDriver::get_zonegroup(const std::string& id,
std::unique_ptr<ZoneGroup>* zonegroup)
{
std::unique_ptr<ZoneGroup> ngz;
int ret;
ret = next->get_zonegroup(id, &ngz);
if (ret != 0)
return ret;
ZoneGroup* zg = new FilterZoneGroup(std::move(ngz));
zonegroup->reset(zg);
return 0;
}
int FilterDriver::cluster_stat(RGWClusterStat& stats)
{
return next->cluster_stat(stats);
}
std::unique_ptr<Lifecycle> FilterDriver::get_lifecycle(void)
{
std::unique_ptr<Lifecycle> lc = next->get_lifecycle();
return std::make_unique<FilterLifecycle>(std::move(lc));
}
std::unique_ptr<Notification> FilterDriver::get_notification(rgw::sal::Object* obj,
rgw::sal::Object* src_obj, req_state* s,
rgw::notify::EventType event_type, optional_yield y,
const std::string* object_name)
{
std::unique_ptr<Notification> n = next->get_notification(nextObject(obj),
nextObject(src_obj),
s, event_type, y,
object_name);
return std::make_unique<FilterNotification>(std::move(n));
}
std::unique_ptr<Notification> FilterDriver::get_notification(const DoutPrefixProvider* dpp,
rgw::sal::Object* obj, rgw::sal::Object* src_obj,
rgw::notify::EventType event_type,
rgw::sal::Bucket* _bucket, std::string& _user_id,
std::string& _user_tenant, std::string& _req_id,
optional_yield y)
{
std::unique_ptr<Notification> n = next->get_notification(dpp, nextObject(obj),
nextObject(src_obj),
event_type,
nextBucket(_bucket),
_user_id,
_user_tenant,
_req_id, y);
return std::make_unique<FilterNotification>(std::move(n));
}
RGWLC* FilterDriver::get_rgwlc()
{
return next->get_rgwlc();
}
RGWCoroutinesManagerRegistry* FilterDriver::get_cr_registry()
{
return next->get_cr_registry();
}
int FilterDriver::log_usage(const DoutPrefixProvider *dpp, std::map<rgw_user_bucket, RGWUsageBatch>& usage_info, optional_yield y)
{
return next->log_usage(dpp, usage_info, y);
}
int FilterDriver::log_op(const DoutPrefixProvider *dpp, std::string& oid, bufferlist& bl)
{
return next->log_op(dpp, oid, bl);
}
int FilterDriver::register_to_service_map(const DoutPrefixProvider *dpp,
const std::string& daemon_type,
const std::map<std::string, std::string>& meta)
{
return next->register_to_service_map(dpp, daemon_type, meta);
}
void FilterDriver::get_quota(RGWQuota& quota)
{
return next->get_quota(quota);
}
void FilterDriver::get_ratelimit(RGWRateLimitInfo& bucket_ratelimit,
RGWRateLimitInfo& user_ratelimit,
RGWRateLimitInfo& anon_ratelimit)
{
return next->get_ratelimit(bucket_ratelimit, user_ratelimit, anon_ratelimit);
}
int FilterDriver::set_buckets_enabled(const DoutPrefixProvider* dpp,
std::vector<rgw_bucket>& buckets, bool enabled, optional_yield y)
{
return next->set_buckets_enabled(dpp, buckets, enabled, y);
}
uint64_t FilterDriver::get_new_req_id()
{
return next->get_new_req_id();
}
int FilterDriver::get_sync_policy_handler(const DoutPrefixProvider* dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef* phandler,
optional_yield y)
{
return next->get_sync_policy_handler(dpp, zone, bucket, phandler, y);
}
RGWDataSyncStatusManager* FilterDriver::get_data_sync_manager(const rgw_zone_id& source_zone)
{
return next->get_data_sync_manager(source_zone);
}
void FilterDriver::wakeup_meta_sync_shards(std::set<int>& shard_ids)
{
return next->wakeup_meta_sync_shards(shard_ids);
}
void FilterDriver::wakeup_data_sync_shards(const DoutPrefixProvider *dpp,
const rgw_zone_id& source_zone,
boost::container::flat_map<int, boost::container::flat_set<rgw_data_notify_entry>>& shard_ids)
{
return next->wakeup_data_sync_shards(dpp, source_zone, shard_ids);
}
int FilterDriver::clear_usage(const DoutPrefixProvider *dpp, optional_yield y)
{
return next->clear_usage(dpp, y);
}
int FilterDriver::read_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage)
{
return next->read_all_usage(dpp, start_epoch, end_epoch, max_entries,
is_truncated, usage_iter, usage);
}
int FilterDriver::trim_all_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, optional_yield y)
{
return next->trim_all_usage(dpp, start_epoch, end_epoch, y);
}
int FilterDriver::get_config_key_val(std::string name, bufferlist* bl)
{
return next->get_config_key_val(name, bl);
}
int FilterDriver::meta_list_keys_init(const DoutPrefixProvider *dpp,
const std::string& section,
const std::string& marker, void** phandle)
{
return next->meta_list_keys_init(dpp, section, marker, phandle);
}
int FilterDriver::meta_list_keys_next(const DoutPrefixProvider *dpp, void* handle,
int max, std::list<std::string>& keys,
bool* truncated)
{
return next->meta_list_keys_next(dpp, handle, max, keys, truncated);
}
void FilterDriver::meta_list_keys_complete(void* handle)
{
next->meta_list_keys_complete(handle);
}
std::string FilterDriver::meta_get_marker(void* handle)
{
return next->meta_get_marker(handle);
}
int FilterDriver::meta_remove(const DoutPrefixProvider* dpp, std::string& metadata_key,
optional_yield y)
{
return next->meta_remove(dpp, metadata_key, y);
}
const RGWSyncModuleInstanceRef& FilterDriver::get_sync_module()
{
return next->get_sync_module();
}
std::unique_ptr<LuaManager> FilterDriver::get_lua_manager()
{
std::unique_ptr<LuaManager> nm = next->get_lua_manager();
return std::make_unique<FilterLuaManager>(std::move(nm));
}
std::unique_ptr<RGWRole> FilterDriver::get_role(std::string name,
std::string tenant,
std::string path,
std::string trust_policy,
std::string max_session_duration_str,
std::multimap<std::string,std::string> tags)
{
return next->get_role(name, tenant, path, trust_policy, max_session_duration_str, tags);
}
std::unique_ptr<RGWRole> FilterDriver::get_role(std::string id)
{
return next->get_role(id);
}
std::unique_ptr<RGWRole> FilterDriver::get_role(const RGWRoleInfo& info)
{
return next->get_role(info);
}
int FilterDriver::get_roles(const DoutPrefixProvider *dpp,
optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
std::vector<std::unique_ptr<RGWRole>>& roles)
{
return next->get_roles(dpp, y, path_prefix, tenant, roles);
}
std::unique_ptr<RGWOIDCProvider> FilterDriver::get_oidc_provider()
{
return next->get_oidc_provider();
}
int FilterDriver::get_oidc_providers(const DoutPrefixProvider *dpp,
const std::string& tenant,
std::vector<std::unique_ptr<RGWOIDCProvider>>& providers, optional_yield y)
{
return next->get_oidc_providers(dpp, tenant, providers, y);
}
std::unique_ptr<Writer> FilterDriver::get_append_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
const std::string& unique_tag,
uint64_t position,
uint64_t *cur_accounted_size)
{
std::unique_ptr<Writer> writer = next->get_append_writer(dpp, y, nextObject(obj),
owner, ptail_placement_rule,
unique_tag, position,
cur_accounted_size);
return std::make_unique<FilterWriter>(std::move(writer), obj);
}
std::unique_ptr<Writer> FilterDriver::get_atomic_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t olh_epoch,
const std::string& unique_tag)
{
std::unique_ptr<Writer> writer = next->get_atomic_writer(dpp, y, nextObject(obj),
owner, ptail_placement_rule,
olh_epoch, unique_tag);
return std::make_unique<FilterWriter>(std::move(writer), obj);
}
const std::string& FilterDriver::get_compression_type(const rgw_placement_rule& rule)
{
return next->get_compression_type(rule);
}
bool FilterDriver::valid_placement(const rgw_placement_rule& rule)
{
return next->valid_placement(rule);
}
void FilterDriver::finalize(void)
{
next->finalize();
}
CephContext* FilterDriver::ctx(void)
{
return next->ctx();
}
int FilterUser::list_buckets(const DoutPrefixProvider* dpp, const std::string& marker,
const std::string& end_marker, uint64_t max,
bool need_stats, BucketList &buckets, optional_yield y)
{
BucketList bl;
int ret;
buckets.clear();
ret = next->list_buckets(dpp, marker, end_marker, max, need_stats, bl, y);
if (ret < 0)
return ret;
buckets.set_truncated(bl.is_truncated());
for (auto& ent : bl.get_buckets()) {
buckets.add(std::make_unique<FilterBucket>(std::move(ent.second), this));
}
return 0;
}
int FilterUser::create_bucket(const DoutPrefixProvider* dpp,
const rgw_bucket& b,
const std::string& zonegroup_id,
rgw_placement_rule& placement_rule,
std::string& swift_ver_location,
const RGWQuotaInfo * pquota_info,
const RGWAccessControlPolicy& policy,
Attrs& attrs,
RGWBucketInfo& info,
obj_version& ep_objv,
bool exclusive,
bool obj_lock_enabled,
bool* existed,
req_info& req_info,
std::unique_ptr<Bucket>* bucket_out,
optional_yield y)
{
std::unique_ptr<Bucket> nb;
int ret;
ret = next->create_bucket(dpp, b, zonegroup_id, placement_rule, swift_ver_location, pquota_info, policy, attrs, info, ep_objv, exclusive, obj_lock_enabled, existed, req_info, &nb, y);
if (ret < 0)
return ret;
Bucket* fb = new FilterBucket(std::move(nb), this);
bucket_out->reset(fb);
return 0;
}
int FilterUser::read_attrs(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->read_attrs(dpp, y);
}
int FilterUser::merge_and_store_attrs(const DoutPrefixProvider* dpp,
Attrs& new_attrs, optional_yield y)
{
return next->merge_and_store_attrs(dpp, new_attrs, y);
}
int FilterUser::read_stats(const DoutPrefixProvider *dpp,
optional_yield y, RGWStorageStats* stats,
ceph::real_time* last_stats_sync,
ceph::real_time* last_stats_update)
{
return next->read_stats(dpp, y, stats, last_stats_sync, last_stats_update);
}
int FilterUser::read_stats_async(const DoutPrefixProvider *dpp, RGWGetUserStats_CB* cb)
{
return next->read_stats_async(dpp, cb);
}
int FilterUser::complete_flush_stats(const DoutPrefixProvider *dpp, optional_yield y)
{
return next->complete_flush_stats(dpp, y);
}
int FilterUser::read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage)
{
return next->read_usage(dpp, start_epoch, end_epoch, max_entries,
is_truncated, usage_iter, usage);
}
int FilterUser::trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, optional_yield y)
{
return next->trim_usage(dpp, start_epoch, end_epoch, y);
}
int FilterUser::load_user(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->load_user(dpp, y);
}
int FilterUser::store_user(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, RGWUserInfo* old_info)
{
return next->store_user(dpp, y, exclusive, old_info);
}
int FilterUser::remove_user(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->remove_user(dpp, y);
}
int FilterUser::verify_mfa(const std::string& mfa_str, bool* verified,
const DoutPrefixProvider* dpp, optional_yield y)
{
return next->verify_mfa(mfa_str, verified, dpp, y);
}
std::unique_ptr<Object> FilterBucket::get_object(const rgw_obj_key& k)
{
std::unique_ptr<Object> o = next->get_object(k);
return std::make_unique<FilterObject>(std::move(o), this);
}
int FilterBucket::list(const DoutPrefixProvider* dpp, ListParams& params, int max,
ListResults& results, optional_yield y)
{
return next->list(dpp, params, max, results, y);
}
int FilterBucket::remove_bucket(const DoutPrefixProvider* dpp,
bool delete_children,
bool forward_to_master,
req_info* req_info,
optional_yield y)
{
return next->remove_bucket(dpp, delete_children, forward_to_master, req_info, y);
}
int FilterBucket::remove_bucket_bypass_gc(int concurrent_max,
bool keep_index_consistent,
optional_yield y,
const DoutPrefixProvider *dpp)
{
return next->remove_bucket_bypass_gc(concurrent_max, keep_index_consistent, y, dpp);
}
int FilterBucket::set_acl(const DoutPrefixProvider* dpp,
RGWAccessControlPolicy &acl, optional_yield y)
{
return next->set_acl(dpp, acl, y);
}
int FilterBucket::load_bucket(const DoutPrefixProvider* dpp, optional_yield y,
bool get_stats)
{
return next->load_bucket(dpp, y, get_stats);
}
int FilterBucket::read_stats(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, std::string* bucket_ver,
std::string* master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string* max_marker, bool* syncstopped)
{
return next->read_stats(dpp, idx_layout, shard_id, bucket_ver, master_ver,
stats, max_marker, syncstopped);
}
int FilterBucket::read_stats_async(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, RGWGetBucketStats_CB* ctx)
{
return next->read_stats_async(dpp, idx_layout, shard_id, ctx);
}
int FilterBucket::sync_user_stats(const DoutPrefixProvider *dpp, optional_yield y)
{
return next->sync_user_stats(dpp, y);
}
int FilterBucket::update_container_stats(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->update_container_stats(dpp, y);
}
int FilterBucket::check_bucket_shards(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->check_bucket_shards(dpp, y);
}
int FilterBucket::chown(const DoutPrefixProvider* dpp, User& new_user, optional_yield y)
{
return next->chown(dpp, new_user, y);
}
int FilterBucket::put_info(const DoutPrefixProvider* dpp, bool exclusive,
ceph::real_time _mtime, optional_yield y)
{
return next->put_info(dpp, exclusive, _mtime, y);
}
bool FilterBucket::is_owner(User* user)
{
return next->is_owner(nextUser(user));
}
int FilterBucket::check_empty(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->check_empty(dpp, y);
}
int FilterBucket::check_quota(const DoutPrefixProvider *dpp, RGWQuota& quota,
uint64_t obj_size, optional_yield y,
bool check_size_only)
{
return next->check_quota(dpp, quota, obj_size, y, check_size_only);
}
int FilterBucket::merge_and_store_attrs(const DoutPrefixProvider* dpp,
Attrs& new_attrs, optional_yield y)
{
return next->merge_and_store_attrs(dpp, new_attrs, y);
}
int FilterBucket::try_refresh_info(const DoutPrefixProvider* dpp,
ceph::real_time* pmtime, optional_yield y)
{
return next->try_refresh_info(dpp, pmtime, y);
}
int FilterBucket::read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage)
{
return next->read_usage(dpp, start_epoch, end_epoch, max_entries,
is_truncated, usage_iter, usage);
}
int FilterBucket::trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, optional_yield y)
{
return next->trim_usage(dpp, start_epoch, end_epoch, y);
}
int FilterBucket::remove_objs_from_index(const DoutPrefixProvider *dpp,
std::list<rgw_obj_index_key>& objs_to_unlink)
{
return next->remove_objs_from_index(dpp, objs_to_unlink);
}
int FilterBucket::check_index(const DoutPrefixProvider *dpp,
std::map<RGWObjCategory, RGWStorageStats>& existing_stats,
std::map<RGWObjCategory, RGWStorageStats>& calculated_stats)
{
return next->check_index(dpp, existing_stats, calculated_stats);
}
int FilterBucket::rebuild_index(const DoutPrefixProvider *dpp)
{
return next->rebuild_index(dpp);
}
int FilterBucket::set_tag_timeout(const DoutPrefixProvider *dpp, uint64_t timeout)
{
return next->set_tag_timeout(dpp, timeout);
}
int FilterBucket::purge_instance(const DoutPrefixProvider* dpp, optional_yield y)
{
return next->purge_instance(dpp, y);
}
std::unique_ptr<MultipartUpload> FilterBucket::get_multipart_upload(
const std::string& oid,
std::optional<std::string> upload_id,
ACLOwner owner, ceph::real_time mtime)
{
std::unique_ptr<MultipartUpload> nmu =
next->get_multipart_upload(oid, upload_id, owner, mtime);
return std::make_unique<FilterMultipartUpload>(std::move(nmu), this);
}
int FilterBucket::list_multiparts(const DoutPrefixProvider *dpp,
const std::string& prefix,
std::string& marker,
const std::string& delim,
const int& max_uploads,
std::vector<std::unique_ptr<MultipartUpload>>& uploads,
std::map<std::string, bool> *common_prefixes,
bool *is_truncated, optional_yield y)
{
std::vector<std::unique_ptr<MultipartUpload>> nup;
int ret;
ret = next->list_multiparts(dpp, prefix, marker, delim, max_uploads, nup,
common_prefixes, is_truncated, y);
if (ret < 0)
return ret;
for (auto& ent : nup) {
uploads.emplace_back(std::make_unique<FilterMultipartUpload>(std::move(ent), this));
}
return 0;
}
int FilterBucket::abort_multiparts(const DoutPrefixProvider* dpp, CephContext* cct, optional_yield y)
{
return next->abort_multiparts(dpp, cct, y);
}
int FilterObject::delete_object(const DoutPrefixProvider* dpp,
optional_yield y,
bool prevent_versioning)
{
return next->delete_object(dpp, y, prevent_versioning);
}
int FilterObject::copy_object(User* user,
req_info* info,
const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object,
rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket,
const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime,
ceph::real_time* mtime,
const ceph::real_time* mod_ptr,
const ceph::real_time* unmod_ptr,
bool high_precision_time,
const char* if_match,
const char* if_nomatch,
AttrsMod attrs_mod,
bool copy_if_newer,
Attrs& attrs,
RGWObjCategory category,
uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at,
std::string* version_id,
std::string* tag,
std::string* etag,
void (*progress_cb)(off_t, void *),
void* progress_data,
const DoutPrefixProvider* dpp,
optional_yield y)
{
return next->copy_object(user, info, source_zone,
nextObject(dest_object),
nextBucket(dest_bucket),
nextBucket(src_bucket),
dest_placement, src_mtime, mtime,
mod_ptr, unmod_ptr, high_precision_time, if_match,
if_nomatch, attrs_mod, copy_if_newer, attrs,
category, olh_epoch, delete_at, version_id, tag,
etag, progress_cb, progress_data, dpp, y);
}
RGWAccessControlPolicy& FilterObject::get_acl()
{
return next->get_acl();
}
int FilterObject::get_obj_state(const DoutPrefixProvider* dpp, RGWObjState **pstate,
optional_yield y, bool follow_olh)
{
return next->get_obj_state(dpp, pstate, y, follow_olh);
}
int FilterObject::set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs,
Attrs* delattrs, optional_yield y)
{
return next->set_obj_attrs(dpp, setattrs, delattrs, y);
}
int FilterObject::get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp,
rgw_obj* target_obj)
{
return next->get_obj_attrs(y, dpp, target_obj);
}
int FilterObject::modify_obj_attrs(const char* attr_name, bufferlist& attr_val,
optional_yield y, const DoutPrefixProvider* dpp)
{
return next->modify_obj_attrs(attr_name, attr_val, y, dpp);
}
int FilterObject::delete_obj_attrs(const DoutPrefixProvider* dpp,
const char* attr_name, optional_yield y)
{
return next->delete_obj_attrs(dpp, attr_name, y);
}
bool FilterObject::is_expired()
{
return next->is_expired();
}
void FilterObject::gen_rand_obj_instance_name()
{
return next->gen_rand_obj_instance_name();
}
std::unique_ptr<MPSerializer> FilterObject::get_serializer(const DoutPrefixProvider *dpp,
const std::string& lock_name)
{
std::unique_ptr<MPSerializer> s = next->get_serializer(dpp, lock_name);
return std::make_unique<FilterMPSerializer>(std::move(s));
}
int FilterObject::transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime,
uint64_t olh_epoch,
const DoutPrefixProvider* dpp,
optional_yield y)
{
return next->transition(nextBucket(bucket), placement_rule, mtime, olh_epoch,
dpp, y);
}
int FilterObject::transition_to_cloud(Bucket* bucket,
rgw::sal::PlacementTier* tier,
rgw_bucket_dir_entry& o,
std::set<std::string>& cloud_targets,
CephContext* cct,
bool update_object,
const DoutPrefixProvider* dpp,
optional_yield y)
{
return next->transition_to_cloud(nextBucket(bucket), nextPlacementTier(tier),
o, cloud_targets, cct, update_object, dpp, y);
}
bool FilterObject::placement_rules_match(rgw_placement_rule& r1, rgw_placement_rule& r2)
{
return next->placement_rules_match(r1, r2);
}
int FilterObject::dump_obj_layout(const DoutPrefixProvider *dpp, optional_yield y,
Formatter* f)
{
return next->dump_obj_layout(dpp, y, f);
}
void FilterObject::set_bucket(Bucket* b)
{
bucket = b;
next->set_bucket(nextBucket(b));
};
int FilterObject::swift_versioning_restore(bool& restored,
const DoutPrefixProvider* dpp, optional_yield y)
{
return next->swift_versioning_restore(restored, dpp, y);
}
int FilterObject::swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y)
{
return next->swift_versioning_copy(dpp, y);
}
std::unique_ptr<Object::ReadOp> FilterObject::get_read_op()
{
std::unique_ptr<ReadOp> r = next->get_read_op();
return std::make_unique<FilterReadOp>(std::move(r));
}
std::unique_ptr<Object::DeleteOp> FilterObject::get_delete_op()
{
std::unique_ptr<DeleteOp> d = next->get_delete_op();
return std::make_unique<FilterDeleteOp>(std::move(d));
}
int FilterObject::get_torrent_info(const DoutPrefixProvider* dpp,
optional_yield y, bufferlist& bl)
{
return next->get_torrent_info(dpp, y, bl);
}
int FilterObject::omap_get_vals_by_keys(const DoutPrefixProvider *dpp,
const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals)
{
return next->omap_get_vals_by_keys(dpp, oid, keys, vals);
}
int FilterObject::omap_set_val_by_key(const DoutPrefixProvider *dpp,
const std::string& key, bufferlist& val,
bool must_exist, optional_yield y)
{
return next->omap_set_val_by_key(dpp, key, val, must_exist, y);
}
int FilterObject::chown(User& new_user, const DoutPrefixProvider* dpp, optional_yield y)
{
return next->chown(new_user, dpp, y);
}
int FilterObject::FilterReadOp::prepare(optional_yield y, const DoutPrefixProvider* dpp)
{
/* Copy params into next */
next->params = params;
return next->prepare(y, dpp);
}
int FilterObject::FilterReadOp::read(int64_t ofs, int64_t end, bufferlist& bl,
optional_yield y, const DoutPrefixProvider* dpp)
{
int ret = next->read(ofs, end, bl, y, dpp);
if (ret < 0)
return ret;
/* Copy params out of next */
params = next->params;
return ret;
}
int FilterObject::FilterReadOp::get_attr(const DoutPrefixProvider* dpp, const char* name, bufferlist& dest, optional_yield y)
{
return next->get_attr(dpp, name, dest, y);
}
int FilterObject::FilterReadOp::iterate(const DoutPrefixProvider* dpp, int64_t ofs,
int64_t end, RGWGetDataCB* cb, optional_yield y)
{
int ret = next->iterate(dpp, ofs, end, cb, y);
if (ret < 0)
return ret;
/* Copy params out of next */
params = next->params;
return ret;
}
int FilterObject::FilterDeleteOp::delete_obj(const DoutPrefixProvider* dpp,
optional_yield y)
{
/* Copy params into next */
next->params = params;
int ret = next->delete_obj(dpp, y);
/* Copy result back */
result = next->result;
return ret;
}
std::unique_ptr<rgw::sal::Object> FilterMultipartUpload::get_meta_obj()
{
std::unique_ptr<Object> no = next->get_meta_obj();
return std::make_unique<FilterObject>(std::move(no), bucket);
}
int FilterMultipartUpload::init(const DoutPrefixProvider *dpp, optional_yield y,
ACLOwner& owner, rgw_placement_rule& dest_placement,
rgw::sal::Attrs& attrs)
{
return next->init(dpp, y, owner, dest_placement, attrs);
}
int FilterMultipartUpload::list_parts(const DoutPrefixProvider *dpp, CephContext *cct,
int num_parts, int marker,
int *next_marker, bool *truncated, optional_yield y,
bool assume_unsorted)
{
int ret;
ret = next->list_parts(dpp, cct, num_parts, marker, next_marker, truncated, y,
assume_unsorted);
if (ret < 0)
return ret;
parts.clear();
for (auto& ent : next->get_parts()) {
parts.emplace(ent.first, std::make_unique<FilterMultipartPart>(std::move(ent.second)));
}
return 0;
}
int FilterMultipartUpload::abort(const DoutPrefixProvider *dpp, CephContext *cct, optional_yield y)
{
return next->abort(dpp, cct, y);
}
int FilterMultipartUpload::complete(const DoutPrefixProvider *dpp,
optional_yield y, CephContext* cct,
std::map<int, std::string>& part_etags,
std::list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed,
RGWCompressionInfo& cs_info, off_t& ofs,
std::string& tag, ACLOwner& owner,
uint64_t olh_epoch,
rgw::sal::Object* target_obj)
{
return next->complete(dpp, y, cct, part_etags, remove_objs, accounted_size,
compressed, cs_info, ofs, tag, owner, olh_epoch,
nextObject(target_obj));
}
int FilterMultipartUpload::get_info(const DoutPrefixProvider *dpp,
optional_yield y, rgw_placement_rule** rule,
rgw::sal::Attrs* attrs)
{
return next->get_info(dpp, y, rule, attrs);
}
std::unique_ptr<Writer> FilterMultipartUpload::get_writer(
const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t part_num,
const std::string& part_num_str)
{
std::unique_ptr<Writer> writer;
writer = next->get_writer(dpp, y, nextObject(obj), owner,
ptail_placement_rule, part_num, part_num_str);
return std::make_unique<FilterWriter>(std::move(writer), obj);
}
int FilterMPSerializer::try_lock(const DoutPrefixProvider *dpp, utime_t dur,
optional_yield y)
{
return next->try_lock(dpp, dur, y);
}
int FilterLCSerializer::try_lock(const DoutPrefixProvider *dpp, utime_t dur,
optional_yield y)
{
return next->try_lock(dpp, dur, y);
}
std::unique_ptr<Lifecycle::LCEntry> FilterLifecycle::get_entry()
{
std::unique_ptr<Lifecycle::LCEntry> e = next->get_entry();
return std::make_unique<FilterLCEntry>(std::move(e));
}
int FilterLifecycle::get_entry(const std::string& oid, const std::string& marker,
std::unique_ptr<LCEntry>* entry)
{
std::unique_ptr<LCEntry> ne;
int ret;
ret = next->get_entry(oid, marker, &ne);
if (ret < 0)
return ret;
LCEntry* e = new FilterLCEntry(std::move(ne));
entry->reset(e);
return 0;
}
int FilterLifecycle::get_next_entry(const std::string& oid, const std::string& marker,
std::unique_ptr<LCEntry>* entry)
{
std::unique_ptr<LCEntry> ne;
int ret;
ret = next->get_next_entry(oid, marker, &ne);
if (ret < 0)
return ret;
LCEntry* e = new FilterLCEntry(std::move(ne));
entry->reset(e);
return 0;
}
int FilterLifecycle::set_entry(const std::string& oid, LCEntry& entry)
{
return next->set_entry(oid, entry);
}
int FilterLifecycle::list_entries(const std::string& oid, const std::string& marker,
uint32_t max_entries,
std::vector<std::unique_ptr<LCEntry>>& entries)
{
std::vector<std::unique_ptr<LCEntry>> ne;
int ret;
ret = next->list_entries(oid, marker, max_entries, ne);
if (ret < 0)
return ret;
for (auto& ent : ne) {
entries.emplace_back(std::make_unique<FilterLCEntry>(std::move(ent)));
}
return 0;
}
int FilterLifecycle::rm_entry(const std::string& oid, LCEntry& entry)
{
return next->rm_entry(oid, entry);
}
int FilterLifecycle::get_head(const std::string& oid, std::unique_ptr<LCHead>* head)
{
std::unique_ptr<LCHead> nh;
int ret;
ret = next->get_head(oid, &nh);
if (ret < 0)
return ret;
LCHead* h = new FilterLCHead(std::move(nh));
head->reset(h);
return 0;
}
int FilterLifecycle::put_head(const std::string& oid, LCHead& head)
{
return next->put_head(oid, *(dynamic_cast<FilterLCHead&>(head).next.get()));
}
std::unique_ptr<LCSerializer> FilterLifecycle::get_serializer(
const std::string& lock_name,
const std::string& oid,
const std::string& cookie)
{
std::unique_ptr<LCSerializer> ns;
ns = next->get_serializer(lock_name, oid, cookie);
return std::make_unique<FilterLCSerializer>(std::move(ns));
}
int FilterNotification::publish_reserve(const DoutPrefixProvider *dpp,
RGWObjTags* obj_tags)
{
return next->publish_reserve(dpp, obj_tags);
}
int FilterNotification::publish_commit(const DoutPrefixProvider* dpp, uint64_t size,
const ceph::real_time& mtime, const
std::string& etag, const std::string& version)
{
return next->publish_commit(dpp, size, mtime, etag, version);
}
int FilterWriter::process(bufferlist&& data, uint64_t offset)
{
return next->process(std::move(data), offset);
}
int FilterWriter::complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y)
{
return next->complete(accounted_size, etag, mtime, set_mtime, attrs,
delete_at, if_match, if_nomatch, user_data, zones_trace,
canceled, y);
}
int FilterLuaManager::get_script(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& key, std::string& script)
{
return next->get_script(dpp, y, key, script);
}
int FilterLuaManager::put_script(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& key, const std::string& script)
{
return next->put_script(dpp, y, key, script);
}
int FilterLuaManager::del_script(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& key)
{
return next->del_script(dpp, y, key);
}
int FilterLuaManager::add_package(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& package_name)
{
return next->add_package(dpp, y, package_name);
}
int FilterLuaManager::remove_package(const DoutPrefixProvider* dpp, optional_yield y,
const std::string& package_name)
{
return next->remove_package(dpp, y, package_name);
}
int FilterLuaManager::list_packages(const DoutPrefixProvider* dpp, optional_yield y,
rgw::lua::packages_t& packages)
{
return next->list_packages(dpp, y, packages);
}
} } // namespace rgw::sal
extern "C" {
rgw::sal::Driver* newBaseFilter(rgw::sal::Driver* next)
{
rgw::sal::FilterDriver* driver = new rgw::sal::FilterDriver(next);
return driver;
}
}
| 37,991 | 27.142222 | 185 |
cc
|
null |
ceph-main/src/rgw/rgw_sal_filter.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 "rgw_sal.h"
#include "rgw_oidc_provider.h"
#include "rgw_role.h"
namespace rgw { namespace sal {
class FilterPlacementTier : public PlacementTier {
protected:
std::unique_ptr<PlacementTier> next;
public:
FilterPlacementTier(std::unique_ptr<PlacementTier> _next) : next(std::move(_next)) {}
virtual ~FilterPlacementTier() = default;
virtual const std::string& get_tier_type() override { return next->get_tier_type(); }
virtual const std::string& get_storage_class() override { return next->get_storage_class(); }
virtual bool retain_head_object() override { return next->retain_head_object(); }
/* Internal to Filters */
PlacementTier* get_next() { return next.get(); }
};
class FilterZoneGroup : public ZoneGroup {
protected:
std::unique_ptr<ZoneGroup> next;
public:
FilterZoneGroup(std::unique_ptr<ZoneGroup> _next) : next(std::move(_next)) {}
virtual ~FilterZoneGroup() = default;
virtual const std::string& get_id() const override
{ return next->get_id(); }
virtual const std::string& get_name() const override
{ return next->get_name(); }
virtual int equals(const std::string& other_zonegroup) const override
{ return next->equals(other_zonegroup); }
virtual const std::string& get_endpoint() const override
{ return next->get_endpoint(); }
virtual bool placement_target_exists(std::string& target) const override
{ return next->placement_target_exists(target); }
virtual bool is_master_zonegroup() const override
{ return next->is_master_zonegroup(); }
virtual const std::string& get_api_name() const override
{ return next->get_api_name(); }
virtual int get_placement_target_names(std::set<std::string>& names) const override
{ return next->get_placement_target_names(names); }
virtual const std::string& get_default_placement_name() const override
{ return next->get_default_placement_name(); }
virtual int get_hostnames(std::list<std::string>& names) const override
{ return next->get_hostnames(names); }
virtual int get_s3website_hostnames(std::list<std::string>& names) const override
{ return next->get_s3website_hostnames(names); }
virtual int get_zone_count() const override
{ return next->get_zone_count(); }
virtual int get_placement_tier(const rgw_placement_rule& rule, std::unique_ptr<PlacementTier>* tier) override;
virtual int get_zone_by_id(const std::string& id, std::unique_ptr<Zone>* zone) override;
virtual int get_zone_by_name(const std::string& name, std::unique_ptr<Zone>* zone) override;
virtual int list_zones(std::list<std::string>& zone_ids) override
{ return next->list_zones(zone_ids); }
virtual std::unique_ptr<ZoneGroup> clone() override {
std::unique_ptr<ZoneGroup> nzg = next->clone();
return std::make_unique<FilterZoneGroup>(std::move(nzg));
}
};
class FilterZone : public Zone {
protected:
std::unique_ptr<Zone> next;
private:
std::unique_ptr<ZoneGroup> group;
public:
FilterZone(std::unique_ptr<Zone> _next) : next(std::move(_next))
{
group = std::make_unique<FilterZoneGroup>(next->get_zonegroup().clone());
}
virtual ~FilterZone() = default;
virtual std::unique_ptr<Zone> clone() override {
std::unique_ptr<Zone> nz = next->clone();
return std::make_unique<FilterZone>(std::move(nz));
}
virtual ZoneGroup& get_zonegroup() override {
return *group.get();
}
virtual const std::string& get_id() override {
return next->get_id();
}
virtual const std::string& get_name() const override {
return next->get_name();
}
virtual bool is_writeable() override {
return next->is_writeable();
}
virtual bool get_redirect_endpoint(std::string* endpoint) override {
return next->get_redirect_endpoint(endpoint);
}
virtual bool has_zonegroup_api(const std::string& api) const override {
return next->has_zonegroup_api(api);
}
virtual const std::string& get_current_period_id() override {
return next->get_current_period_id();
}
virtual const RGWAccessKey& get_system_key() override {
return next->get_system_key();
}
virtual const std::string& get_realm_name() override {
return next->get_realm_name();
}
virtual const std::string& get_realm_id() override {
return next->get_realm_id();
}
virtual const std::string_view get_tier_type() override {
return next->get_tier_type();
}
virtual RGWBucketSyncPolicyHandlerRef get_sync_policy_handler() override {
return next->get_sync_policy_handler();
}
};
class FilterDriver : public Driver {
protected:
Driver* next;
private:
std::unique_ptr<FilterZone> zone;
public:
FilterDriver(Driver* _next) : next(_next) {}
virtual ~FilterDriver() = default;
virtual int initialize(CephContext *cct, const DoutPrefixProvider *dpp) override;
virtual const std::string get_name() const override;
virtual std::string get_cluster_id(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual std::unique_ptr<User> get_user(const rgw_user& u) override;
virtual int get_user_by_access_key(const DoutPrefixProvider* dpp, const
std::string& key, optional_yield y,
std::unique_ptr<User>* user) override;
virtual int get_user_by_email(const DoutPrefixProvider* dpp, const
std::string& email, optional_yield y,
std::unique_ptr<User>* user) override;
virtual int get_user_by_swift(const DoutPrefixProvider* dpp, const
std::string& user_str, optional_yield y,
std::unique_ptr<User>* user) override;
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& k) override;
virtual int get_bucket(User* u, const RGWBucketInfo& i,
std::unique_ptr<Bucket>* bucket) override;
virtual int get_bucket(const DoutPrefixProvider* dpp, User* u, const
rgw_bucket& b, std::unique_ptr<Bucket>* bucket,
optional_yield y) override;
virtual int get_bucket(const DoutPrefixProvider* dpp, User* u, const
std::string& tenant, const std::string& name,
std::unique_ptr<Bucket>* bucket, optional_yield y) override;
virtual bool is_meta_master() override;
virtual int forward_request_to_master(const DoutPrefixProvider *dpp, User* user,
obj_version* objv, bufferlist& in_data,
JSONParser* jp, req_info& info,
optional_yield y) override;
virtual int forward_iam_request_to_master(const DoutPrefixProvider *dpp,
const RGWAccessKey& key,
obj_version* objv,
bufferlist& in_data,
RGWXMLDecoder::XMLParser* parser,
req_info& info,
optional_yield y) override;
virtual Zone* get_zone() override { return zone.get(); }
virtual std::string zone_unique_id(uint64_t unique_num) override;
virtual std::string zone_unique_trans_id(const uint64_t unique_num) override;
virtual int get_zonegroup(const std::string& id, std::unique_ptr<ZoneGroup>* zonegroup) override;
virtual int list_all_zones(const DoutPrefixProvider* dpp, std::list<std::string>& zone_ids) override {
return next->list_all_zones(dpp, zone_ids);
}
virtual int cluster_stat(RGWClusterStat& stats) override;
virtual std::unique_ptr<Lifecycle> get_lifecycle(void) override;
virtual std::unique_ptr<Notification> get_notification(rgw::sal::Object* obj,
rgw::sal::Object* src_obj, struct req_state* s,
rgw::notify::EventType event_type, optional_yield y,
const std::string* object_name=nullptr) override;
virtual std::unique_ptr<Notification> get_notification(
const DoutPrefixProvider* dpp, rgw::sal::Object* obj, rgw::sal::Object* src_obj,
rgw::notify::EventType event_type, rgw::sal::Bucket* _bucket,
std::string& _user_id, std::string& _user_tenant,
std::string& _req_id, optional_yield y) override;
int read_topics(const std::string& tenant, rgw_pubsub_topics& topics, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) override {
return next->read_topics(tenant, topics, objv_tracker, y, dpp);
}
int write_topics(const std::string& tenant, const rgw_pubsub_topics& topics, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) override {
return next->write_topics(tenant, topics, objv_tracker, y, dpp);
}
int remove_topics(const std::string& tenant, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) override {
return next->remove_topics(tenant, objv_tracker, y, dpp);
}
virtual RGWLC* get_rgwlc(void) override;
virtual RGWCoroutinesManagerRegistry* get_cr_registry() override;
virtual int log_usage(const DoutPrefixProvider *dpp, std::map<rgw_user_bucket,
RGWUsageBatch>& usage_info, optional_yield y) override;
virtual int log_op(const DoutPrefixProvider *dpp, std::string& oid,
bufferlist& bl) override;
virtual int register_to_service_map(const DoutPrefixProvider *dpp, const
std::string& daemon_type,
const std::map<std::string,
std::string>& meta) override;
virtual void get_quota(RGWQuota& quota) override;
virtual void get_ratelimit(RGWRateLimitInfo& bucket_ratelimit,
RGWRateLimitInfo& user_ratelimit,
RGWRateLimitInfo& anon_ratelimit) override;
virtual int set_buckets_enabled(const DoutPrefixProvider* dpp,
std::vector<rgw_bucket>& buckets,
bool enabled, optional_yield y) override;
virtual uint64_t get_new_req_id() override;
virtual int get_sync_policy_handler(const DoutPrefixProvider* dpp,
std::optional<rgw_zone_id> zone,
std::optional<rgw_bucket> bucket,
RGWBucketSyncPolicyHandlerRef* phandler,
optional_yield y) override;
virtual RGWDataSyncStatusManager* get_data_sync_manager(const rgw_zone_id& source_zone) override;
virtual void wakeup_meta_sync_shards(std::set<int>& shard_ids) override;
virtual void wakeup_data_sync_shards(const DoutPrefixProvider *dpp,
const rgw_zone_id& source_zone,
boost::container::flat_map<int, boost::container::flat_set<rgw_data_notify_entry>>& shard_ids) override;
virtual int clear_usage(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int read_all_usage(const DoutPrefixProvider *dpp,
uint64_t start_epoch, uint64_t end_epoch,
uint32_t max_entries, bool* is_truncated,
RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_all_usage(const DoutPrefixProvider *dpp,
uint64_t start_epoch, uint64_t end_epoch, optional_yield y) override;
virtual int get_config_key_val(std::string name, bufferlist* bl) override;
virtual int meta_list_keys_init(const DoutPrefixProvider *dpp,
const std::string& section,
const std::string& marker,
void** phandle) override;
virtual int meta_list_keys_next(const DoutPrefixProvider *dpp, void* handle,
int max, std::list<std::string>& keys,
bool* truncated) override;
virtual void meta_list_keys_complete(void* handle) override;
virtual std::string meta_get_marker(void* handle) override;
virtual int meta_remove(const DoutPrefixProvider* dpp,
std::string& metadata_key, optional_yield y) override;
virtual const RGWSyncModuleInstanceRef& get_sync_module() override;
virtual std::string get_host_id() override { return next->get_host_id(); }
virtual std::unique_ptr<LuaManager> get_lua_manager() override;
virtual std::unique_ptr<RGWRole> get_role(std::string name,
std::string tenant,
std::string path="",
std::string trust_policy="",
std::string
max_session_duration_str="",
std::multimap<std::string,std::string> tags={}) override;
virtual std::unique_ptr<RGWRole> get_role(std::string id) override;
virtual std::unique_ptr<RGWRole> get_role(const RGWRoleInfo& info) override;
virtual int get_roles(const DoutPrefixProvider *dpp,
optional_yield y,
const std::string& path_prefix,
const std::string& tenant,
std::vector<std::unique_ptr<RGWRole>>& roles) override;
virtual std::unique_ptr<RGWOIDCProvider> get_oidc_provider() override;
virtual int get_oidc_providers(const DoutPrefixProvider *dpp,
const std::string& tenant,
std::vector<std::unique_ptr<RGWOIDCProvider>>&
providers, optional_yield y) override;
virtual std::unique_ptr<Writer> get_append_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule
*ptail_placement_rule,
const std::string& unique_tag,
uint64_t position,
uint64_t *cur_accounted_size) override;
virtual std::unique_ptr<Writer> get_atomic_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t olh_epoch,
const std::string& unique_tag) override;
virtual const std::string& get_compression_type(const rgw_placement_rule& rule) override;
virtual bool valid_placement(const rgw_placement_rule& rule) override;
virtual void finalize(void) override;
virtual CephContext* ctx(void) override;
virtual void register_admin_apis(RGWRESTMgr* mgr) override {
return next->register_admin_apis(mgr);
}
};
class FilterUser : public User {
protected:
std::unique_ptr<User> next;
public:
FilterUser(std::unique_ptr<User> _next) : next(std::move(_next)) {}
FilterUser(FilterUser& u) : next(u.next->clone()) {};
virtual ~FilterUser() = default;
virtual std::unique_ptr<User> clone() override {
return std::make_unique<FilterUser>(*this);
}
virtual int list_buckets(const DoutPrefixProvider* dpp,
const std::string& marker, const std::string& end_marker,
uint64_t max, bool need_stats, BucketList& buckets,
optional_yield y) override;
virtual int create_bucket(const DoutPrefixProvider* dpp,
const rgw_bucket& b,
const std::string& zonegroup_id,
rgw_placement_rule& placement_rule,
std::string& swift_ver_location,
const RGWQuotaInfo* pquota_info,
const RGWAccessControlPolicy& policy,
Attrs& attrs,
RGWBucketInfo& info,
obj_version& ep_objv,
bool exclusive,
bool obj_lock_enabled,
bool* existed,
req_info& req_info,
std::unique_ptr<Bucket>* bucket,
optional_yield y) override;
virtual std::string& get_display_name() override { return next->get_display_name(); }
virtual const std::string& get_tenant() override { return next->get_tenant(); }
virtual void set_tenant(std::string& _t) override { next->set_tenant(_t); }
virtual const std::string& get_ns() override { return next->get_ns(); }
virtual void set_ns(std::string& _ns) override { next->set_ns(_ns); }
virtual void clear_ns() override { next->clear_ns(); }
virtual const rgw_user& get_id() const override { return next->get_id(); }
virtual uint32_t get_type() const override { return next->get_type(); }
virtual int32_t get_max_buckets() const override { return next->get_max_buckets(); }
virtual void set_max_buckets(int32_t _max_buckets) override { return next->set_max_buckets(_max_buckets); }
virtual void set_info(RGWQuotaInfo& _quota) override { return next->set_info(_quota); }
virtual const RGWUserCaps& get_caps() const override { return next->get_caps(); }
virtual RGWObjVersionTracker& get_version_tracker() override {
return next->get_version_tracker();
}
virtual Attrs& get_attrs() override { return next->get_attrs(); }
virtual void set_attrs(Attrs& _attrs) override { next->set_attrs(_attrs); }
virtual bool empty() const override { return next->empty(); }
virtual int read_attrs(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp, Attrs&
new_attrs, optional_yield y) override;
virtual int read_stats(const DoutPrefixProvider *dpp,
optional_yield y, RGWStorageStats* stats,
ceph::real_time* last_stats_sync = nullptr,
ceph::real_time* last_stats_update = nullptr) override;
virtual int read_stats_async(const DoutPrefixProvider *dpp,
RGWGetUserStats_CB* cb) override;
virtual int complete_flush_stats(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket, rgw_usage_log_entry>& usage) override;
virtual int trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, optional_yield y) override;
virtual int load_user(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int store_user(const DoutPrefixProvider* dpp, optional_yield y, bool
exclusive, RGWUserInfo* old_info = nullptr) override;
virtual int remove_user(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int verify_mfa(const std::string& mfa_str, bool* verified,
const DoutPrefixProvider* dpp, optional_yield y) override;
RGWUserInfo& get_info() override { return next->get_info(); }
virtual void print(std::ostream& out) const override { return next->print(out); }
/* Internal to Filters */
User* get_next() { return next.get(); }
};
class FilterBucket : public Bucket {
protected:
std::unique_ptr<Bucket> next;
private:
User* user;
public:
FilterBucket(std::unique_ptr<Bucket> _next, User* _user) :
next(std::move(_next)), user(_user) {}
virtual ~FilterBucket() = default;
virtual std::unique_ptr<Object> get_object(const rgw_obj_key& key) override;
virtual int list(const DoutPrefixProvider* dpp, ListParams&, int,
ListResults&, optional_yield y) override;
virtual Attrs& get_attrs(void) override { return next->get_attrs(); }
virtual int set_attrs(Attrs a) override { return next->set_attrs(a); }
virtual int remove_bucket(const DoutPrefixProvider* dpp, bool delete_children,
bool forward_to_master, req_info* req_info,
optional_yield y) override;
virtual int remove_bucket_bypass_gc(int concurrent_max, bool
keep_index_consistent,
optional_yield y, const
DoutPrefixProvider *dpp) override;
virtual RGWAccessControlPolicy& get_acl(void) override { return next->get_acl(); }
virtual int set_acl(const DoutPrefixProvider* dpp, RGWAccessControlPolicy& acl,
optional_yield y) override;
virtual void set_owner(rgw::sal::User* _owner) override { next->set_owner(_owner); }
virtual int load_bucket(const DoutPrefixProvider* dpp, optional_yield y,
bool get_stats = false) override;
virtual int read_stats(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, std::string* bucket_ver, std::string* master_ver,
std::map<RGWObjCategory, RGWStorageStats>& stats,
std::string* max_marker = nullptr,
bool* syncstopped = nullptr) override;
virtual int read_stats_async(const DoutPrefixProvider *dpp,
const bucket_index_layout_generation& idx_layout,
int shard_id, RGWGetBucketStats_CB* ctx) override;
virtual int sync_user_stats(const DoutPrefixProvider *dpp, optional_yield y) override;
virtual int update_container_stats(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int check_bucket_shards(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int chown(const DoutPrefixProvider* dpp, User& new_user,
optional_yield y) override;
virtual int put_info(const DoutPrefixProvider* dpp, bool exclusive,
ceph::real_time mtime, optional_yield y) override;
virtual bool is_owner(User* user) override;
virtual User* get_owner(void) override { return user; }
virtual ACLOwner get_acl_owner(void) override { return next->get_acl_owner(); }
virtual int check_empty(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int check_quota(const DoutPrefixProvider *dpp, RGWQuota& quota,
uint64_t obj_size, optional_yield y,
bool check_size_only = false) override;
virtual int merge_and_store_attrs(const DoutPrefixProvider* dpp,
Attrs& new_attrs, optional_yield y) override;
virtual int try_refresh_info(const DoutPrefixProvider* dpp,
ceph::real_time* pmtime, optional_yield y) override;
virtual int read_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, uint32_t max_entries,
bool* is_truncated, RGWUsageIter& usage_iter,
std::map<rgw_user_bucket,
rgw_usage_log_entry>& usage) override;
virtual int trim_usage(const DoutPrefixProvider *dpp, uint64_t start_epoch,
uint64_t end_epoch, optional_yield y) override;
virtual int remove_objs_from_index(const DoutPrefixProvider *dpp,
std::list<rgw_obj_index_key>&
objs_to_unlink) override;
virtual int check_index(const DoutPrefixProvider *dpp,
std::map<RGWObjCategory, RGWStorageStats>&
existing_stats,
std::map<RGWObjCategory, RGWStorageStats>&
calculated_stats) override;
virtual int rebuild_index(const DoutPrefixProvider *dpp) override;
virtual int set_tag_timeout(const DoutPrefixProvider *dpp, uint64_t timeout) override;
virtual int purge_instance(const DoutPrefixProvider* dpp, optional_yield y) override;
virtual void set_count(uint64_t _count) override { return next->set_count(_count); }
virtual void set_size(uint64_t _size) override { return next->set_size(_size); }
virtual bool empty() const override { return next->empty(); }
virtual const std::string& get_name() const override { return next->get_name(); }
virtual const std::string& get_tenant() const override { return next->get_tenant(); }
virtual const std::string& get_marker() const override { return next->get_marker(); }
virtual const std::string& get_bucket_id() const override { return next->get_bucket_id(); }
virtual size_t get_size() const override { return next->get_size(); }
virtual size_t get_size_rounded() const override { return next->get_size_rounded(); }
virtual uint64_t get_count() const override { return next->get_count(); }
virtual rgw_placement_rule& get_placement_rule() override { return next->get_placement_rule(); }
virtual ceph::real_time& get_creation_time() override { return next->get_creation_time(); }
virtual ceph::real_time& get_modification_time() override { return next->get_modification_time(); }
virtual obj_version& get_version() override { return next->get_version(); }
virtual void set_version(obj_version &ver) override { next->set_version(ver); }
virtual bool versioned() override { return next->versioned(); }
virtual bool versioning_enabled() override { return next->versioning_enabled(); }
virtual std::unique_ptr<Bucket> clone() override {
std::unique_ptr<Bucket> nb = next->clone();
return std::make_unique<FilterBucket>(std::move(nb), user);
}
virtual std::unique_ptr<MultipartUpload> get_multipart_upload(
const std::string& oid,
std::optional<std::string> upload_id=std::nullopt,
ACLOwner owner={}, ceph::real_time mtime=real_clock::now()) override;
virtual int list_multiparts(const DoutPrefixProvider *dpp,
const std::string& prefix,
std::string& marker,
const std::string& delim,
const int& max_uploads,
std::vector<std::unique_ptr<MultipartUpload>>& uploads,
std::map<std::string, bool> *common_prefixes,
bool *is_truncated, optional_yield y) override;
virtual int abort_multiparts(const DoutPrefixProvider* dpp,
CephContext* cct, optional_yield y) override;
int read_topics(rgw_pubsub_bucket_topics& notifications, RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) override {
return next->read_topics(notifications, objv_tracker, y, dpp);
}
int write_topics(const rgw_pubsub_bucket_topics& notifications, RGWObjVersionTracker* obj_tracker,
optional_yield y, const DoutPrefixProvider *dpp) override {
return next->write_topics(notifications, obj_tracker, y, dpp);
}
int remove_topics(RGWObjVersionTracker* objv_tracker,
optional_yield y, const DoutPrefixProvider *dpp) override {
return next->remove_topics(objv_tracker, y, dpp);
}
virtual rgw_bucket& get_key() override { return next->get_key(); }
virtual RGWBucketInfo& get_info() override { return next->get_info(); }
virtual void print(std::ostream& out) const override { return next->print(out); }
virtual bool operator==(const Bucket& b) const override { return next->operator==(b); }
virtual bool operator!=(const Bucket& b) const override { return next->operator!=(b); }
friend class BucketList;
/* Internal to Filters */
Bucket* get_next() { return next.get(); }
};
class FilterObject : public Object {
protected:
std::unique_ptr<Object> next;
private:
Bucket* bucket{nullptr};
public:
struct FilterReadOp : ReadOp {
std::unique_ptr<ReadOp> next;
FilterReadOp(std::unique_ptr<ReadOp> _next) : next(std::move(_next)) {}
virtual ~FilterReadOp() = default;
virtual int prepare(optional_yield y, const DoutPrefixProvider* dpp) override;
virtual int read(int64_t ofs, int64_t end, bufferlist& bl, optional_yield y,
const DoutPrefixProvider* dpp) override;
virtual int iterate(const DoutPrefixProvider* dpp, int64_t ofs, int64_t end,
RGWGetDataCB* cb, optional_yield y) override;
virtual int get_attr(const DoutPrefixProvider* dpp, const char* name,
bufferlist& dest, optional_yield y) override;
};
struct FilterDeleteOp : DeleteOp {
std::unique_ptr<DeleteOp> next;
FilterDeleteOp(std::unique_ptr<DeleteOp> _next) : next(std::move(_next)) {}
virtual ~FilterDeleteOp() = default;
virtual int delete_obj(const DoutPrefixProvider* dpp, optional_yield y) override;
};
FilterObject(std::unique_ptr<Object> _next) : next(std::move(_next)) {}
FilterObject(std::unique_ptr<Object> _next, Bucket* _bucket) :
next(std::move(_next)), bucket(_bucket) {}
FilterObject(FilterObject& _o) {
next = _o.next->clone();
bucket = _o.bucket;
}
virtual ~FilterObject() = default;
virtual int delete_object(const DoutPrefixProvider* dpp,
optional_yield y,
bool prevent_versioning = false) override;
virtual int copy_object(User* user,
req_info* info, const rgw_zone_id& source_zone,
rgw::sal::Object* dest_object, rgw::sal::Bucket* dest_bucket,
rgw::sal::Bucket* src_bucket,
const rgw_placement_rule& dest_placement,
ceph::real_time* src_mtime, ceph::real_time* mtime,
const ceph::real_time* mod_ptr, const ceph::real_time* unmod_ptr,
bool high_precision_time,
const char* if_match, const char* if_nomatch,
AttrsMod attrs_mod, bool copy_if_newer, Attrs& attrs,
RGWObjCategory category, uint64_t olh_epoch,
boost::optional<ceph::real_time> delete_at,
std::string* version_id, std::string* tag, std::string* etag,
void (*progress_cb)(off_t, void *), void* progress_data,
const DoutPrefixProvider* dpp, optional_yield y) override;
virtual RGWAccessControlPolicy& get_acl(void) override;
virtual int set_acl(const RGWAccessControlPolicy& acl) override { return next->set_acl(acl); }
virtual void set_atomic() override { return next->set_atomic(); }
virtual bool is_atomic() override { return next->is_atomic(); }
virtual void set_prefetch_data() override { return next->set_prefetch_data(); }
virtual bool is_prefetch_data() override { return next->is_prefetch_data(); }
virtual void set_compressed() override { return next->set_compressed(); }
virtual bool is_compressed() override { return next->is_compressed(); }
virtual void invalidate() override { return next->invalidate(); }
virtual bool empty() const override { return next->empty(); }
virtual const std::string &get_name() const override { return next->get_name(); }
virtual int get_obj_state(const DoutPrefixProvider* dpp, RGWObjState **state,
optional_yield y, bool follow_olh = true) override;
virtual void set_obj_state(RGWObjState& _state) override { return next->set_obj_state(_state); }
virtual int set_obj_attrs(const DoutPrefixProvider* dpp, Attrs* setattrs,
Attrs* delattrs, optional_yield y) override;
virtual int get_obj_attrs(optional_yield y, const DoutPrefixProvider* dpp,
rgw_obj* target_obj = NULL) override;
virtual int modify_obj_attrs(const char* attr_name, bufferlist& attr_val,
optional_yield y, const DoutPrefixProvider* dpp) override;
virtual int delete_obj_attrs(const DoutPrefixProvider* dpp, const char* attr_name,
optional_yield y) override;
virtual bool is_expired() override;
virtual void gen_rand_obj_instance_name() override;
virtual std::unique_ptr<MPSerializer> get_serializer(const DoutPrefixProvider *dpp,
const std::string& lock_name) override;
virtual int transition(Bucket* bucket,
const rgw_placement_rule& placement_rule,
const real_time& mtime,
uint64_t olh_epoch,
const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual int transition_to_cloud(Bucket* bucket,
rgw::sal::PlacementTier* tier,
rgw_bucket_dir_entry& o,
std::set<std::string>& cloud_targets,
CephContext* cct,
bool update_object,
const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual bool placement_rules_match(rgw_placement_rule& r1, rgw_placement_rule& r2) override;
virtual int dump_obj_layout(const DoutPrefixProvider *dpp, optional_yield y,
Formatter* f) override;
virtual Attrs& get_attrs(void) override { return next->get_attrs(); };
virtual const Attrs& get_attrs(void) const override { return next->get_attrs(); };
virtual int set_attrs(Attrs a) override { return next->set_attrs(a); };
virtual bool has_attrs(void) override { return next->has_attrs(); };
virtual ceph::real_time get_mtime(void) const override { return next->get_mtime(); };
virtual uint64_t get_obj_size(void) const override { return next->get_obj_size(); };
virtual Bucket* get_bucket(void) const override { return bucket; };
virtual void set_bucket(Bucket* b) override;
virtual std::string get_hash_source(void) override { return next->get_hash_source(); };
virtual void set_hash_source(std::string s) override { return next->set_hash_source(s); };
virtual std::string get_oid(void) const override { return next->get_oid(); };
virtual bool get_delete_marker(void) override { return next->get_delete_marker(); };
virtual bool get_in_extra_data(void) override { return next->get_in_extra_data(); };
virtual void set_in_extra_data(bool i) override { return next->set_in_extra_data(i); };
int range_to_ofs(uint64_t obj_size, int64_t &ofs, int64_t &end) {
return next->range_to_ofs(obj_size, ofs, end);
};
virtual void set_obj_size(uint64_t s) override { return next->set_obj_size(s); };
virtual void set_name(const std::string& n) override { return next->set_name(n); };
virtual void set_key(const rgw_obj_key& k) override { return next->set_key(k); };
virtual rgw_obj get_obj(void) const override { return next->get_obj(); };
virtual rgw_obj_key& get_key() override { return next->get_key(); }
virtual void set_instance(const std::string &i) override { return next->set_instance(i); }
virtual const std::string &get_instance() const override { return next->get_instance(); }
virtual bool have_instance(void) override { return next->have_instance(); }
virtual void clear_instance() override { return next->clear_instance(); }
virtual int swift_versioning_restore(bool& restored, /* out */
const DoutPrefixProvider* dpp, optional_yield y) override;
virtual int swift_versioning_copy(const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual std::unique_ptr<ReadOp> get_read_op() override;
virtual std::unique_ptr<DeleteOp> get_delete_op() override;
virtual int get_torrent_info(const DoutPrefixProvider* dpp,
optional_yield y, bufferlist& bl) override;
virtual int omap_get_vals_by_keys(const DoutPrefixProvider *dpp,
const std::string& oid,
const std::set<std::string>& keys,
Attrs* vals) override;
virtual int omap_set_val_by_key(const DoutPrefixProvider *dpp,
const std::string& key, bufferlist& val,
bool must_exist, optional_yield y) override;
virtual int chown(User& new_user, const DoutPrefixProvider* dpp,
optional_yield y) override;
virtual std::unique_ptr<Object> clone() override {
return std::make_unique<FilterObject>(*this);
}
virtual void print(std::ostream& out) const override { return next->print(out); }
/* Internal to Filters */
Object* get_next() { return next.get(); }
};
class FilterMultipartPart : public MultipartPart {
protected:
std::unique_ptr<MultipartPart> next;
public:
FilterMultipartPart(std::unique_ptr<MultipartPart> _next) : next(std::move(_next)) {}
virtual ~FilterMultipartPart() = default;
virtual uint32_t get_num() override { return next->get_num(); }
virtual uint64_t get_size() override { return next->get_size(); }
virtual const std::string& get_etag() override { return next->get_etag(); }
virtual ceph::real_time& get_mtime() override { return next->get_mtime(); }
};
class FilterMultipartUpload : public MultipartUpload {
protected:
std::unique_ptr<MultipartUpload> next;
Bucket* bucket;
std::map<uint32_t, std::unique_ptr<MultipartPart>> parts;
public:
FilterMultipartUpload(std::unique_ptr<MultipartUpload> _next, Bucket* _b) :
next(std::move(_next)), bucket(_b) {}
virtual ~FilterMultipartUpload() = default;
virtual const std::string& get_meta() const override { return next->get_meta(); }
virtual const std::string& get_key() const override { return next->get_key(); }
virtual const std::string& get_upload_id() const override { return next->get_upload_id(); }
virtual const ACLOwner& get_owner() const override { return next->get_owner(); }
virtual ceph::real_time& get_mtime() override { return next->get_mtime(); }
virtual std::map<uint32_t, std::unique_ptr<MultipartPart>>& get_parts() override { return parts; }
virtual const jspan_context& get_trace() override { return next->get_trace(); }
virtual std::unique_ptr<rgw::sal::Object> get_meta_obj() override;
virtual int init(const DoutPrefixProvider* dpp, optional_yield y, ACLOwner& owner, rgw_placement_rule& dest_placement, rgw::sal::Attrs& attrs) override;
virtual int list_parts(const DoutPrefixProvider* dpp, CephContext* cct,
int num_parts, int marker,
int* next_marker, bool* truncated, optional_yield y,
bool assume_unsorted = false) override;
virtual int abort(const DoutPrefixProvider* dpp, CephContext* cct, optional_yield y) override;
virtual int complete(const DoutPrefixProvider* dpp,
optional_yield y, CephContext* cct,
std::map<int, std::string>& part_etags,
std::list<rgw_obj_index_key>& remove_objs,
uint64_t& accounted_size, bool& compressed,
RGWCompressionInfo& cs_info, off_t& ofs,
std::string& tag, ACLOwner& owner,
uint64_t olh_epoch,
rgw::sal::Object* target_obj) override;
virtual int get_info(const DoutPrefixProvider *dpp, optional_yield y,
rgw_placement_rule** rule,
rgw::sal::Attrs* attrs = nullptr) override;
virtual std::unique_ptr<Writer> get_writer(const DoutPrefixProvider *dpp,
optional_yield y,
rgw::sal::Object* obj,
const rgw_user& owner,
const rgw_placement_rule *ptail_placement_rule,
uint64_t part_num,
const std::string& part_num_str) override;
virtual void print(std::ostream& out) const override { return next->print(out); }
};
class FilterMPSerializer : public MPSerializer {
protected:
std::unique_ptr<MPSerializer> next;
public:
FilterMPSerializer(std::unique_ptr<MPSerializer> _next) : next(std::move(_next)) {}
virtual ~FilterMPSerializer() = default;
virtual int try_lock(const DoutPrefixProvider *dpp, utime_t dur, optional_yield y) override;
virtual int unlock() override { return next->unlock(); }
virtual void clear_locked() override { next->clear_locked(); }
virtual bool is_locked() override { return next->is_locked(); }
virtual void print(std::ostream& out) const override { return next->print(out); }
};
class FilterLCSerializer : public LCSerializer {
protected:
std::unique_ptr<LCSerializer> next;
public:
FilterLCSerializer(std::unique_ptr<LCSerializer> _next) : next(std::move(_next)) {}
virtual ~FilterLCSerializer() = default;
virtual int try_lock(const DoutPrefixProvider *dpp, utime_t dur, optional_yield y) override;
virtual int unlock() override { return next->unlock(); }
virtual void print(std::ostream& out) const override { return next->print(out); }
};
class FilterLifecycle : public Lifecycle {
protected:
std::unique_ptr<Lifecycle> next;
public:
struct FilterLCHead : LCHead {
std::unique_ptr<LCHead> next;
FilterLCHead(std::unique_ptr<LCHead> _next) : next(std::move(_next)) {}
virtual ~FilterLCHead() = default;
virtual time_t& get_start_date() override { return next->get_start_date(); }
virtual void set_start_date(time_t t) override { next->set_start_date(t); }
virtual std::string& get_marker() override { return next->get_marker(); }
virtual void set_marker(const std::string& m) override { next->set_marker(m); }
virtual time_t& get_shard_rollover_date() override { return next->get_shard_rollover_date(); }
virtual void set_shard_rollover_date(time_t t) override { next->set_shard_rollover_date(t); }
};
struct FilterLCEntry : LCEntry {
std::unique_ptr<LCEntry> next;
FilterLCEntry(std::unique_ptr<LCEntry> _next) : next(std::move(_next)) {}
virtual ~FilterLCEntry() = default;
virtual std::string& get_bucket() override { return next->get_bucket(); }
virtual void set_bucket(const std::string& b) override { next->set_bucket(b); }
virtual std::string& get_oid() override { return next->get_oid(); }
virtual void set_oid(const std::string& o) override { next->set_oid(o); }
virtual uint64_t get_start_time() override { return next->get_start_time(); }
virtual void set_start_time(uint64_t t) override { next->set_start_time(t); }
virtual uint32_t get_status() override { return next->get_status(); }
virtual void set_status(uint32_t s) override { next->set_status(s); }
virtual void print(std::ostream& out) const override { return next->print(out); }
};
FilterLifecycle(std::unique_ptr<Lifecycle> _next) : next(std::move(_next)) {}
virtual ~FilterLifecycle() = default;
virtual std::unique_ptr<LCEntry> get_entry() override;
virtual int get_entry(const std::string& oid, const std::string& marker,
std::unique_ptr<LCEntry>* entry) override;
virtual int get_next_entry(const std::string& oid, const std::string& marker,
std::unique_ptr<LCEntry>* entry) override;
virtual int set_entry(const std::string& oid, LCEntry& entry) override;
virtual int list_entries(const std::string& oid, const std::string& marker,
uint32_t max_entries,
std::vector<std::unique_ptr<LCEntry>>& entries) override;
virtual int rm_entry(const std::string& oid, LCEntry& entry) override;
virtual int get_head(const std::string& oid, std::unique_ptr<LCHead>* head) override;
virtual int put_head(const std::string& oid, LCHead& head) override;
virtual std::unique_ptr<LCSerializer> get_serializer(const std::string& lock_name,
const std::string& oid,
const std::string& cookie) override;
};
class FilterNotification : public Notification {
protected:
std::unique_ptr<Notification> next;
public:
FilterNotification(std::unique_ptr<Notification> _next) : next(std::move(_next)) {}
virtual ~FilterNotification() = default;
virtual int publish_reserve(const DoutPrefixProvider *dpp,
RGWObjTags* obj_tags = nullptr) override;
virtual int publish_commit(const DoutPrefixProvider* dpp, uint64_t size,
const ceph::real_time& mtime,
const std::string& etag,
const std::string& version) override;
};
class FilterWriter : public Writer {
protected:
std::unique_ptr<Writer> next;
Object* obj;
public:
FilterWriter(std::unique_ptr<Writer> _next, Object* _obj) :
next(std::move(_next)), obj(_obj) {}
virtual ~FilterWriter() = default;
virtual int prepare(optional_yield y) { return next->prepare(y); }
virtual int process(bufferlist&& data, uint64_t offset) override;
virtual int complete(size_t accounted_size, const std::string& etag,
ceph::real_time *mtime, ceph::real_time set_mtime,
std::map<std::string, bufferlist>& attrs,
ceph::real_time delete_at,
const char *if_match, const char *if_nomatch,
const std::string *user_data,
rgw_zone_set *zones_trace, bool *canceled,
optional_yield y) override;
};
class FilterLuaManager : public LuaManager {
protected:
std::unique_ptr<LuaManager> next;
public:
FilterLuaManager(std::unique_ptr<LuaManager> _next) : next(std::move(_next)) {}
virtual ~FilterLuaManager() = default;
virtual int get_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, std::string& script) override;
virtual int put_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key, const std::string& script) override;
virtual int del_script(const DoutPrefixProvider* dpp, optional_yield y, const std::string& key) override;
virtual int add_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name) override;
virtual int remove_package(const DoutPrefixProvider* dpp, optional_yield y, const std::string& package_name) override;
virtual int list_packages(const DoutPrefixProvider* dpp, optional_yield y, rgw::lua::packages_t& packages) override;
};
} } // namespace rgw::sal
| 42,650 | 46.024256 | 154 |
h
|
null |
ceph-main/src/rgw/rgw_sal_fwd.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
namespace rgw { namespace sal {
class Driver;
class User;
class Bucket;
class BucketList;
class Object;
class MultipartUpload;
class Lifecycle;
class Notification;
class Writer;
class PlacementTier;
class ZoneGroup;
class Zone;
class LuaManager;
struct RGWRoleInfo;
class ConfigStore;
class RealmWriter;
class ZoneGroupWriter;
class ZoneWriter;
} } // namespace rgw::sal
| 837 | 18.952381 | 70 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.