repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
ceph-main/src/rgw/rgw_keystone.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <atomic> #include <string_view> #include <type_traits> #include <utility> #include <boost/optional.hpp> #include "rgw_common.h" #include "rgw_http_client.h" #include "common/ceph_mutex.h" #include "global/global_init.h" bool rgw_is_pki_token(const std::string& token); void rgw_get_token_id(const std::string& token, std::string& token_id); static inline std::string rgw_get_token_id(const std::string& token) { std::string token_id; rgw_get_token_id(token, token_id); return token_id; } namespace rgw { namespace keystone { enum class ApiVersion { VER_2, VER_3 }; class Config { protected: Config() = default; virtual ~Config() = default; public: virtual std::string get_endpoint_url() const noexcept = 0; virtual ApiVersion get_api_version() const noexcept = 0; virtual std::string get_admin_token() const noexcept = 0; virtual std::string_view get_admin_user() const noexcept = 0; virtual std::string get_admin_password() const noexcept = 0; virtual std::string_view get_admin_tenant() const noexcept = 0; virtual std::string_view get_admin_project() const noexcept = 0; virtual std::string_view get_admin_domain() const noexcept = 0; }; class CephCtxConfig : public Config { protected: CephCtxConfig() = default; virtual ~CephCtxConfig() = default; const static std::string empty; public: static CephCtxConfig& get_instance() { static CephCtxConfig instance; return instance; } std::string get_endpoint_url() const noexcept override; ApiVersion get_api_version() const noexcept override; std::string get_admin_token() const noexcept override; std::string_view get_admin_user() const noexcept override { return g_ceph_context->_conf->rgw_keystone_admin_user; } std::string get_admin_password() const noexcept override; std::string_view get_admin_tenant() const noexcept override { return g_ceph_context->_conf->rgw_keystone_admin_tenant; } std::string_view get_admin_project() const noexcept override { return g_ceph_context->_conf->rgw_keystone_admin_project; } std::string_view get_admin_domain() const noexcept override { return g_ceph_context->_conf->rgw_keystone_admin_domain; } }; class TokenEnvelope; class TokenCache; class Service { public: class RGWKeystoneHTTPTransceiver : public RGWHTTPTransceiver { public: RGWKeystoneHTTPTransceiver(CephContext * const cct, const std::string& method, const std::string& url, bufferlist * const token_body_bl) : RGWHTTPTransceiver(cct, method, url, token_body_bl, cct->_conf->rgw_keystone_verify_ssl, { "X-Subject-Token" }) { } const header_value_t& get_subject_token() const { try { return get_header_value("X-Subject-Token"); } catch (std::out_of_range&) { static header_value_t empty_val; return empty_val; } } }; typedef RGWKeystoneHTTPTransceiver RGWValidateKeystoneToken; typedef RGWKeystoneHTTPTransceiver RGWGetKeystoneAdminToken; static int get_admin_token(const DoutPrefixProvider *dpp, CephContext* const cct, TokenCache& token_cache, const Config& config, std::string& token); static int issue_admin_token_request(const DoutPrefixProvider *dpp, CephContext* const cct, const Config& config, TokenEnvelope& token); static int get_keystone_barbican_token(const DoutPrefixProvider *dpp, CephContext * const cct, std::string& token); }; class TokenEnvelope { public: class Domain { public: std::string id; std::string name; void decode_json(JSONObj *obj); }; class Project { public: Domain domain; std::string id; std::string name; void decode_json(JSONObj *obj); }; class Token { public: Token() : expires(0) { } std::string id; time_t expires; Project tenant_v2; void decode_json(JSONObj *obj); }; class Role { public: Role() : is_admin(false), is_reader(false) { } Role(const Role &r) { id = r.id; name = r.name; is_admin = r.is_admin; is_reader = r.is_reader; } std::string id; std::string name; bool is_admin; bool is_reader; void decode_json(JSONObj *obj); }; class User { public: std::string id; std::string name; Domain domain; std::list<Role> roles_v2; void decode_json(JSONObj *obj); }; Token token; Project project; User user; std::list<Role> roles; void decode_v3(JSONObj* obj); void decode_v2(JSONObj* obj); public: /* We really need the default ctor because of the internals of TokenCache. */ TokenEnvelope() = default; void set_expires(time_t expires) { token.expires = expires; } time_t get_expires() const { return token.expires; } const std::string& get_domain_id() const {return project.domain.id;}; const std::string& get_domain_name() const {return project.domain.name;}; const std::string& get_project_id() const {return project.id;}; const std::string& get_project_name() const {return project.name;}; const std::string& get_user_id() const {return user.id;}; const std::string& get_user_name() const {return user.name;}; bool has_role(const std::string& r) const; bool expired() const { const uint64_t now = ceph_clock_now().sec(); return std::cmp_greater_equal(now, get_expires()); } int parse(const DoutPrefixProvider *dpp, CephContext* cct, const std::string& token_str, ceph::buffer::list& bl /* in */, ApiVersion version); void update_roles(const std::vector<std::string> & admin, const std::vector<std::string> & reader); }; class TokenCache { struct token_entry { TokenEnvelope token; std::list<std::string>::iterator lru_iter; }; std::atomic<bool> down_flag = { false }; const boost::intrusive_ptr<CephContext> cct; std::string admin_token_id; std::string barbican_token_id; std::map<std::string, token_entry> tokens; std::map<std::string, token_entry> service_tokens; std::list<std::string> tokens_lru; std::list<std::string> service_tokens_lru; ceph::mutex lock = ceph::make_mutex("rgw::keystone::TokenCache"); const size_t max; explicit TokenCache(const rgw::keystone::Config& config) : cct(g_ceph_context), max(cct->_conf->rgw_keystone_token_cache_size) { } ~TokenCache() { down_flag = true; } public: TokenCache(const TokenCache&) = delete; void operator=(const TokenCache&) = delete; template<class ConfigT> static TokenCache& get_instance() { static_assert(std::is_base_of<rgw::keystone::Config, ConfigT>::value, "ConfigT must be a subclass of rgw::keystone::Config"); /* In C++11 this is thread safe. */ static TokenCache instance(ConfigT::get_instance()); return instance; } bool find(const std::string& token_id, TokenEnvelope& token); bool find_service(const std::string& token_id, TokenEnvelope& token); boost::optional<TokenEnvelope> find(const std::string& token_id) { TokenEnvelope token_envlp; if (find(token_id, token_envlp)) { return token_envlp; } return boost::none; } boost::optional<TokenEnvelope> find_service(const std::string& token_id) { TokenEnvelope token_envlp; if (find_service(token_id, token_envlp)) { return token_envlp; } return boost::none; } bool find_admin(TokenEnvelope& token); bool find_barbican(TokenEnvelope& token); void add(const std::string& token_id, const TokenEnvelope& token); void add_service(const std::string& token_id, const TokenEnvelope& token); void add_admin(const TokenEnvelope& token); void add_barbican(const TokenEnvelope& token); void invalidate(const DoutPrefixProvider *dpp, const std::string& token_id); bool going_down() const; private: void add_locked(const std::string& token_id, const TokenEnvelope& token, std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru); bool find_locked(const std::string& token_id, TokenEnvelope& token, std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru); }; class AdminTokenRequest { public: virtual ~AdminTokenRequest() = default; virtual void dump(Formatter* f) const = 0; }; class AdminTokenRequestVer2 : public AdminTokenRequest { const Config& conf; public: explicit AdminTokenRequestVer2(const Config& conf) : conf(conf) { } void dump(Formatter *f) const override; }; class AdminTokenRequestVer3 : public AdminTokenRequest { const Config& conf; public: explicit AdminTokenRequestVer3(const Config& conf) : conf(conf) { } void dump(Formatter *f) const override; }; class BarbicanTokenRequestVer2 : public AdminTokenRequest { CephContext *cct; public: explicit BarbicanTokenRequestVer2(CephContext * const _cct) : cct(_cct) { } void dump(Formatter *f) const override; }; class BarbicanTokenRequestVer3 : public AdminTokenRequest { CephContext *cct; public: explicit BarbicanTokenRequestVer3(CephContext * const _cct) : cct(_cct) { } void dump(Formatter *f) const override; }; }; /* namespace keystone */ }; /* namespace rgw */
9,715
27.162319
99
h
null
ceph-main/src/rgw/rgw_kmip_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once class RGWKMIPManager; class RGWKMIPTransceiver { public: enum kmip_operation { CREATE, LOCATE, GET, GET_ATTRIBUTES, GET_ATTRIBUTE_LIST, DESTROY }; CephContext *cct; kmip_operation operation; char *name = 0; char *unique_id = 0; // output - must free char *out = 0; // unique_id, several struct { // unique_ids, locate char **strings; int string_count; } outlist[1] = {{0, 0}}; struct { // key, get unsigned char *data; int keylen; } outkey[1] = {0, 0}; // end must free int ret; bool done; ceph::mutex lock = ceph::make_mutex("rgw_kmip_req::lock"); ceph::condition_variable cond; int wait(optional_yield y); RGWKMIPTransceiver(CephContext * const cct, kmip_operation operation) : cct(cct), operation(operation), ret(-EDOM), done(false) {} ~RGWKMIPTransceiver(); int send(); int process(optional_yield y); }; class RGWKMIPManager { protected: CephContext *cct; bool is_started = false; RGWKMIPManager(CephContext *cct) : cct(cct) {}; public: virtual ~RGWKMIPManager() { }; virtual int start() = 0; virtual void stop() = 0; virtual int add_request(RGWKMIPTransceiver*) = 0; }; void rgw_kmip_client_init(RGWKMIPManager &); void rgw_kmip_client_cleanup();
1,404
20.287879
70
h
null
ceph-main/src/rgw/rgw_kmip_client_impl.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once struct RGWKmipWorker; class RGWKMIPManagerImpl: public RGWKMIPManager { protected: ceph::mutex lock = ceph::make_mutex("RGWKMIPManager"); ceph::condition_variable cond; struct Request : boost::intrusive::list_base_hook<> { boost::intrusive::list_member_hook<> req_hook; RGWKMIPTransceiver &details; Request(RGWKMIPTransceiver &details) : details(details) {} }; boost::intrusive::list<Request, boost::intrusive::member_hook< Request, boost::intrusive::list_member_hook<>, &Request::req_hook>> requests; bool going_down = false; RGWKmipWorker *worker = 0; public: RGWKMIPManagerImpl(CephContext *cct) : RGWKMIPManager(cct) {}; int add_request(RGWKMIPTransceiver *); int start(); void stop(); friend RGWKmipWorker; };
874
30.25
73
h
null
ceph-main/src/rgw/rgw_kms.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /** * Server-side encryption integrations with Key Management Systems (SSE-KMS) */ #pragma once #include <string> static const std::string RGW_SSE_KMS_BACKEND_TESTING = "testing"; static const std::string RGW_SSE_KMS_BACKEND_BARBICAN = "barbican"; static const std::string RGW_SSE_KMS_BACKEND_VAULT = "vault"; static const std::string RGW_SSE_KMS_BACKEND_KMIP = "kmip"; static const std::string RGW_SSE_KMS_VAULT_AUTH_TOKEN = "token"; static const std::string RGW_SSE_KMS_VAULT_AUTH_AGENT = "agent"; static const std::string RGW_SSE_KMS_VAULT_SE_TRANSIT = "transit"; static const std::string RGW_SSE_KMS_VAULT_SE_KV = "kv"; static const std::string RGW_SSE_KMS_KMIP_SE_KV = "kv"; /** * Retrieves the actual server-side encryption key from a KMS system given a * key ID. Currently supported KMS systems are OpenStack Barbican and HashiCorp * Vault, but keys can also be retrieved from Ceph configuration file (if * kms is set to 'local'). * * \params * TODO * \return */ int make_actual_key_from_kms(const DoutPrefixProvider *dpp, CephContext *cct, std::map<std::string, bufferlist>& attrs, std::string& actual_key); int reconstitute_actual_key_from_kms(const DoutPrefixProvider *dpp, CephContext *cct, std::map<std::string, bufferlist>& attrs, std::string& actual_key); int make_actual_key_from_sse_s3(const DoutPrefixProvider *dpp, CephContext *cct, std::map<std::string, bufferlist>& attrs, std::string& actual_key); int reconstitute_actual_key_from_sse_s3(const DoutPrefixProvider *dpp, CephContext *cct, std::map<std::string, bufferlist>& attrs, std::string& actual_key); int create_sse_s3_bucket_key(const DoutPrefixProvider *dpp, CephContext *cct, const std::string& actual_key); int remove_sse_s3_bucket_key(const DoutPrefixProvider *dpp, CephContext *cct, const std::string& actual_key); /** * SecretEngine Interface * Defining interface here such that we can use both a real implementation * of this interface, and a mock implementation in tests. **/ class SecretEngine { public: virtual int get_key(const DoutPrefixProvider *dpp, std::string_view key_id, std::string& actual_key) = 0; virtual ~SecretEngine(){}; };
2,533
37.984615
107
h
null
ceph-main/src/rgw/rgw_lc.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <map> #include <array> #include <string> #include <iostream> #include "common/debug.h" #include "include/types.h" #include "include/rados/librados.hpp" #include "common/ceph_mutex.h" #include "common/Cond.h" #include "common/iso_8601.h" #include "common/Thread.h" #include "rgw_common.h" #include "cls/rgw/cls_rgw_types.h" #include "rgw_tag.h" #include "rgw_sal.h" #include <atomic> #include <tuple> #define HASH_PRIME 7877 #define MAX_ID_LEN 255 static std::string lc_oid_prefix = "lc"; static std::string lc_index_lock_name = "lc_process"; extern const char* LC_STATUS[]; typedef enum { lc_uninitial = 0, lc_processing, lc_failed, lc_complete, } LC_BUCKET_STATUS; class LCExpiration { protected: std::string days; //At present only current object has expiration date std::string date; public: LCExpiration() {} LCExpiration(const std::string& _days, const std::string& _date) : days(_days), date(_date) {} void encode(bufferlist& bl) const { ENCODE_START(3, 2, bl); encode(days, bl); encode(date, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(3, 2, 2, bl); decode(days, bl); if (struct_v >= 3) { decode(date, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; // static void generate_test_instances(list<ACLOwner*>& o); void set_days(const std::string& _days) { days = _days; } std::string get_days_str() const { return days; } int get_days() const {return atoi(days.c_str()); } bool has_days() const { return !days.empty(); } void set_date(const std::string& _date) { date = _date; } std::string get_date() const { return date; } bool has_date() const { return !date.empty(); } bool empty() const { return days.empty() && date.empty(); } bool valid() const { if (!days.empty() && !date.empty()) { return false; } else if (!days.empty() && get_days() <= 0) { return false; } //We've checked date in xml parsing return true; } }; WRITE_CLASS_ENCODER(LCExpiration) class LCTransition { protected: std::string days; std::string date; std::string storage_class; public: int get_days() const { return atoi(days.c_str()); } std::string get_date() const { return date; } std::string get_storage_class() const { return storage_class; } bool has_days() const { return !days.empty(); } bool has_date() const { return !date.empty(); } bool empty() const { return days.empty() && date.empty(); } bool valid() const { if (!days.empty() && !date.empty()) { return false; } else if (!days.empty() && get_days() < 0) { return false; } //We've checked date in xml parsing return true; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(days, bl); encode(date, bl); encode(storage_class, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(days, bl); decode(date, bl); decode(storage_class, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const { f->dump_string("days", days); f->dump_string("date", date); f->dump_string("storage_class", storage_class); } }; WRITE_CLASS_ENCODER(LCTransition) enum class LCFlagType : uint16_t { none = 0, ArchiveZone, }; class LCFlag { public: LCFlagType bit; const char* name; constexpr LCFlag(LCFlagType ord, const char* name) : bit(ord), name(name) {} }; class LCFilter { public: static constexpr uint32_t make_flag(LCFlagType type) { switch (type) { case LCFlagType::none: return 0; break; default: return 1 << (uint32_t(type) - 1); } } static constexpr std::array<LCFlag, 2> filter_flags = { LCFlag(LCFlagType::none, "none"), LCFlag(LCFlagType::ArchiveZone, "ArchiveZone"), }; protected: std::string prefix; RGWObjTags obj_tags; uint32_t flags; public: LCFilter() : flags(make_flag(LCFlagType::none)) {} const std::string& get_prefix() const { return prefix; } const RGWObjTags& get_tags() const { return obj_tags; } const uint32_t get_flags() const { return flags; } bool empty() const { return !(has_prefix() || has_tags() || has_flags()); } // Determine if we need AND tag when creating xml bool has_multi_condition() const { if (obj_tags.count() + int(has_prefix()) + int(has_flags()) > 1) // Prefix is a member of Filter return true; return false; } bool has_prefix() const { return !prefix.empty(); } bool has_tags() const { return !obj_tags.empty(); } bool has_flags() const { return !(flags == uint32_t(LCFlagType::none)); } bool have_flag(LCFlagType flag) const { return flags & make_flag(flag); } void encode(bufferlist& bl) const { ENCODE_START(3, 1, bl); encode(prefix, bl); encode(obj_tags, bl); encode(flags, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(3, bl); decode(prefix, bl); if (struct_v >= 2) { decode(obj_tags, bl); if (struct_v >= 3) { decode(flags, bl); } } DECODE_FINISH(bl); } void dump(Formatter *f) const; }; WRITE_CLASS_ENCODER(LCFilter) class LCRule { protected: std::string id; std::string prefix; std::string status; LCExpiration expiration; LCExpiration noncur_expiration; LCExpiration mp_expiration; LCFilter filter; std::map<std::string, LCTransition> transitions; std::map<std::string, LCTransition> noncur_transitions; bool dm_expiration = false; public: LCRule(){}; virtual ~LCRule() {} const std::string& get_id() const { return id; } const std::string& get_status() const { return status; } bool is_enabled() const { return status == "Enabled"; } void set_enabled(bool flag) { status = (flag ? "Enabled" : "Disabled"); } const std::string& get_prefix() const { return prefix; } const LCFilter& get_filter() const { return filter; } const LCExpiration& get_expiration() const { return expiration; } const LCExpiration& get_noncur_expiration() const { return noncur_expiration; } const LCExpiration& get_mp_expiration() const { return mp_expiration; } bool get_dm_expiration() const { return dm_expiration; } const std::map<std::string, LCTransition>& get_transitions() const { return transitions; } const std::map<std::string, LCTransition>& get_noncur_transitions() const { return noncur_transitions; } void set_id(const std::string& _id) { id = _id; } void set_prefix(const std::string& _prefix) { prefix = _prefix; } void set_status(const std::string& _status) { status = _status; } void set_expiration(const LCExpiration& _expiration) { expiration = _expiration; } void set_noncur_expiration(const LCExpiration& _noncur_expiration) { noncur_expiration = _noncur_expiration; } void set_mp_expiration(const LCExpiration& _mp_expiration) { mp_expiration = _mp_expiration; } void set_dm_expiration(bool _dm_expiration) { dm_expiration = _dm_expiration; } bool add_transition(const LCTransition& _transition) { auto ret = transitions.emplace(_transition.get_storage_class(), _transition); return ret.second; } bool add_noncur_transition(const LCTransition& _noncur_transition) { auto ret = noncur_transitions.emplace(_noncur_transition.get_storage_class(), _noncur_transition); return ret.second; } bool valid() const; void encode(bufferlist& bl) const { ENCODE_START(6, 1, bl); encode(id, bl); encode(prefix, bl); encode(status, bl); encode(expiration, bl); encode(noncur_expiration, bl); encode(mp_expiration, bl); encode(dm_expiration, bl); encode(filter, bl); encode(transitions, bl); encode(noncur_transitions, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(6, 1, 1, bl); decode(id, bl); decode(prefix, bl); decode(status, bl); decode(expiration, bl); if (struct_v >=2) { decode(noncur_expiration, bl); } if (struct_v >= 3) { decode(mp_expiration, bl); } if (struct_v >= 4) { decode(dm_expiration, bl); } if (struct_v >= 5) { decode(filter, bl); } if (struct_v >= 6) { decode(transitions, bl); decode(noncur_transitions, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void init_simple_days_rule(std::string_view _id, std::string_view _prefix, int num_days); }; WRITE_CLASS_ENCODER(LCRule) struct transition_action { int days; boost::optional<ceph::real_time> date; std::string storage_class; transition_action() : days(0) {} void dump(Formatter *f) const { if (!date) { f->dump_int("days", days); } else { utime_t ut(*date); f->dump_stream("date") << ut; } } }; /* XXX why not LCRule? */ struct lc_op { std::string id; bool status{false}; bool dm_expiration{false}; int expiration{0}; int noncur_expiration{0}; int mp_expiration{0}; boost::optional<ceph::real_time> expiration_date; boost::optional<RGWObjTags> obj_tags; std::map<std::string, transition_action> transitions; std::map<std::string, transition_action> noncur_transitions; uint32_t rule_flags; /* ctors are nice */ lc_op() = delete; lc_op(const std::string id) : id(id) {} void dump(Formatter *f) const; }; class RGWLifecycleConfiguration { protected: CephContext *cct; std::multimap<std::string, lc_op> prefix_map; std::multimap<std::string, LCRule> rule_map; bool _add_rule(const LCRule& rule); bool has_same_action(const lc_op& first, const lc_op& second); public: explicit RGWLifecycleConfiguration(CephContext *_cct) : cct(_cct) {} RGWLifecycleConfiguration() : cct(NULL) {} void set_ctx(CephContext *ctx) { cct = ctx; } virtual ~RGWLifecycleConfiguration() {} // int get_perm(std::string& id, int perm_mask); // int get_group_perm(ACLGroupTypeEnum group, int perm_mask); void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(rule_map, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(rule_map, bl); std::multimap<std::string, LCRule>::iterator iter; for (iter = rule_map.begin(); iter != rule_map.end(); ++iter) { LCRule& rule = iter->second; _add_rule(rule); } DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWLifecycleConfiguration*>& o); void add_rule(const LCRule& rule); int check_and_add_rule(const LCRule& rule); bool valid(); std::multimap<std::string, LCRule>& get_rule_map() { return rule_map; } std::multimap<std::string, lc_op>& get_prefix_map() { return prefix_map; } /* void create_default(std::string id, std::string name) { ACLGrant grant; grant.set_canon(id, name, RGW_PERM_FULL_CONTROL); add_grant(&grant); } */ }; WRITE_CLASS_ENCODER(RGWLifecycleConfiguration) class RGWLC : public DoutPrefixProvider { CephContext *cct; rgw::sal::Driver* driver; std::unique_ptr<rgw::sal::Lifecycle> sal_lc; int max_objs{0}; std::string *obj_names{nullptr}; std::atomic<bool> down_flag = { false }; std::string cookie; public: class WorkPool; class LCWorker : public Thread { const DoutPrefixProvider *dpp; CephContext *cct; RGWLC *lc; int ix; std::mutex lock; std::condition_variable cond; WorkPool* workpool{nullptr}; /* save the target bucket names created as part of object transition * to cloud. This list is maintained for the duration of each RGWLC::process() * post which it is discarded. */ std::set<std::string> cloud_targets; public: using lock_guard = std::lock_guard<std::mutex>; using unique_lock = std::unique_lock<std::mutex>; LCWorker(const DoutPrefixProvider* dpp, CephContext *_cct, RGWLC *_lc, int ix); RGWLC* get_lc() { return lc; } std::string thr_name() { return std::string{"lc_thrd: "} + std::to_string(ix); } void *entry() override; void stop(); bool should_work(utime_t& now); int schedule_next_start_time(utime_t& start, utime_t& now); std::set<std::string>& get_cloud_targets() { return cloud_targets; } virtual ~LCWorker() override; friend class RGWRados; friend class RGWLC; friend class WorkQ; }; /* LCWorker */ friend class RGWRados; std::vector<std::unique_ptr<RGWLC::LCWorker>> workers; RGWLC() : cct(nullptr), driver(nullptr) {} virtual ~RGWLC() override; void initialize(CephContext *_cct, rgw::sal::Driver* _driver); void finalize(); int process(LCWorker* worker, const std::unique_ptr<rgw::sal::Bucket>& optional_bucket, bool once); int advance_head(const std::string& lc_shard, rgw::sal::Lifecycle::LCHead& head, rgw::sal::Lifecycle::LCEntry& entry, time_t start_date); int process(int index, int max_lock_secs, LCWorker* worker, bool once); int process_bucket(int index, int max_lock_secs, LCWorker* worker, const std::string& bucket_entry_marker, bool once); bool expired_session(time_t started); time_t thread_stop_at(); int list_lc_progress(std::string& marker, uint32_t max_entries, std::vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>>&, int& index); int bucket_lc_process(std::string& shard_id, LCWorker* worker, time_t stop_at, bool once); int bucket_lc_post(int index, int max_lock_sec, rgw::sal::Lifecycle::LCEntry& entry, int& result, LCWorker* worker); bool going_down(); void start_processor(); void stop_processor(); int set_bucket_config(rgw::sal::Bucket* bucket, const rgw::sal::Attrs& bucket_attrs, RGWLifecycleConfiguration *config); int remove_bucket_config(rgw::sal::Bucket* bucket, const rgw::sal::Attrs& bucket_attrs, bool merge_attrs = true); CephContext *get_cct() const override { return cct; } rgw::sal::Lifecycle* get_lc() const { return sal_lc.get(); } unsigned get_subsys() const; std::ostream& gen_prefix(std::ostream& out) const; private: int handle_multipart_expiration(rgw::sal::Bucket* target, const std::multimap<std::string, lc_op>& prefix_map, LCWorker* worker, time_t stop_at, bool once); }; namespace rgw::lc { int fix_lc_shard_entry(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, rgw::sal::Lifecycle* sal_lc, rgw::sal::Bucket* bucket); std::string s3_expiration_header( DoutPrefixProvider* dpp, const rgw_obj_key& obj_key, const RGWObjTags& obj_tagset, const ceph::real_time& mtime, const std::map<std::string, buffer::list>& bucket_attrs); bool s3_multipart_abort_header( DoutPrefixProvider* dpp, const rgw_obj_key& obj_key, const ceph::real_time& mtime, const std::map<std::string, buffer::list>& bucket_attrs, ceph::real_time& abort_date, std::string& rule_id); } // namespace rgw::lc
15,484
23.157566
102
h
null
ceph-main/src/rgw/rgw_ldap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "acconfig.h" #if defined(HAVE_OPENLDAP) #define LDAP_DEPRECATED 1 #include "ldap.h" #endif #include <stdint.h> #include <tuple> #include <vector> #include <string> #include <iostream> #include <mutex> namespace rgw { #if defined(HAVE_OPENLDAP) class LDAPHelper { std::string uri; std::string binddn; std::string bindpw; std::string searchdn; std::string searchfilter; std::string dnattr; LDAP *ldap; bool msad = false; /* TODO: possible future specialization */ std::mutex mtx; public: using lock_guard = std::lock_guard<std::mutex>; LDAPHelper(std::string _uri, std::string _binddn, std::string _bindpw, const std::string &_searchdn, const std::string &_searchfilter, const std::string &_dnattr) : uri(std::move(_uri)), binddn(std::move(_binddn)), bindpw(std::move(_bindpw)), searchdn(_searchdn), searchfilter(_searchfilter), dnattr(_dnattr), ldap(nullptr) { // nothing } int init() { int ret; ret = ldap_initialize(&ldap, uri.c_str()); if (ret == LDAP_SUCCESS) { unsigned long ldap_ver = LDAP_VERSION3; ret = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, (void*) &ldap_ver); } if (ret == LDAP_SUCCESS) { ret = ldap_set_option(ldap, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); } return (ret == LDAP_SUCCESS) ? ret : -EINVAL; } int bind() { int ret; ret = ldap_simple_bind_s(ldap, binddn.c_str(), bindpw.c_str()); return (ret == LDAP_SUCCESS) ? ret : -EINVAL; } int rebind() { if (ldap) { (void) ldap_unbind(ldap); (void) init(); return bind(); } return -EINVAL; } int simple_bind(const char *dn, const std::string& pwd) { LDAP* tldap; int ret = ldap_initialize(&tldap, uri.c_str()); if (ret == LDAP_SUCCESS) { unsigned long ldap_ver = LDAP_VERSION3; ret = ldap_set_option(tldap, LDAP_OPT_PROTOCOL_VERSION, (void*) &ldap_ver); if (ret == LDAP_SUCCESS) { ret = ldap_simple_bind_s(tldap, dn, pwd.c_str()); } (void) ldap_unbind(tldap); } return ret; // OpenLDAP client error space } int auth(const std::string &uid, const std::string &pwd); ~LDAPHelper() { if (ldap) (void) ldap_unbind(ldap); } }; /* LDAPHelper */ #else class LDAPHelper { public: LDAPHelper(const std::string &_uri, const std::string &_binddn, const std::string &_bindpw, const std::string &_searchdn, const std::string &_searchfilter, const std::string &_dnattr) {} int init() { return -ENOTSUP; } int bind() { return -ENOTSUP; } int auth(const std::string &uid, const std::string &pwd) { return -EACCES; } ~LDAPHelper() {} }; /* LDAPHelper */ #endif /* HAVE_OPENLDAP */ } /* namespace rgw */ #include "common/ceph_context.h" #include "common/common_init.h" #include "common/dout.h" #include "common/safe_io.h" #include <boost/algorithm/string.hpp> #include "include/ceph_assert.h" std::string parse_rgw_ldap_bindpw(CephContext* ctx);
3,195
21.992806
99
h
null
ceph-main/src/rgw/rgw_lib.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <mutex> #include "rgw_common.h" #include "rgw_client_io.h" #include "rgw_rest.h" #include "rgw_request.h" #include "rgw_ldap.h" #include "include/ceph_assert.h" #include "rgw_main.h" class OpsLogSink; namespace rgw { class RGWLibFrontend; class RGWLib : public DoutPrefixProvider { boost::intrusive_ptr<CephContext> cct; AppMain main; RGWLibFrontend* fe; public: RGWLib() : main(this), fe(nullptr) {} ~RGWLib() {} rgw::sal::Driver* get_driver() { return main.get_driver(); } RGWLibFrontend* get_fe() { return fe; } rgw::LDAPHelper* get_ldh() { return main.get_ldh(); } CephContext *get_cct() const override { return cct.get(); } unsigned get_subsys() const { return ceph_subsys_rgw; } std::ostream& gen_prefix(std::ostream& out) const { return out << "lib rgw: "; } void set_fe(RGWLibFrontend* fe); int init(); int init(std::vector<const char *>& args); int stop(); }; extern RGWLib* g_rgwlib; /* request interface */ class RGWLibIO : public rgw::io::BasicClient, public rgw::io::Accounter { RGWUserInfo user_info; RGWEnv env; public: RGWLibIO() { get_env().set("HTTP_HOST", ""); } explicit RGWLibIO(const RGWUserInfo &_user_info) : user_info(_user_info) {} int init_env(CephContext *cct) override { env.init(cct); return 0; } const RGWUserInfo& get_user() { return user_info; } int set_uid(rgw::sal::Driver* driver, const rgw_user& uid); int write_data(const char *buf, int len); int read_data(char *buf, int len); int send_status(int status, const char *status_name); int send_100_continue(); int complete_header(); int send_content_length(uint64_t len); RGWEnv& get_env() noexcept override { return env; } size_t complete_request() override { /* XXX */ return 0; }; void set_account(bool) override { return; } uint64_t get_bytes_sent() const override { return 0; } uint64_t get_bytes_received() const override { return 0; } }; /* RGWLibIO */ class RGWRESTMgr_Lib : public RGWRESTMgr { public: RGWRESTMgr_Lib() {} ~RGWRESTMgr_Lib() override {} }; /* RGWRESTMgr_Lib */ class RGWHandler_Lib : public RGWHandler { friend class RGWRESTMgr_Lib; public: int authorize(const DoutPrefixProvider *dpp, optional_yield y) override; RGWHandler_Lib() {} ~RGWHandler_Lib() override {} static int init_from_header(rgw::sal::Driver* driver, req_state *s); }; /* RGWHandler_Lib */ class RGWLibRequest : public RGWRequest, public RGWHandler_Lib { private: std::unique_ptr<rgw::sal::User> tuser; // Don't use this. It's empty except during init. public: CephContext* cct; /* unambiguiously return req_state */ inline req_state* get_state() { return this->RGWRequest::s; } RGWLibRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user) : RGWRequest(g_rgwlib->get_driver()->get_new_req_id()), tuser(std::move(_user)), cct(_cct) {} int postauth_init(optional_yield) override { return 0; } /* descendant equivalent of *REST*::init_from_header(...): * prepare request for execute()--should mean, fixup URI-alikes * and any other expected stat vars in local req_state, for * now */ virtual int header_init() = 0; /* descendant initializer responsible to call RGWOp::init()--which * descendants are required to inherit */ virtual int op_init() = 0; using RGWHandler::init; int init(const RGWEnv& rgw_env, rgw::sal::Driver* _driver, RGWLibIO* io, req_state* _s) { RGWRequest::init_state(_s); RGWHandler::init(_driver, _s, io); get_state()->req_id = driver->zone_unique_id(id); get_state()->trans_id = driver->zone_unique_trans_id(id); get_state()->bucket_tenant = tuser->get_tenant(); get_state()->set_user(tuser); ldpp_dout(_s, 2) << "initializing for trans_id = " << get_state()->trans_id.c_str() << dendl; int ret = header_init(); if (ret == 0) { ret = init_from_header(driver, _s); } return ret; } virtual bool only_bucket() = 0; int read_permissions(RGWOp *op, optional_yield y) override; }; /* RGWLibRequest */ class RGWLibContinuedReq : public RGWLibRequest { RGWLibIO io_ctx; req_state rstate; public: RGWLibContinuedReq(CephContext* _cct, const RGWProcessEnv& penv, std::unique_ptr<rgw::sal::User> _user) : RGWLibRequest(_cct, std::move(_user)), io_ctx(), rstate(_cct, penv, &io_ctx.get_env(), id) { io_ctx.init(_cct); RGWRequest::init_state(&rstate); RGWHandler::init(g_rgwlib->get_driver(), &rstate, &io_ctx); get_state()->req_id = driver->zone_unique_id(id); get_state()->trans_id = driver->zone_unique_trans_id(id); ldpp_dout(get_state(), 2) << "initializing for trans_id = " << get_state()->trans_id.c_str() << dendl; } inline rgw::sal::Driver* get_driver() { return driver; } inline RGWLibIO& get_io() { return io_ctx; } virtual int execute() final { ceph_abort(); } virtual int exec_start() = 0; virtual int exec_continue() = 0; virtual int exec_finish() = 0; }; /* RGWLibContinuedReq */ } /* namespace rgw */
5,465
25.028571
93
h
null
ceph-main/src/rgw/rgw_lib_frontend.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <boost/container/flat_map.hpp> #include "rgw_lib.h" #include "rgw_file.h" namespace rgw { class RGWLibProcess : public RGWProcess { RGWAccessKey access_key; std::mutex mtx; std::condition_variable cv; int gen; bool shutdown; typedef flat_map<RGWLibFS*, RGWLibFS*> FSMAP; FSMAP mounted_fs; using lock_guard = std::lock_guard<std::mutex>; using unique_lock = std::unique_lock<std::mutex>; public: RGWLibProcess(CephContext* cct, RGWProcessEnv& pe, int num_threads, std::string uri_prefix, RGWFrontendConfig* _conf) : RGWProcess(cct, pe, num_threads, std::move(uri_prefix), _conf), gen(0), shutdown(false) {} void run() override; void checkpoint(); void stop() { shutdown = true; for (const auto& fs: mounted_fs) { fs.second->stop(); } cv.notify_all(); } void register_fs(RGWLibFS* fs) { lock_guard guard(mtx); mounted_fs.insert(FSMAP::value_type(fs, fs)); ++gen; } void unregister_fs(RGWLibFS* fs) { lock_guard guard(mtx); FSMAP::iterator it = mounted_fs.find(fs); if (it != mounted_fs.end()) { mounted_fs.erase(it); ++gen; } } void enqueue_req(RGWLibRequest* req) { lsubdout(g_ceph_context, rgw, 10) << __func__ << " enqueue request req=" << std::hex << req << std::dec << dendl; req_throttle.get(1); req_wq.queue(req); } /* enqueue_req */ /* "regular" requests */ void handle_request(const DoutPrefixProvider *dpp, RGWRequest* req) override; // async handler, deletes req int process_request(RGWLibRequest* req); int process_request(RGWLibRequest* req, RGWLibIO* io); void set_access_key(RGWAccessKey& key) { access_key = key; } /* requests w/continue semantics */ int start_request(RGWLibContinuedReq* req); int finish_request(RGWLibContinuedReq* req); }; /* RGWLibProcess */ class RGWLibFrontend : public RGWProcessFrontend { public: RGWLibFrontend(RGWProcessEnv& pe, RGWFrontendConfig *_conf) : RGWProcessFrontend(pe, _conf) {} int init() override; void stop() override { RGWProcessFrontend::stop(); get_process()->stop(); } RGWLibProcess* get_process() { return static_cast<RGWLibProcess*>(pprocess); } inline void enqueue_req(RGWLibRequest* req) { static_cast<RGWLibProcess*>(pprocess)->enqueue_req(req); // async } inline int execute_req(RGWLibRequest* req) { return static_cast<RGWLibProcess*>(pprocess)->process_request(req); // !async } inline int start_req(RGWLibContinuedReq* req) { return static_cast<RGWLibProcess*>(pprocess)->start_request(req); } inline int finish_req(RGWLibContinuedReq* req) { return static_cast<RGWLibProcess*>(pprocess)->finish_request(req); } }; /* RGWLibFrontend */ } /* namespace rgw */
3,015
25.45614
111
h
null
ceph-main/src/rgw/rgw_loadgen.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <map> #include <string> #include "rgw_client_io.h" struct RGWLoadGenRequestEnv { int port; uint64_t content_length; std::string content_type; std::string request_method; std::string uri; std::string query_string; std::string date_str; std::map<std::string, std::string> headers; RGWLoadGenRequestEnv() : port(0), content_length(0) { } void set_date(utime_t& tm); int sign(const DoutPrefixProvider *dpp, RGWAccessKey& access_key); }; /* XXX does RGWLoadGenIO actually want to perform stream/HTTP I/O, * or (e.g) are these NOOPs? */ class RGWLoadGenIO : public rgw::io::RestfulClient { uint64_t left_to_read; RGWLoadGenRequestEnv* req; RGWEnv env; int init_env(CephContext *cct) override; size_t read_data(char *buf, size_t len); size_t write_data(const char *buf, size_t len); public: explicit RGWLoadGenIO(RGWLoadGenRequestEnv* const req) : left_to_read(0), req(req) { } size_t send_status(int status, const char *status_name) override; size_t send_100_continue() override; size_t send_header(const std::string_view& name, const std::string_view& value) override; size_t complete_header() override; size_t send_content_length(uint64_t len) override; size_t recv_body(char* buf, size_t max) override { return read_data(buf, max); } size_t send_body(const char* buf, size_t len) override { return write_data(buf, len); } void flush() override; RGWEnv& get_env() noexcept override { return env; } size_t complete_request() override; };
1,697
22.260274
70
h
null
ceph-main/src/rgw/rgw_log.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <boost/container/flat_map.hpp> #include "rgw_common.h" #include "common/OutputDataSocket.h" #include <vector> #include <fstream> #include "rgw_sal_fwd.h" class RGWOp; struct delete_multi_obj_entry { std::string key; std::string version_id; std::string error_message; std::string marker_version_id; uint32_t http_status = 0; bool error = false; bool delete_marker = false; void encode(bufferlist &bl) const { ENCODE_START(1, 1, bl); encode(key, bl); encode(version_id, bl); encode(error_message, bl); encode(marker_version_id, bl); encode(http_status, bl); encode(error, bl); encode(delete_marker, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator &p) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, p); decode(key, p); decode(version_id, p); decode(error_message, p); decode(marker_version_id, p); decode(http_status, p); decode(error, p); decode(delete_marker, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(delete_multi_obj_entry) struct delete_multi_obj_op_meta { uint32_t num_ok = 0; uint32_t num_err = 0; std::vector<delete_multi_obj_entry> objects; void encode(bufferlist &bl) const { ENCODE_START(1, 1, bl); encode(num_ok, bl); encode(num_err, bl); encode(objects, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator &p) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, p); decode(num_ok, p); decode(num_err, p); decode(objects, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(delete_multi_obj_op_meta) struct rgw_log_entry { using headers_map = boost::container::flat_map<std::string, std::string>; using Clock = req_state::Clock; rgw_user object_owner; rgw_user bucket_owner; std::string bucket; Clock::time_point time; std::string remote_addr; std::string user; rgw_obj_key obj; std::string op; std::string uri; std::string http_status; std::string error_code; uint64_t bytes_sent = 0; uint64_t bytes_received = 0; uint64_t obj_size = 0; Clock::duration total_time{}; std::string user_agent; std::string referrer; std::string bucket_id; headers_map x_headers; std::string trans_id; std::vector<std::string> token_claims; uint32_t identity_type = TYPE_NONE; std::string access_key_id; std::string subuser; bool temp_url {false}; delete_multi_obj_op_meta delete_multi_obj_meta; void encode(bufferlist &bl) const { ENCODE_START(14, 5, bl); encode(object_owner.id, bl); encode(bucket_owner.id, bl); encode(bucket, bl); encode(time, bl); encode(remote_addr, bl); encode(user, bl); encode(obj.name, bl); encode(op, bl); encode(uri, bl); encode(http_status, bl); encode(error_code, bl); encode(bytes_sent, bl); encode(obj_size, bl); encode(total_time, bl); encode(user_agent, bl); encode(referrer, bl); encode(bytes_received, bl); encode(bucket_id, bl); encode(obj, bl); encode(object_owner, bl); encode(bucket_owner, bl); encode(x_headers, bl); encode(trans_id, bl); encode(token_claims, bl); encode(identity_type,bl); encode(access_key_id, bl); encode(subuser, bl); encode(temp_url, bl); encode(delete_multi_obj_meta, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator &p) { DECODE_START_LEGACY_COMPAT_LEN(14, 5, 5, p); decode(object_owner.id, p); if (struct_v > 3) decode(bucket_owner.id, p); decode(bucket, p); decode(time, p); decode(remote_addr, p); decode(user, p); decode(obj.name, p); decode(op, p); decode(uri, p); decode(http_status, p); decode(error_code, p); decode(bytes_sent, p); decode(obj_size, p); decode(total_time, p); decode(user_agent, p); decode(referrer, p); if (struct_v >= 2) decode(bytes_received, p); else bytes_received = 0; if (struct_v >= 3) { if (struct_v <= 5) { uint64_t id; decode(id, p); char buf[32]; snprintf(buf, sizeof(buf), "%" PRIu64, id); bucket_id = buf; } else { decode(bucket_id, p); } } else { bucket_id = ""; } if (struct_v >= 7) { decode(obj, p); } if (struct_v >= 8) { decode(object_owner, p); decode(bucket_owner, p); } if (struct_v >= 9) { decode(x_headers, p); } if (struct_v >= 10) { decode(trans_id, p); } if (struct_v >= 11) { decode(token_claims, p); } if (struct_v >= 12) { decode(identity_type, p); } if (struct_v >= 13) { decode(access_key_id, p); decode(subuser, p); decode(temp_url, p); } if (struct_v >= 14) { decode(delete_multi_obj_meta, p); } DECODE_FINISH(p); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<rgw_log_entry*>& o); }; WRITE_CLASS_ENCODER(rgw_log_entry) class OpsLogSink { public: virtual int log(req_state* s, struct rgw_log_entry& entry) = 0; virtual ~OpsLogSink() = default; }; class OpsLogManifold: public OpsLogSink { std::vector<OpsLogSink*> sinks; public: ~OpsLogManifold() override; void add_sink(OpsLogSink* sink); int log(req_state* s, struct rgw_log_entry& entry) override; }; class JsonOpsLogSink : public OpsLogSink { ceph::Formatter *formatter; ceph::mutex lock = ceph::make_mutex("JsonOpsLogSink"); void formatter_to_bl(bufferlist& bl); protected: virtual int log_json(req_state* s, bufferlist& bl) = 0; public: JsonOpsLogSink(); ~JsonOpsLogSink() override; int log(req_state* s, struct rgw_log_entry& entry) override; }; class OpsLogFile : public JsonOpsLogSink, public Thread, public DoutPrefixProvider { CephContext* cct; ceph::mutex mutex = ceph::make_mutex("OpsLogFile"); std::vector<bufferlist> log_buffer; std::vector<bufferlist> flush_buffer; ceph::condition_variable cond; std::ofstream file; bool stopped; uint64_t data_size; uint64_t max_data_size; std::string path; std::atomic_bool need_reopen; void flush(); protected: int log_json(req_state* s, bufferlist& bl) override; void *entry() override; public: OpsLogFile(CephContext* cct, std::string& path, uint64_t max_data_size); ~OpsLogFile() override; CephContext *get_cct() const override { return cct; } unsigned get_subsys() const override; std::ostream& gen_prefix(std::ostream& out) const override { return out << "rgw OpsLogFile: "; } void reopen(); void start(); void stop(); }; class OpsLogSocket : public OutputDataSocket, public JsonOpsLogSink { protected: int log_json(req_state* s, bufferlist& bl) override; void init_connection(bufferlist& bl) override; public: OpsLogSocket(CephContext *cct, uint64_t _backlog); }; class OpsLogRados : public OpsLogSink { // main()'s driver pointer as a reference, possibly modified by RGWRealmReloader rgw::sal::Driver* const& driver; public: OpsLogRados(rgw::sal::Driver* const& driver); int log(req_state* s, struct rgw_log_entry& entry) override; }; class RGWREST; int rgw_log_op(RGWREST* const rest, struct req_state* s, const RGWOp* op, OpsLogSink* olog); void rgw_log_usage_init(CephContext* cct, rgw::sal::Driver* driver); void rgw_log_usage_finalize(); void rgw_format_ops_log_entry(struct rgw_log_entry& entry, ceph::Formatter *formatter);
7,535
24.986207
98
h
null
ceph-main/src/rgw/rgw_lua_background.h
#pragma once #include "common/dout.h" #include "rgw_common.h" #include <string> #include <unordered_map> #include <variant> #include "rgw_lua_utils.h" #include "rgw_realm_reloader.h" namespace rgw::lua { //Interval between each execution of the script is set to 5 seconds constexpr const int INIT_EXECUTE_INTERVAL = 5; //Writeable meta table named RGW with mutex protection using BackgroundMapValue = std::variant<std::string, long long int, double, bool>; using BackgroundMap = std::unordered_map<std::string, BackgroundMapValue>; struct RGWTable : EmptyMetaTable { static const char* INCREMENT; static const char* DECREMENT; static std::string TableName() {return "RGW";} static std::string Name() {return TableName() + "Meta";} static int increment_by(lua_State* L); static int IndexClosure(lua_State* L) { const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL))); auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL))); const char* index = luaL_checkstring(L, 2); if (strcasecmp(index, INCREMENT) == 0) { lua_pushlightuserdata(L, map); lua_pushlightuserdata(L, &mtx); lua_pushboolean(L, false /*increment*/); lua_pushcclosure(L, increment_by, THREE_UPVALS); return ONE_RETURNVAL; } if (strcasecmp(index, DECREMENT) == 0) { lua_pushlightuserdata(L, map); lua_pushlightuserdata(L, &mtx); lua_pushboolean(L, true /*decrement*/); lua_pushcclosure(L, increment_by, THREE_UPVALS); return ONE_RETURNVAL; } std::lock_guard l(mtx); const auto it = map->find(std::string(index)); if (it == map->end()) { lua_pushnil(L); } else { std::visit([L](auto&& value) { pushvalue(L, value); }, it->second); } return ONE_RETURNVAL; } static int LenClosure(lua_State* L) { const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL))); auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL))); std::lock_guard l(mtx); lua_pushinteger(L, map->size()); return ONE_RETURNVAL; } static int NewIndexClosure(lua_State* L) { const auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL))); auto& mtx = *reinterpret_cast<std::mutex*>(lua_touserdata(L, lua_upvalueindex(SECOND_UPVAL))); const auto index = luaL_checkstring(L, 2); if (strcasecmp(index, INCREMENT) == 0 || strcasecmp(index, DECREMENT) == 0) { return luaL_error(L, "increment/decrement are reserved function names for RGW"); } std::unique_lock l(mtx); size_t len; BackgroundMapValue value; const int value_type = lua_type(L, 3); switch (value_type) { case LUA_TNIL: // erase the element. since in lua: "t[index] = nil" is removing the entry at "t[index]" if (const auto it = map->find(index); it != map->end()) { // index was found update_erased_iterator<BackgroundMap>(L, it, map->erase(it)); } return NO_RETURNVAL; case LUA_TBOOLEAN: value = static_cast<bool>(lua_toboolean(L, 3)); len = sizeof(bool); break; case LUA_TNUMBER: if (lua_isinteger(L, 3)) { value = lua_tointeger(L, 3); len = sizeof(long long int); } else { value = lua_tonumber(L, 3); len = sizeof(double); } break; case LUA_TSTRING: { const auto str = lua_tolstring(L, 3, &len); value = std::string{str, len}; break; } default: l.unlock(); return luaL_error(L, "unsupported value type for RGW table"); } if (len + strnlen(index, MAX_LUA_VALUE_SIZE) > MAX_LUA_VALUE_SIZE) { return luaL_error(L, "Lua maximum size of entry limit exceeded"); } else if (map->size() > MAX_LUA_KEY_ENTRIES) { l.unlock(); return luaL_error(L, "Lua max number of entries limit exceeded"); } else { map->insert_or_assign(index, value); } return NO_RETURNVAL; } static int PairsClosure(lua_State* L) { auto map = reinterpret_cast<BackgroundMap*>(lua_touserdata(L, lua_upvalueindex(FIRST_UPVAL))); lua_pushlightuserdata(L, map); lua_pushcclosure(L, next<BackgroundMap>, ONE_UPVAL); // push the stateless iterator function lua_pushnil(L); // indicate this is the first call // return next(), nil return TWO_RETURNVALS; } }; class Background : public RGWRealmReloader::Pauser { public: static const BackgroundMapValue empty_table_value; private: BackgroundMap rgw_map; bool stopped = false; bool started = false; bool paused = false; int execute_interval; const DoutPrefix dp; std::unique_ptr<rgw::sal::LuaManager> lua_manager; CephContext* const cct; const std::string luarocks_path; std::thread runner; mutable std::mutex table_mutex; std::mutex cond_mutex; std::mutex pause_mutex; std::condition_variable cond; void run(); protected: std::string rgw_script; virtual int read_script(); public: Background(rgw::sal::Driver* driver, CephContext* cct, const std::string& luarocks_path, int execute_interval = INIT_EXECUTE_INTERVAL); virtual ~Background() = default; void start(); void shutdown(); void create_background_metatable(lua_State* L); const BackgroundMapValue& get_table_value(const std::string& key) const; template<typename T> void put_table_value(const std::string& key, T value) { std::unique_lock cond_lock(table_mutex); rgw_map[key] = value; } void pause() override; void resume(rgw::sal::Driver* _driver) override; }; } //namepsace rgw::lua
5,848
29.784211
104
h
null
ceph-main/src/rgw/rgw_main.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <vector> #include <map> #include <string> #include "rgw_common.h" #include "rgw_rest.h" #include "rgw_frontend.h" #include "rgw_period_pusher.h" #include "rgw_realm_reloader.h" #include "rgw_ldap.h" #include "rgw_lua.h" #include "rgw_dmclock_scheduler_ctx.h" #include "rgw_ratelimit.h" class RGWPauser : public RGWRealmReloader::Pauser { std::vector<Pauser*> pausers; public: ~RGWPauser() override = default; void add_pauser(Pauser* pauser) { pausers.push_back(pauser); } void pause() override { std::for_each(pausers.begin(), pausers.end(), [](Pauser* p){p->pause();}); } void resume(rgw::sal::Driver* driver) override { std::for_each(pausers.begin(), pausers.end(), [driver](Pauser* p){p->resume(driver);}); } }; namespace rgw { namespace lua { class Background; } namespace sal { class ConfigStore; } class RGWLib; class AppMain { /* several components should be initalized only if librgw is * also serving HTTP */ bool have_http_frontend{false}; bool nfs{false}; std::vector<RGWFrontend*> fes; std::vector<RGWFrontendConfig*> fe_configs; std::multimap<string, RGWFrontendConfig*> fe_map; std::unique_ptr<rgw::LDAPHelper> ldh; OpsLogSink* olog = nullptr; RGWREST rest; std::unique_ptr<rgw::lua::Background> lua_background; std::unique_ptr<rgw::auth::ImplicitTenants> implicit_tenant_context; std::unique_ptr<rgw::dmclock::SchedulerCtx> sched_ctx; std::unique_ptr<ActiveRateLimiter> ratelimiter; std::map<std::string, std::string> service_map_meta; // wow, realm reloader has a lot of parts std::unique_ptr<RGWRealmReloader> reloader; std::unique_ptr<RGWPeriodPusher> pusher; std::unique_ptr<RGWFrontendPauser> fe_pauser; std::unique_ptr<RGWRealmWatcher> realm_watcher; std::unique_ptr<RGWPauser> rgw_pauser; std::unique_ptr<sal::ConfigStore> cfgstore; SiteConfig site; const DoutPrefixProvider* dpp; RGWProcessEnv env; public: AppMain(const DoutPrefixProvider* dpp); ~AppMain(); void shutdown(std::function<void(void)> finalize_async_signals = []() { /* nada */}); sal::ConfigStore* get_config_store() const { return cfgstore.get(); } rgw::sal::Driver* get_driver() { return env.driver; } rgw::LDAPHelper* get_ldh() { return ldh.get(); } void init_frontends1(bool nfs = false); void init_numa(); int init_storage(); void init_perfcounters(); void init_http_clients(); void cond_init_apis(); void init_ldap(); void init_opslog(); int init_frontends2(RGWLib* rgwlib = nullptr); void init_tracepoints(); void init_notification_endpoints(); void init_lua(); bool have_http() { return have_http_frontend; } static OpsLogFile* ops_log_file; }; /* AppMain */ } // namespace rgw static inline RGWRESTMgr *set_logging(RGWRESTMgr* mgr) { mgr->set_logging(true); return mgr; } static inline RGWRESTMgr *rest_filter(rgw::sal::Driver* driver, int dialect, RGWRESTMgr* orig) { RGWSyncModuleInstanceRef sync_module = driver->get_sync_module(); if (sync_module) { return sync_module->get_rest_filter(dialect, orig); } else { return orig; } }
3,556
24.407143
94
h
null
ceph-main/src/rgw/rgw_meta_sync_status.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string> #include "common/ceph_time.h" struct rgw_meta_sync_info { enum SyncState { StateInit = 0, StateBuildingFullSyncMaps = 1, StateSync = 2, }; uint16_t state; uint32_t num_shards; std::string period; //< period id of current metadata log epoch_t realm_epoch = 0; //< realm epoch of period void encode(bufferlist& bl) const { ENCODE_START(2, 1, bl); encode(state, bl); encode(num_shards, bl); encode(period, bl); encode(realm_epoch, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(state, bl); decode(num_shards, bl); if (struct_v >= 2) { decode(period, bl); decode(realm_epoch, bl); } DECODE_FINISH(bl); } void decode_json(JSONObj *obj); void dump(Formatter *f) const; static void generate_test_instances(std::list<rgw_meta_sync_info*>& ls); rgw_meta_sync_info() : state((int)StateInit), num_shards(0) {} }; WRITE_CLASS_ENCODER(rgw_meta_sync_info) struct rgw_meta_sync_marker { enum SyncState { FullSync = 0, IncrementalSync = 1, }; uint16_t state; std::string marker; std::string next_step_marker; uint64_t total_entries; uint64_t pos; real_time timestamp; epoch_t realm_epoch{0}; //< realm_epoch of period marker rgw_meta_sync_marker() : state(FullSync), total_entries(0), pos(0) {} void encode(bufferlist& bl) const { ENCODE_START(2, 1, bl); encode(state, bl); encode(marker, bl); encode(next_step_marker, bl); encode(total_entries, bl); encode(pos, bl); encode(timestamp, bl); encode(realm_epoch, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(2, bl); decode(state, bl); decode(marker, bl); decode(next_step_marker, bl); decode(total_entries, bl); decode(pos, bl); decode(timestamp, bl); if (struct_v >= 2) { decode(realm_epoch, bl); } DECODE_FINISH(bl); } void decode_json(JSONObj *obj); void dump(Formatter *f) const; static void generate_test_instances(std::list<rgw_meta_sync_marker*>& ls); }; WRITE_CLASS_ENCODER(rgw_meta_sync_marker) struct rgw_meta_sync_status { rgw_meta_sync_info sync_info; std::map<uint32_t, rgw_meta_sync_marker> sync_markers; rgw_meta_sync_status() {} void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(sync_info, bl); encode(sync_markers, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(sync_info, bl); decode(sync_markers, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<rgw_meta_sync_status*>& ls); }; WRITE_CLASS_ENCODER(rgw_meta_sync_status)
2,955
23.229508
76
h
null
ceph-main/src/rgw/rgw_multi.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <map> #include "rgw_xml.h" #include "rgw_obj_types.h" #include "rgw_obj_manifest.h" #include "rgw_compression_types.h" #include "common/dout.h" #include "rgw_sal_fwd.h" #define MULTIPART_UPLOAD_ID_PREFIX_LEGACY "2/" #define MULTIPART_UPLOAD_ID_PREFIX "2~" // must contain a unique char that may not come up in gen_rand_alpha() class RGWMultiCompleteUpload : public XMLObj { public: RGWMultiCompleteUpload() {} ~RGWMultiCompleteUpload() override {} bool xml_end(const char *el) override; std::map<int, std::string> parts; }; class RGWMultiPart : public XMLObj { std::string etag; int num; public: RGWMultiPart() : num(0) {} ~RGWMultiPart() override {} bool xml_end(const char *el) override; std::string& get_etag() { return etag; } int get_num() { return num; } }; class RGWMultiPartNumber : public XMLObj { public: RGWMultiPartNumber() {} ~RGWMultiPartNumber() override {} }; class RGWMultiETag : public XMLObj { public: RGWMultiETag() {} ~RGWMultiETag() override {} }; class RGWMultiXMLParser : public RGWXMLParser { XMLObj *alloc_obj(const char *el) override; public: RGWMultiXMLParser() {} virtual ~RGWMultiXMLParser() override; }; extern bool is_v2_upload_id(const std::string& upload_id);
1,368
20.730159
110
h
null
ceph-main/src/rgw/rgw_notify_event_type.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <string> #include <vector> namespace rgw::notify { enum EventType { ObjectCreated = 0xF, ObjectCreatedPut = 0x1, ObjectCreatedPost = 0x2, ObjectCreatedCopy = 0x4, ObjectCreatedCompleteMultipartUpload = 0x8, ObjectRemoved = 0xF0, ObjectRemovedDelete = 0x10, ObjectRemovedDeleteMarkerCreated = 0x20, // lifecycle events (RGW extension) ObjectLifecycle = 0xFF00, ObjectExpiration = 0xF00, ObjectExpirationCurrent = 0x100, ObjectExpirationNoncurrent = 0x200, ObjectExpirationDeleteMarker = 0x400, ObjectExpirationAbortMPU = 0x800, ObjectTransition = 0xF000, ObjectTransitionCurrent = 0x1000, ObjectTransitionNoncurrent = 0x2000, ObjectSynced = 0xF0000, ObjectSyncedCreate = 0x10000, ObjectSyncedDelete = 0x20000, ObjectSyncedDeletionMarkerCreated = 0x40000, UnknownEvent = 0x100000 }; using EventTypeList = std::vector<EventType>; // two event types are considered equal if their bits intersect bool operator==(EventType lhs, EventType rhs); std::string to_string(EventType t); std::string to_event_string(EventType t); EventType from_string(const std::string& s); // create a vector of event types from comma separated list of event types void from_string_list(const std::string& string_list, EventTypeList& event_list); }
1,803
35.08
83
h
null
ceph-main/src/rgw/rgw_obj_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_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_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_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.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.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.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_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.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.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_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_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_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.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_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_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_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.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.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.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_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.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_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.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.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.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_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_signal.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 signal { void signal_shutdown(); void wait_shutdown(); int signal_fd_init(); void signal_fd_finalize(); void handle_sigterm(int signum); void handle_sigterm(int signum); void sighup_handler(int signum); } // namespace signal } // namespace rgw
699
20.875
70
h
null
ceph-main/src/rgw/rgw_string.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 <stdlib.h> #include <limits.h> #include <string_view> #include <string> #include <stdexcept> #include <boost/container/small_vector.hpp> struct ltstr_nocase { bool operator()(const std::string& s1, const std::string& s2) const { return strcasecmp(s1.c_str(), s2.c_str()) < 0; } }; static inline int stringcasecmp(const std::string& s1, const std::string& s2) { return strcasecmp(s1.c_str(), s2.c_str()); } static inline int stringcasecmp(const std::string& s1, const char *s2) { return strcasecmp(s1.c_str(), s2); } static inline int stringcasecmp(const std::string& s1, int ofs, int size, const std::string& s2) { return strncasecmp(s1.c_str() + ofs, s2.c_str(), size); } static inline int stringtoll(const std::string& s, int64_t *val) { char *end; long long result = strtoll(s.c_str(), &end, 10); if (result == LLONG_MAX) return -EINVAL; if (*end) return -EINVAL; *val = (int64_t)result; return 0; } static inline int stringtoull(const std::string& s, uint64_t *val) { char *end; unsigned long long result = strtoull(s.c_str(), &end, 10); if (result == ULLONG_MAX) return -EINVAL; if (*end) return -EINVAL; *val = (uint64_t)result; return 0; } static inline int stringtol(const std::string& s, int32_t *val) { char *end; long result = strtol(s.c_str(), &end, 10); if (result == LONG_MAX) return -EINVAL; if (*end) return -EINVAL; *val = (int32_t)result; return 0; } static inline int stringtoul(const std::string& s, uint32_t *val) { char *end; unsigned long result = strtoul(s.c_str(), &end, 10); if (result == ULONG_MAX) return -EINVAL; if (*end) return -EINVAL; *val = (uint32_t)result; return 0; } /* A converter between std::string_view and null-terminated C-strings. * It copies memory while trying to utilize the local memory instead of * issuing dynamic allocations. */ template<std::size_t N = 128> static inline boost::container::small_vector<char, N> sview2cstr(const std::string_view& sv) { boost::container::small_vector<char, N> cstr; cstr.reserve(sv.size() + sizeof('\0')); cstr.assign(std::begin(sv), std::end(sv)); cstr.push_back('\0'); return cstr; } /* std::strlen() isn't guaranteed to be computable at compile-time. Although * newer GCCs actually do that, Clang doesn't. Please be aware this function * IS NOT A DROP-IN REPLACEMENT FOR STRLEN -- it returns a different result * for strings having \0 in the middle. */ template<size_t N> static inline constexpr size_t sarrlen(const char (&arr)[N]) { return N - 1; } namespace detail { // variadic sum() to add up string lengths for reserve() static inline constexpr size_t sum() { return 0; } template <typename... Args> constexpr size_t sum(size_t v, Args... args) { return v + sum(args...); } // traits for string_size() template <typename T> struct string_traits { static constexpr size_t size(const T& s) { return s.size(); } }; // specializations for char*/const char* use strlen() template <> struct string_traits<const char*> { static size_t size(const char* s) { return std::strlen(s); } }; template <> struct string_traits<char*> : string_traits<const char*> {}; // constexpr specializations for char[]/const char[] template <std::size_t N> struct string_traits<const char[N]> { static constexpr size_t size_(const char* s, size_t i) { return i < N ? (*(s + i) == '\0' ? i : size_(s, i + 1)) : throw std::invalid_argument("Unterminated string constant."); } static constexpr size_t size(const char(&s)[N]) { return size_(s, 0); } }; template <std::size_t N> struct string_traits<char[N]> : string_traits<const char[N]> {}; // helpers for string_cat_reserve() static inline void append_to(std::string& s) {} template <typename... Args> void append_to(std::string& s, const std::string_view& v, const Args&... args) { s.append(v.begin(), v.end()); append_to(s, args...); } // helpers for string_join_reserve() static inline void join_next(std::string& s, const std::string_view& d) {} template <typename... Args> void join_next(std::string& s, const std::string_view& d, const std::string_view& v, const Args&... args) { s.append(d.begin(), d.end()); s.append(v.begin(), v.end()); join_next(s, d, args...); } static inline void join(std::string& s, const std::string_view& d) {} template <typename... Args> void join(std::string& s, const std::string_view& d, const std::string_view& v, const Args&... args) { s.append(v.begin(), v.end()); join_next(s, d, args...); } } // namespace detail /// return the length of a c string, string literal, or string type template <typename T> constexpr size_t string_size(const T& s) { return detail::string_traits<T>::size(s); } /// concatenates the given string arguments, returning as a std::string that /// gets preallocated with reserve() template <typename... Args> std::string string_cat_reserve(const Args&... args) { size_t total_size = detail::sum(string_size(args)...); std::string result; result.reserve(total_size); detail::append_to(result, args...); return result; } /// joins the given string arguments with a delimiter, returning as a /// std::string that gets preallocated with reserve() template <typename... Args> std::string string_join_reserve(const std::string_view& delim, const Args&... args) { size_t delim_size = delim.size() * std::max<ssize_t>(0, sizeof...(args) - 1); size_t total_size = detail::sum(string_size(args)...) + delim_size; std::string result; result.reserve(total_size); detail::join(result, delim, args...); return result; } template <typename... Args> std::string string_join_reserve(char delim, const Args&... args) { return string_join_reserve(std::string_view{&delim, 1}, args...); } /// use case-insensitive comparison in match_wildcards() static constexpr uint32_t MATCH_CASE_INSENSITIVE = 0x01; /// attempt to match the given input string with the pattern, which may contain /// the wildcard characters * and ? extern bool match_wildcards(std::string_view pattern, std::string_view input, uint32_t flags = 0);
6,357
25.940678
96
h
null
ceph-main/src/rgw/rgw_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_role.h" #include "rgw_auth.h" #include "rgw_web_idp.h" namespace STS { class AssumeRoleRequestBase { protected: static constexpr uint64_t MIN_POLICY_SIZE = 1; static constexpr uint64_t MAX_POLICY_SIZE = 2048; static constexpr uint64_t DEFAULT_DURATION_IN_SECS = 3600; static constexpr uint64_t MIN_ROLE_ARN_SIZE = 2; static constexpr uint64_t MAX_ROLE_ARN_SIZE = 2048; static constexpr uint64_t MIN_ROLE_SESSION_SIZE = 2; static constexpr uint64_t MAX_ROLE_SESSION_SIZE = 64; uint64_t MIN_DURATION_IN_SECS; uint64_t MAX_DURATION_IN_SECS; CephContext* cct; uint64_t duration; std::string err_msg; std::string iamPolicy; std::string roleArn; std::string roleSessionName; public: AssumeRoleRequestBase(CephContext* cct, const std::string& duration, const std::string& iamPolicy, const std::string& roleArn, const std::string& roleSessionName); const std::string& getRoleARN() const { return roleArn; } const std::string& getRoleSessionName() const { return roleSessionName; } const std::string& getPolicy() const {return iamPolicy; } static const uint64_t& getMaxPolicySize() { return MAX_POLICY_SIZE; } void setMaxDuration(const uint64_t& maxDuration) { MAX_DURATION_IN_SECS = maxDuration; } const uint64_t& getDuration() const { return duration; } int validate_input(const DoutPrefixProvider *dpp) const; }; class AssumeRoleWithWebIdentityRequest : public AssumeRoleRequestBase { static constexpr uint64_t MIN_PROVIDER_ID_LEN = 4; static constexpr uint64_t MAX_PROVIDER_ID_LEN = 2048; std::string providerId; std::string iamPolicy; std::string iss; std::string sub; std::string aud; std::vector<std::pair<std::string,std::string>> session_princ_tags; public: AssumeRoleWithWebIdentityRequest( CephContext* cct, const std::string& duration, const std::string& providerId, const std::string& iamPolicy, const std::string& roleArn, const std::string& roleSessionName, const std::string& iss, const std::string& sub, const std::string& aud, std::vector<std::pair<std::string,std::string>> session_princ_tags) : AssumeRoleRequestBase(cct, duration, iamPolicy, roleArn, roleSessionName), providerId(providerId), iss(iss), sub(sub), aud(aud), session_princ_tags(session_princ_tags) {} const std::string& getProviderId() const { return providerId; } const std::string& getIss() const { return iss; } const std::string& getAud() const { return aud; } const std::string& getSub() const { return sub; } const std::vector<std::pair<std::string,std::string>>& getPrincipalTags() const { return session_princ_tags; } int validate_input(const DoutPrefixProvider *dpp) const; }; class AssumeRoleRequest : public AssumeRoleRequestBase { static constexpr uint64_t MIN_EXTERNAL_ID_LEN = 2; static constexpr uint64_t MAX_EXTERNAL_ID_LEN = 1224; static constexpr uint64_t MIN_SERIAL_NUMBER_SIZE = 9; static constexpr uint64_t MAX_SERIAL_NUMBER_SIZE = 256; static constexpr uint64_t TOKEN_CODE_SIZE = 6; std::string externalId; std::string serialNumber; std::string tokenCode; public: AssumeRoleRequest(CephContext* cct, const std::string& duration, const std::string& externalId, const std::string& iamPolicy, const std::string& roleArn, const std::string& roleSessionName, const std::string& serialNumber, const std::string& tokenCode) : AssumeRoleRequestBase(cct, duration, iamPolicy, roleArn, roleSessionName), externalId(externalId), serialNumber(serialNumber), tokenCode(tokenCode){} int validate_input(const DoutPrefixProvider *dpp) const; }; class GetSessionTokenRequest { protected: static constexpr uint64_t MIN_DURATION_IN_SECS = 900; static constexpr uint64_t DEFAULT_DURATION_IN_SECS = 3600; uint64_t duration; std::string serialNumber; std::string tokenCode; public: GetSessionTokenRequest(const std::string& duration, const std::string& serialNumber, const std::string& tokenCode); const uint64_t& getDuration() const { return duration; } static const uint64_t& getMinDuration() { return MIN_DURATION_IN_SECS; } }; class AssumedRoleUser { std::string arn; std::string assumeRoleId; public: int generateAssumedRoleUser( CephContext* cct, rgw::sal::Driver* driver, const std::string& roleId, const rgw::ARN& roleArn, const std::string& roleSessionName); const std::string& getARN() const { return arn; } const std::string& getAssumeRoleId() const { return assumeRoleId; } void dump(Formatter *f) const; }; struct SessionToken { std::string access_key_id; std::string secret_access_key; std::string expiration; std::string policy; std::string roleId; rgw_user user; std::string acct_name; uint32_t perm_mask; bool is_admin; uint32_t acct_type; std::string role_session; std::vector<std::string> token_claims; std::string issued_at; std::vector<std::pair<std::string,std::string>> principal_tags; SessionToken() {} void encode(bufferlist& bl) const { ENCODE_START(5, 1, bl); encode(access_key_id, bl); encode(secret_access_key, bl); encode(expiration, bl); encode(policy, bl); encode(roleId, bl); encode(user, bl); encode(acct_name, bl); encode(perm_mask, bl); encode(is_admin, bl); encode(acct_type, bl); encode(role_session, bl); encode(token_claims, bl); encode(issued_at, bl); encode(principal_tags, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(5, bl); decode(access_key_id, bl); decode(secret_access_key, bl); decode(expiration, bl); decode(policy, bl); decode(roleId, bl); decode(user, bl); decode(acct_name, bl); decode(perm_mask, bl); decode(is_admin, bl); decode(acct_type, bl); if (struct_v >= 2) { decode(role_session, bl); } if (struct_v >= 3) { decode(token_claims, bl); } if (struct_v >= 4) { decode(issued_at, bl); } if (struct_v >= 5) { decode(principal_tags, bl); } DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(SessionToken) class Credentials { static constexpr int MAX_ACCESS_KEY_LEN = 20; static constexpr int MAX_SECRET_KEY_LEN = 40; std::string accessKeyId; std::string expiration; std::string secretAccessKey; std::string sessionToken; public: int generateCredentials(const DoutPrefixProvider *dpp, CephContext* cct, const uint64_t& duration, const boost::optional<std::string>& policy, const boost::optional<std::string>& roleId, const boost::optional<std::string>& role_session, const boost::optional<std::vector<std::string>>& token_claims, const boost::optional<std::vector<std::pair<std::string,std::string>>>& session_princ_tags, boost::optional<rgw_user> user, rgw::auth::Identity* identity); const std::string& getAccessKeyId() const { return accessKeyId; } const std::string& getExpiration() const { return expiration; } const std::string& getSecretAccessKey() const { return secretAccessKey; } const std::string& getSessionToken() const { return sessionToken; } void dump(Formatter *f) const; }; struct AssumeRoleResponse { int retCode; AssumedRoleUser user; Credentials creds; uint64_t packedPolicySize; }; struct AssumeRoleWithWebIdentityResponse { AssumeRoleResponse assumeRoleResp; std::string aud; std::string providerId; std::string sub; }; using AssumeRoleResponse = struct AssumeRoleResponse ; using GetSessionTokenResponse = std::tuple<int, Credentials>; using AssumeRoleWithWebIdentityResponse = struct AssumeRoleWithWebIdentityResponse; class STSService { CephContext* cct; rgw::sal::Driver* driver; rgw_user user_id; std::unique_ptr<rgw::sal::RGWRole> role; rgw::auth::Identity* identity; public: STSService() = default; STSService(CephContext* cct, rgw::sal::Driver* driver, rgw_user user_id, rgw::auth::Identity* identity) : cct(cct), driver(driver), user_id(user_id), identity(identity) {} std::tuple<int, rgw::sal::RGWRole*> getRoleInfo(const DoutPrefixProvider *dpp, const std::string& arn, optional_yield y); AssumeRoleResponse assumeRole(const DoutPrefixProvider *dpp, AssumeRoleRequest& req, optional_yield y); GetSessionTokenResponse getSessionToken(const DoutPrefixProvider *dpp, GetSessionTokenRequest& req); AssumeRoleWithWebIdentityResponse assumeRoleWithWebIdentity(const DoutPrefixProvider *dpp, AssumeRoleWithWebIdentityRequest& req); }; }
9,296
35.892857
132
h
null
ceph-main/src/rgw/rgw_swift_auth.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_user.h" #include "rgw_op.h" #include "rgw_rest.h" #include "rgw_auth.h" #include "rgw_auth_keystone.h" #include "rgw_auth_filters.h" #include "rgw_sal.h" #define RGW_SWIFT_TOKEN_EXPIRATION (15 * 60) namespace rgw { namespace auth { namespace swift { /* TempURL: applier. */ class TempURLApplier : public rgw::auth::LocalApplier { public: TempURLApplier(CephContext* const cct, const RGWUserInfo& user_info) : LocalApplier(cct, user_info, LocalApplier::NO_SUBUSER, std::nullopt, LocalApplier::NO_ACCESS_KEY) { }; void modify_request_state(const DoutPrefixProvider* dpp, req_state * s) const override; /* in/out */ void write_ops_log_entry(rgw_log_entry& entry) const override; struct Factory { virtual ~Factory() {} virtual aplptr_t create_apl_turl(CephContext* cct, const req_state* s, const RGWUserInfo& user_info) const = 0; }; }; /* TempURL: engine */ class TempURLEngine : public rgw::auth::Engine { using result_t = rgw::auth::Engine::result_t; CephContext* const cct; rgw::sal::Driver* driver; const TempURLApplier::Factory* const apl_factory; /* Helper methods. */ void get_owner_info(const DoutPrefixProvider* dpp, const req_state* s, RGWUserInfo& owner_info, optional_yield y) const; std::string convert_from_iso8601(std::string expires) const; bool is_applicable(const req_state* s) const noexcept; bool is_expired(const std::string& expires) const; bool is_disallowed_header_present(const req_info& info) const; class SignatureHelper; class PrefixableSignatureHelper; public: TempURLEngine(CephContext* const cct, rgw::sal::Driver* _driver , const TempURLApplier::Factory* const apl_factory) : cct(cct), driver(_driver), apl_factory(apl_factory) { } /* Interface implementations. */ const char* get_name() const noexcept override { return "rgw::auth::swift::TempURLEngine"; } result_t authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const override; }; /* AUTH_rgwtk */ class SignedTokenEngine : public rgw::auth::Engine { using result_t = rgw::auth::Engine::result_t; CephContext* const cct; rgw::sal::Driver* driver; const rgw::auth::TokenExtractor* const extractor; const rgw::auth::LocalApplier::Factory* const apl_factory; bool is_applicable(const std::string& token) const noexcept; using rgw::auth::Engine::authenticate; result_t authenticate(const DoutPrefixProvider* dpp, const std::string& token, const req_state* s) const; public: SignedTokenEngine(CephContext* const cct, rgw::sal::Driver* _driver, const rgw::auth::TokenExtractor* const extractor, const rgw::auth::LocalApplier::Factory* const apl_factory) : cct(cct), driver(_driver), extractor(extractor), apl_factory(apl_factory) { } const char* get_name() const noexcept override { return "rgw::auth::swift::SignedTokenEngine"; } result_t authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const override { return authenticate(dpp, extractor->get_token(s), s); } }; /* External token */ class ExternalTokenEngine : public rgw::auth::Engine { using result_t = rgw::auth::Engine::result_t; CephContext* const cct; rgw::sal::Driver* driver; const rgw::auth::TokenExtractor* const extractor; const rgw::auth::LocalApplier::Factory* const apl_factory; bool is_applicable(const std::string& token) const noexcept; result_t authenticate(const DoutPrefixProvider* dpp, const std::string& token, const req_state* s, optional_yield y) const; public: ExternalTokenEngine(CephContext* const cct, rgw::sal::Driver* _driver, const rgw::auth::TokenExtractor* const extractor, const rgw::auth::LocalApplier::Factory* const apl_factory) : cct(cct), driver(_driver), extractor(extractor), apl_factory(apl_factory) { } const char* get_name() const noexcept override { return "rgw::auth::swift::ExternalTokenEngine"; } 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); } }; /* SwiftAnonymous: applier. */ class SwiftAnonymousApplier : public rgw::auth::LocalApplier { public: SwiftAnonymousApplier(CephContext* const cct, const RGWUserInfo& user_info) : LocalApplier(cct, user_info, LocalApplier::NO_SUBUSER, std::nullopt, LocalApplier::NO_ACCESS_KEY) { } bool is_admin_of(const rgw_user& uid) const {return false;} bool is_owner_of(const rgw_user& uid) const {return uid.id.compare(RGW_USER_ANON_ID) == 0;} }; class SwiftAnonymousEngine : public rgw::auth::AnonymousEngine { const rgw::auth::TokenExtractor* const extractor; bool is_applicable(const req_state* s) const noexcept override { return extractor->get_token(s).empty(); } public: SwiftAnonymousEngine(CephContext* const cct, const SwiftAnonymousApplier::Factory* const apl_factory, const rgw::auth::TokenExtractor* const extractor) : AnonymousEngine(cct, apl_factory), extractor(extractor) { } const char* get_name() const noexcept override { return "rgw::auth::swift::SwiftAnonymousEngine"; } }; class DefaultStrategy : public rgw::auth::Strategy, public rgw::auth::RemoteApplier::Factory, public rgw::auth::LocalApplier::Factory, public rgw::auth::swift::TempURLApplier::Factory { rgw::sal::Driver* driver; const ImplicitTenants& implicit_tenant_context; /* The engines. */ const rgw::auth::swift::TempURLEngine tempurl_engine; const rgw::auth::swift::SignedTokenEngine signed_engine; boost::optional <const rgw::auth::keystone::TokenEngine> keystone_engine; const rgw::auth::swift::ExternalTokenEngine external_engine; const rgw::auth::swift::SwiftAnonymousEngine anon_engine; using keystone_config_t = rgw::keystone::CephCtxConfig; using keystone_cache_t = rgw::keystone::TokenCache; using aplptr_t = rgw::auth::IdentityApplier::aplptr_t; using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t; /* The method implements TokenExtractor for X-Auth-Token present in req_state. */ struct AuthTokenExtractor : rgw::auth::TokenExtractor { std::string get_token(const req_state* const s) const override { /* Returning a reference here would end in GCC complaining about a reference * to temporary. */ return s->info.env->get("HTTP_X_AUTH_TOKEN", ""); } } auth_token_extractor; /* The method implements TokenExtractor for X-Service-Token present in req_state. */ struct ServiceTokenExtractor : rgw::auth::TokenExtractor { std::string get_token(const req_state* const s) const override { return s->info.env->get("HTTP_X_SERVICE_TOKEN", ""); } } service_token_extractor; aplptr_t create_apl_remote(CephContext* const cct, const req_state* const s, acl_strategy_t&& extra_acl_strategy, const rgw::auth::RemoteApplier::AuthInfo &info) const override { auto apl = \ rgw::auth::add_3rdparty(driver, rgw_user(s->account_name), rgw::auth::add_sysreq(cct, driver, s, rgw::auth::RemoteApplier(cct, driver, std::move(extra_acl_strategy), info, implicit_tenant_context, rgw::auth::ImplicitTenants::IMPLICIT_TENANTS_SWIFT))); /* TODO(rzarzynski): replace with static_ptr. */ return aplptr_t(new decltype(apl)(std::move(apl))); } aplptr_t create_apl_local(CephContext* const cct, const req_state* const s, const RGWUserInfo& user_info, const std::string& subuser, const std::optional<uint32_t>& perm_mask, const std::string& access_key_id) const override { auto apl = \ rgw::auth::add_3rdparty(driver, rgw_user(s->account_name), rgw::auth::add_sysreq(cct, driver, s, rgw::auth::LocalApplier(cct, user_info, subuser, perm_mask, access_key_id))); /* TODO(rzarzynski): replace with static_ptr. */ return aplptr_t(new decltype(apl)(std::move(apl))); } aplptr_t create_apl_turl(CephContext* const cct, const req_state* const s, const RGWUserInfo& user_info) const override { /* TempURL doesn't need any user account override. It's a Swift-specific * mechanism that requires account name internally, so there is no * business with delegating the responsibility outside. */ return aplptr_t(new rgw::auth::swift::TempURLApplier(cct, user_info)); } public: DefaultStrategy(CephContext* const cct, const ImplicitTenants& implicit_tenant_context, rgw::sal::Driver* _driver) : driver(_driver), implicit_tenant_context(implicit_tenant_context), tempurl_engine(cct, driver, static_cast<rgw::auth::swift::TempURLApplier::Factory*>(this)), signed_engine(cct, driver, static_cast<rgw::auth::TokenExtractor*>(&auth_token_extractor), static_cast<rgw::auth::LocalApplier::Factory*>(this)), external_engine(cct, driver, static_cast<rgw::auth::TokenExtractor*>(&auth_token_extractor), static_cast<rgw::auth::LocalApplier::Factory*>(this)), anon_engine(cct, static_cast<SwiftAnonymousApplier::Factory*>(this), static_cast<rgw::auth::TokenExtractor*>(&auth_token_extractor)) { /* 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, tempurl_engine); add_engine(Control::SUFFICIENT, signed_engine); /* The auth strategy is responsible for deciding whether a parcular * engine is disabled or not. */ if (! cct->_conf->rgw_keystone_url.empty()) { keystone_engine.emplace(cct, static_cast<rgw::auth::TokenExtractor*>(&auth_token_extractor), static_cast<rgw::auth::TokenExtractor*>(&service_token_extractor), static_cast<rgw::auth::RemoteApplier::Factory*>(this), keystone_config_t::get_instance(), keystone_cache_t::get_instance<keystone_config_t>()); add_engine(Control::SUFFICIENT, *keystone_engine); } if (! cct->_conf->rgw_swift_auth_url.empty()) { add_engine(Control::SUFFICIENT, external_engine); } add_engine(Control::SUFFICIENT, anon_engine); } const char* get_name() const noexcept override { return "rgw::auth::swift::DefaultStrategy"; } }; } /* namespace swift */ } /* namespace auth */ } /* namespace rgw */ class RGW_SWIFT_Auth_Get : public RGWOp { public: RGW_SWIFT_Auth_Get() {} ~RGW_SWIFT_Auth_Get() override {} int verify_permission(optional_yield) override { return 0; } void execute(optional_yield y) override; const char* name() const override { return "swift_auth_get"; } dmc::client_id dmclock_client() override { return dmc::client_id::auth; } }; class RGWHandler_SWIFT_Auth : public RGWHandler_REST { public: RGWHandler_SWIFT_Auth() {} ~RGWHandler_SWIFT_Auth() override {} RGWOp *op_get() override; int init(rgw::sal::Driver* driver, req_state *state, rgw::io::BasicClient *cio) override; int authorize(const DoutPrefixProvider *dpp, optional_yield y) override; int postauth_init(optional_yield) override { return 0; } int read_permissions(RGWOp *op, optional_yield) override { return 0; } virtual RGWAccessControlPolicy *alloc_policy() { return NULL; } virtual void free_policy(RGWAccessControlPolicy *policy) {} }; class RGWRESTMgr_SWIFT_Auth : public RGWRESTMgr { public: RGWRESTMgr_SWIFT_Auth() = default; ~RGWRESTMgr_SWIFT_Auth() 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 { return new RGWHandler_SWIFT_Auth; } };
13,237
36.290141
114
h
null
ceph-main/src/rgw/rgw_sync_checkpoint.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <optional> #include "common/ceph_time.h" #include "rgw_basic_types.h" class DoutPrefixProvider; namespace rgw::sal { class RadosStore; } class RGWBucketInfo; class RGWBucketSyncPolicyHandler; // poll the bucket's sync status until it's caught up against all sync sources int rgw_bucket_sync_checkpoint(const DoutPrefixProvider* dpp, rgw::sal::RadosStore* store, const RGWBucketSyncPolicyHandler& policy, const RGWBucketInfo& info, std::optional<rgw_zone_id> opt_source_zone, std::optional<rgw_bucket> opt_source_bucket, ceph::timespan retry_delay, ceph::coarse_mono_time timeout_at);
1,239
33.444444
78
h
null
ceph-main/src/rgw/rgw_tag.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 <map> class RGWObjTags { public: using tag_map_t = std::multimap <std::string, std::string>; protected: tag_map_t tag_map; uint32_t max_obj_tags{10}; static constexpr uint32_t max_tag_key_size{128}; static constexpr uint32_t max_tag_val_size{256}; public: RGWObjTags() = default; RGWObjTags(uint32_t max_obj_tags):max_obj_tags(max_obj_tags) {} void encode(bufferlist& bl) const { ENCODE_START(1,1,bl); encode(tag_map, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator &bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(tag_map,bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void add_tag(const std::string& key, const std::string& val=""); void emplace_tag(std::string&& key, std::string&& val); int check_and_add_tag(const std::string& key, const std::string& val=""); size_t count() const {return tag_map.size();} int set_from_string(const std::string& input); void clear() { tag_map.clear(); } bool empty() const noexcept { return tag_map.empty(); } const tag_map_t& get_tags() const {return tag_map;} tag_map_t& get_tags() {return tag_map;} }; WRITE_CLASS_ENCODER(RGWObjTags)
1,360
26.22
75
h
null
ceph-main/src/rgw/rgw_tar.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 <algorithm> #include <array> #include <cstring> #include <string_view> #include <tuple> #include <utility> #include <boost/optional.hpp> #include <boost/range/adaptor/reversed.hpp> namespace rgw { namespace tar { static constexpr size_t BLOCK_SIZE = 512; static inline std::pair<class StatusIndicator, boost::optional<class HeaderView>> interpret_block(const StatusIndicator& status, ceph::bufferlist& bl); class StatusIndicator { friend std::pair<class StatusIndicator, boost::optional<class HeaderView>> interpret_block(const StatusIndicator& status, ceph::bufferlist& bl); bool is_empty; bool is_eof; StatusIndicator() : is_empty(false), is_eof(false) { } StatusIndicator(const StatusIndicator& prev_status, const bool is_empty) : is_empty(is_empty), is_eof(is_empty && prev_status.empty()) { } public: bool empty() const { return is_empty; } bool eof() const { return is_eof; } static StatusIndicator create() { return StatusIndicator(); } } /* class StatusIndicator */; enum class FileType : char { UNKNOWN = '\0', /* The tar format uses ASCII encoding. */ NORMAL_FILE = '0', DIRECTORY = '5' }; /* enum class FileType */ class HeaderView { protected: /* Everything is char here (ASCII encoding), so we don't need to worry about * the struct padding. */ const struct header_t { char filename[100]; char __filemode[8]; char __owner_id[8]; char __group_id[8]; char filesize[12]; char lastmod[12]; char checksum[8]; char filetype; char __padding[355]; } *header; static_assert(sizeof(*header) == BLOCK_SIZE, "The TAR header must be exactly BLOCK_SIZE length"); /* The label is far more important from what the code really does. */ static size_t pos2len(const size_t pos) { return pos + 1; } public: explicit HeaderView(const char (&header)[BLOCK_SIZE]) : header(reinterpret_cast<const header_t*>(header)) { } FileType get_filetype() const { switch (header->filetype) { case static_cast<char>(FileType::NORMAL_FILE): return FileType::NORMAL_FILE; case static_cast<char>(FileType::DIRECTORY): return FileType::DIRECTORY; default: return FileType::UNKNOWN; } } std::string_view get_filename() const { return std::string_view(header->filename, std::min(sizeof(header->filename), strlen(header->filename))); } size_t get_filesize() const { /* The string_ref is pretty suitable here because tar encodes its * metadata in ASCII. */ const std::string_view raw(header->filesize, sizeof(header->filesize)); /* We need to find where the padding ends. */ const auto pad_ends_at = std::min(raw.find_last_not_of('\0'), raw.find_last_not_of(' ')); const auto trimmed = raw.substr(0, pad_ends_at == std::string_view::npos ? std::string_view::npos : pos2len(pad_ends_at)); size_t sum = 0, mul = 1; for (const char c : boost::adaptors::reverse(trimmed)) { sum += (c - '0') * mul; mul *= 8; } return sum; } }; /* class Header */ static inline std::pair<StatusIndicator, boost::optional<HeaderView>> interpret_block(const StatusIndicator& status, ceph::bufferlist& bl) { static constexpr std::array<char, BLOCK_SIZE> zero_block = {0, }; const char (&block)[BLOCK_SIZE] = \ reinterpret_cast<const char (&)[BLOCK_SIZE]>(*bl.c_str()); if (std::memcmp(zero_block.data(), block, BLOCK_SIZE) == 0) { return std::make_pair(StatusIndicator(status, true), boost::none); } else { return std::make_pair(StatusIndicator(status, false), HeaderView(block)); } } } /* namespace tar */ } /* namespace rgw */
4,059
25.363636
78
h
null
ceph-main/src/rgw/rgw_token.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) 2016 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 <stdint.h> #include <boost/algorithm/string.hpp> #include <sstream> #include "common/ceph_json.h" #include "common/Formatter.h" #include "rgw/rgw_b64.h" namespace rgw { using std::string; class RGWToken { public: static constexpr auto type_name = "RGW_TOKEN"; enum token_type : uint32_t { TOKEN_NONE, TOKEN_AD, TOKEN_KEYSTONE, TOKEN_LDAP, }; static enum token_type to_type(const string& s) { if (boost::iequals(s, "ad")) return TOKEN_AD; if (boost::iequals(s, "ldap")) return TOKEN_LDAP; if (boost::iequals(s, "keystone")) return TOKEN_KEYSTONE; return TOKEN_NONE; } static const char* from_type(enum token_type type) { switch (type) { case TOKEN_AD: return "ad"; case TOKEN_LDAP: return "ldap"; case TOKEN_KEYSTONE: return "keystone"; default: return "none"; }; } token_type type; string id; string key; virtual uint32_t version() const { return 1; }; bool valid() const{ return ((type != TOKEN_NONE) && (! id.empty()) && (! key.empty())); } RGWToken() : type(TOKEN_NONE) {}; RGWToken(enum token_type _type, const std::string& _id, const std::string& _key) : type(_type), id(_id), key(_key) {}; explicit RGWToken(const string& json) { JSONParser p; p.parse(json.c_str(), json.length()); JSONDecoder::decode_json(RGWToken::type_name, *this, &p); } RGWToken& operator=(const std::string& json) { JSONParser p; p.parse(json.c_str(), json.length()); JSONDecoder::decode_json(RGWToken::type_name, *this, &p); return *this; } void encode(bufferlist& bl) const { uint32_t ver = version(); string typestr{from_type(type)}; ENCODE_START(1, 1, bl); encode(type_name, bl); encode(ver, bl); encode(typestr, bl); encode(id, bl); encode(key, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { string name; string typestr; uint32_t version; DECODE_START(1, bl); decode(name, bl); decode(version, bl); decode(typestr, bl); type = to_type(typestr); decode(id, bl); decode(key, bl); DECODE_FINISH(bl); } void dump(Formatter* f) const { ::encode_json("version", uint32_t(version()), f); ::encode_json("type", from_type(type), f); ::encode_json("id", id, f); ::encode_json("key", key, f); } void encode_json(Formatter* f) { RGWToken& token = *this; f->open_object_section(type_name); ::encode_json(type_name, token, f); f->close_section(); } void decode_json(JSONObj* obj) { uint32_t version; string type_name; string typestr; JSONDecoder::decode_json("version", version, obj); JSONDecoder::decode_json("type", typestr, obj); type = to_type(typestr); JSONDecoder::decode_json("id", id, obj); JSONDecoder::decode_json("key", key, obj); } std::string encode_json_base64(Formatter* f) { encode_json(f); std::ostringstream os; f->flush(os); return to_base64(std::move(os.str())); } friend inline std::ostream& operator<<(std::ostream& os, const RGWToken& token); virtual ~RGWToken() {}; }; WRITE_CLASS_ENCODER(RGWToken) inline std::ostream& operator<<(std::ostream& os, const RGWToken& token) { os << "<<RGWToken" << " type=" << RGWToken::from_type(token.type) << " id=" << token.id << " key=" << token.key << ">>"; return os; } } /* namespace rgw */
4,088
22.912281
84
h
null
ceph-main/src/rgw/rgw_torrent.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/ceph_crypto.h" #include "common/dout.h" #include "common/async/yield_context.h" #include "rgw_putobj.h" #include "rgw_sal_fwd.h" //control characters void bencode_dict(bufferlist& bl); void bencode_list(bufferlist& bl); void bencode_end(bufferlist& bl); //key len void bencode_key(std::string_view key, bufferlist& bl); //single values void bencode(int value, bufferlist& bl); //single values void bencode(std::string_view str, bufferlist& bl); //dictionary elements void bencode(std::string_view key, int value, bufferlist& bl); //dictionary elements void bencode(std::string_view key, std::string_view value, bufferlist& bl); // read the bencoded torrent file from the given object int rgw_read_torrent_file(const DoutPrefixProvider* dpp, rgw::sal::Object* object, ceph::bufferlist &bl, optional_yield y); // PutObj filter that builds a torrent file during upload class RGWPutObj_Torrent : public rgw::putobj::Pipe { size_t max_len = 0; size_t piece_len = 0; bufferlist piece_hashes; size_t len = 0; size_t piece_offset = 0; uint32_t piece_count = 0; ceph::crypto::SHA1 digest; public: RGWPutObj_Torrent(rgw::sal::DataProcessor* next, size_t max_len, size_t piece_len); int process(bufferlist&& data, uint64_t logical_offset) override; // after processing is complete, return the bencoded torrent file bufferlist bencode_torrent(std::string_view filename) const; };
1,639
26.79661
75
h
null
ceph-main/src/rgw/rgw_tracer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "common/tracer.h" #include "rgw_common.h" namespace tracing { namespace rgw { const auto OP = "op"; const auto BUCKET_NAME = "bucket_name"; const auto USER_ID = "user_id"; const auto OBJECT_NAME = "object_name"; const auto RETURN = "return"; const auto UPLOAD_ID = "upload_id"; const auto TYPE = "type"; const auto REQUEST = "request"; const auto MULTIPART = "multipart_upload "; extern tracing::Tracer tracer; } // namespace rgw } // namespace tracing static inline void extract_span_context(const rgw::sal::Attrs& attr, jspan_context& span_ctx) { auto trace_iter = attr.find(RGW_ATTR_TRACE); if (trace_iter != attr.end()) { try { auto trace_bl_iter = trace_iter->second.cbegin(); tracing::decode(span_ctx, trace_bl_iter); } catch (buffer::error& err) {} } }
912
25.085714
95
h
null
ceph-main/src/rgw/rgw_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 <string> #include <map> #include "common/Formatter.h" #include "common/dout.h" #include "rgw_formats.h" #include "rgw_user.h" #include "rgw_sal_fwd.h" class RGWUsage { public: static int show(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, rgw::sal::User* user , rgw::sal::Bucket* bucket, uint64_t start_epoch, uint64_t end_epoch, bool show_log_entries, bool show_log_sum, std::map<std::string, bool> *categories, RGWFormatterFlusher& flusher); static int trim(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, rgw::sal::User* user , rgw::sal::Bucket* bucket, uint64_t start_epoch, uint64_t end_epoch, optional_yield y); static int clear(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, optional_yield y); };
897
27.967742
94
h
null
ceph-main/src/rgw/rgw_user_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 <string_view> #include <fmt/format.h> #include "common/dout.h" #include "common/Formatter.h" struct rgw_user { std::string tenant; std::string id; std::string ns; rgw_user() {} explicit rgw_user(const std::string& s) { from_str(s); } rgw_user(const std::string& tenant, const std::string& id, const std::string& ns="") : tenant(tenant), id(id), ns(ns) { } rgw_user(std::string&& tenant, std::string&& id, std::string&& ns="") : tenant(std::move(tenant)), id(std::move(id)), ns(std::move(ns)) { } void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(tenant, bl); encode(id, bl); encode(ns, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(tenant, bl); decode(id, bl); if (struct_v >= 2) { decode(ns, bl); } DECODE_FINISH(bl); } void to_str(std::string& str) const { if (!tenant.empty()) { if (!ns.empty()) { str = tenant + '$' + ns + '$' + id; } else { str = tenant + '$' + id; } } else if (!ns.empty()) { str = '$' + ns + '$' + id; } else { str = id; } } void clear() { tenant.clear(); id.clear(); ns.clear(); } bool empty() const { return id.empty(); } std::string to_str() const { std::string s; to_str(s); return s; } void from_str(const std::string& str) { size_t pos = str.find('$'); if (pos != std::string::npos) { tenant = str.substr(0, pos); std::string_view sv = str; std::string_view ns_id = sv.substr(pos + 1); size_t ns_pos = ns_id.find('$'); if (ns_pos != std::string::npos) { ns = std::string(ns_id.substr(0, ns_pos)); id = std::string(ns_id.substr(ns_pos + 1)); } else { ns.clear(); id = std::string(ns_id); } } else { tenant.clear(); ns.clear(); id = str; } } rgw_user& operator=(const std::string& str) { from_str(str); return *this; } int compare(const rgw_user& u) const { int r = tenant.compare(u.tenant); if (r != 0) return r; r = ns.compare(u.ns); if (r != 0) { return r; } return id.compare(u.id); } int compare(const std::string& str) const { rgw_user u(str); return compare(u); } bool operator!=(const rgw_user& rhs) const { return (compare(rhs) != 0); } bool operator==(const rgw_user& rhs) const { return (compare(rhs) == 0); } bool operator<(const rgw_user& rhs) const { if (tenant < rhs.tenant) { return true; } else if (tenant > rhs.tenant) { return false; } if (ns < rhs.ns) { return true; } else if (ns > rhs.ns) { return false; } return (id < rhs.id); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<rgw_user*>& o); }; WRITE_CLASS_ENCODER(rgw_user)
3,596
21.622642
86
h
null
ceph-main/src/rgw/rgw_web_idp.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once namespace rgw { namespace web_idp { //WebToken contains some claims from the decoded token which are of interest to us. struct WebTokenClaims { //Subject of the token std::string sub; //Intended audience for this token std::string aud; //Issuer of this token std::string iss; //Human-readable id for the resource owner std::string user_name; //Client Id std::string client_id; //azp std::string azp; }; }; /* namespace web_idp */ }; /* namespace rgw */
599
21.222222
83
h
null
ceph-main/src/rgw/rgw_website.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 Yehuda Sadeh <[email protected]> * 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 <list> #include <string> #include "common/ceph_json.h" #include "rgw_xml.h" struct RGWRedirectInfo { std::string protocol; std::string hostname; uint16_t http_redirect_code = 0; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(protocol, bl); encode(hostname, bl); encode(http_redirect_code, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(protocol, bl); decode(hostname, bl); decode(http_redirect_code, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWRedirectInfo) struct RGWBWRedirectInfo { RGWRedirectInfo redirect; std::string replace_key_prefix_with; std::string replace_key_with; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(redirect, bl); encode(replace_key_prefix_with, bl); encode(replace_key_with, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(redirect, bl); decode(replace_key_prefix_with, bl); decode(replace_key_with, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void dump_xml(Formatter *f) const; void decode_json(JSONObj *obj); void decode_xml(XMLObj *obj); }; WRITE_CLASS_ENCODER(RGWBWRedirectInfo) struct RGWBWRoutingRuleCondition { std::string key_prefix_equals; uint16_t http_error_code_returned_equals = 0; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(key_prefix_equals, bl); encode(http_error_code_returned_equals, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(key_prefix_equals, bl); decode(http_error_code_returned_equals, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void dump_xml(Formatter *f) const; void decode_json(JSONObj *obj); void decode_xml(XMLObj *obj); bool check_key_condition(const std::string& key); bool check_error_code_condition(const int error_code) { return (uint16_t)error_code == http_error_code_returned_equals; } }; WRITE_CLASS_ENCODER(RGWBWRoutingRuleCondition) struct RGWBWRoutingRule { RGWBWRoutingRuleCondition condition; RGWBWRedirectInfo redirect_info; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(condition, bl); encode(redirect_info, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(condition, bl); decode(redirect_info, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void dump_xml(Formatter *f) const; void decode_json(JSONObj *obj); void decode_xml(XMLObj *obj); bool check_key_condition(const std::string& key) { return condition.check_key_condition(key); } bool check_error_code_condition(int error_code) { return condition.check_error_code_condition(error_code); } void apply_rule(const std::string& default_protocol, const std::string& default_hostname, const std::string& key, std::string *redirect, int *redirect_code); }; WRITE_CLASS_ENCODER(RGWBWRoutingRule) struct RGWBWRoutingRules { std::list<RGWBWRoutingRule> rules; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(rules, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(rules, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void dump_xml(Formatter *f) const; void decode_json(JSONObj *obj); bool check_key_condition(const std::string& key, RGWBWRoutingRule **rule); bool check_error_code_condition(int error_code, RGWBWRoutingRule **rule); bool check_key_and_error_code_condition(const std::string& key, const int error_code, RGWBWRoutingRule **rule); }; WRITE_CLASS_ENCODER(RGWBWRoutingRules) struct RGWBucketWebsiteConf { RGWRedirectInfo redirect_all; std::string index_doc_suffix; std::string error_doc; std::string subdir_marker; std::string listing_css_doc; bool listing_enabled; bool is_redirect_all; bool is_set_index_doc; RGWBWRoutingRules routing_rules; RGWBucketWebsiteConf() : listing_enabled(false) { is_redirect_all = false; is_set_index_doc = false; } void encode(bufferlist& bl) const { ENCODE_START(2, 1, bl); encode(index_doc_suffix, bl); encode(error_doc, bl); encode(routing_rules, bl); encode(redirect_all, bl); encode(subdir_marker, bl); encode(listing_css_doc, bl); encode(listing_enabled, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(2, bl); decode(index_doc_suffix, bl); decode(error_doc, bl); decode(routing_rules, bl); decode(redirect_all, bl); if (struct_v >= 2) { decode(subdir_marker, bl); decode(listing_css_doc, bl); decode(listing_enabled, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); void decode_xml(XMLObj *obj); void dump_xml(Formatter *f) const; bool should_redirect(const std::string& key, const int http_error_code, RGWBWRoutingRule *redirect); bool get_effective_key(const std::string& key, std::string *effective_key, bool is_file) const; const std::string& get_index_doc() const { return index_doc_suffix; } bool is_empty() const { return index_doc_suffix.empty() && error_doc.empty() && subdir_marker.empty() && listing_css_doc.empty() && ! listing_enabled; } }; WRITE_CLASS_ENCODER(RGWBucketWebsiteConf)
6,407
25.262295
76
h
null
ceph-main/src/rgw/rgw_worker.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <atomic> #include "common/Thread.h" #include "common/ceph_mutex.h" #include "include/common_fwd.h" class RGWRados; class RGWRadosThread { class Worker : public Thread, public DoutPrefixProvider { CephContext *cct; RGWRadosThread *processor; ceph::mutex lock = ceph::make_mutex("RGWRadosThread::Worker"); ceph::condition_variable cond; void wait() { std::unique_lock l{lock}; cond.wait(l); }; void wait_interval(const ceph::real_clock::duration& wait_time) { std::unique_lock l{lock}; cond.wait_for(l, wait_time); } public: Worker(CephContext *_cct, RGWRadosThread *_p) : cct(_cct), processor(_p) {} void *entry() override; void signal() { std::lock_guard l{lock}; cond.notify_all(); } CephContext *get_cct() const { return cct; } unsigned get_subsys() const { return ceph_subsys_rgw; } std::ostream& gen_prefix(std::ostream& out) const { return out << "rgw rados thread: "; } }; Worker *worker; protected: CephContext *cct; RGWRados *store; std::atomic<bool> down_flag = { false }; std::string thread_name; virtual uint64_t interval_msec() = 0; virtual void stop_process() {} public: RGWRadosThread(RGWRados *_store, const std::string& thread_name = "radosgw") : worker(NULL), cct(_store->ctx()), store(_store), thread_name(thread_name) {} virtual ~RGWRadosThread() { stop(); } virtual int init(const DoutPrefixProvider *dpp) { return 0; } virtual int process(const DoutPrefixProvider *dpp) = 0; bool going_down() { return down_flag; } void start(); void stop(); void signal() { if (worker) { worker->signal(); } } };
2,124
22.097826
91
h
null
ceph-main/src/rgw/rgw_xml.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <map> #include <stdexcept> #include <string> #include <iosfwd> #include <include/types.h> #include <common/Formatter.h> class XMLObj; class RGWXMLParser; class XMLObjIter { public: typedef std::map<std::string, XMLObj *>::iterator map_iter_t; typedef std::map<std::string, XMLObj *>::iterator const_map_iter_t; XMLObjIter(); virtual ~XMLObjIter(); void set(const XMLObjIter::const_map_iter_t &_cur, const XMLObjIter::const_map_iter_t &_end); XMLObj *get_next(); bool get_name(std::string& name) const; private: map_iter_t cur; map_iter_t end; }; /** * Represents a block of XML. * Give the class an XML blob, and it will parse the blob into * an attr_name->value map. * It shouldn't be the start point for any parsing. Look at RGWXMLParser for that. */ class XMLObj { private: XMLObj *parent; std::string obj_type; protected: std::string data; std::multimap<std::string, XMLObj *> children; std::map<std::string, std::string> attr_map; // invoked at the beginning of the XML tag, and populate any attributes bool xml_start(XMLObj *parent, const char *el, const char **attr); // callback invoked at the end of the XML tag // if objects are created while parsing, this should be overwritten in the drived class virtual bool xml_end(const char *el); // callback invoked for storing the data of the XML tag // if data manipulation is needed this could be overwritten in the drived class virtual void xml_handle_data(const char *s, int len); // get the parent object XMLObj *get_parent(); // add a child XML object void add_child(const std::string& el, XMLObj *obj); public: XMLObj() : parent(nullptr) {} virtual ~XMLObj(); // get the data (as string) const std::string& get_data() const; // get the type of the object (as string) const std::string& get_obj_type() const; bool get_attr(const std::string& name, std::string& attr) const; // return a list of sub-tags matching the name XMLObjIter find(const std::string& name); // return the first sub-tag XMLObjIter find_first(); // return the first sub-tags matching the name XMLObj *find_first(const std::string& name); friend std::ostream& operator<<(std::ostream &out, const XMLObj &obj); friend RGWXMLParser; }; struct XML_ParserStruct; // an XML parser is an XML object without a parent (root of the tree) // the parser could be used in 2 ways: // // (1) lazy object creation/intrusive API: usually used within the RGWXMLDecode namespace (as RGWXMLDecode::XMLParser) // the parser will parse the input and store info, but will not generate the target object. The object can be allocated outside // of the parser (stack or heap), and require to implement the decode_xml() API for the values to be populated. // note that the decode_xml() calls may throw exceptions if parsing fails // // (2) object creation while parsing: a new class needs to be derived from RGWXMLParser and implement alloc_obj() // API that should create a set of classes derived from XMLObj implementing xml_end() to create the actual target objects // // There could be a mix-and-match of the 2 types, control over that is in the alloc_obj() call // deciding for which tags objects are allocate during parsing and for which tags object allocation is external class RGWXMLParser : public XMLObj { private: XML_ParserStruct *p; char *buf; int buf_len; XMLObj *cur_obj; std::vector<XMLObj *> objs; std::list<XMLObj *> allocated_objs; std::list<XMLObj> unallocated_objs; bool success; bool init_called; // calls xml_start() on each parsed object // passed as static callback to actual parser, passes itself as user_data static void call_xml_start(void* user_data, const char *el, const char **attr); // calls xml_end() on each parsed object // passed as static callback to actual parser, passes itself as user_data static void call_xml_end(void* user_data, const char *el); // calls xml_handle_data() on each parsed object // passed as static callback to actual parser, passes itself as user_data static void call_xml_handle_data(void* user_data, const char *s, int len); protected: // if objects are created while parsing, this should be implemented in the derived class // and be a factory for creating the classes derived from XMLObj // note that not all sub-tags has to be constructed here, any such tag which is not // constructed will be lazily created when decode_xml() is invoked on it // // note that in case of different tags sharing the same name at different levels // this method should not be used virtual XMLObj *alloc_obj(const char *el) { return nullptr; } public: RGWXMLParser(); virtual ~RGWXMLParser() override; // initialize the parser, must be called before parsing bool init(); // parse the XML buffer (can be invoked multiple times for incremental parsing) // receives the buffer to parse, its length, and boolean indication (0,1) // whether this is the final chunk of the buffer bool parse(const char *buf, int len, int done); // get the XML blob being parsed const char *get_xml() const { return buf; } }; namespace RGWXMLDecoder { struct err : std::runtime_error { using runtime_error::runtime_error; }; typedef RGWXMLParser XMLParser; template<class T> bool decode_xml(const char *name, T& val, XMLObj* obj, bool mandatory = false); template<class T> bool decode_xml(const char *name, std::vector<T>& v, XMLObj* obj, bool mandatory = false); template<class C> bool decode_xml(const char *name, C& container, void (*cb)(C&, XMLObj *obj), XMLObj *obj, bool mandatory = false); template<class T> void decode_xml(const char *name, T& val, T& default_val, XMLObj* obj); } static inline std::ostream& operator<<(std::ostream &out, RGWXMLDecoder::err& err) { return out << err.what(); } template<class T> void decode_xml_obj(T& val, XMLObj *obj) { val.decode_xml(obj); } static inline void decode_xml_obj(std::string& val, XMLObj *obj) { val = obj->get_data(); } void decode_xml_obj(unsigned long long& val, XMLObj *obj); void decode_xml_obj(long long& val, XMLObj *obj); void decode_xml_obj(unsigned long& val, XMLObj *obj); void decode_xml_obj(long& val, XMLObj *obj); void decode_xml_obj(unsigned& val, XMLObj *obj); void decode_xml_obj(int& val, XMLObj *obj); void decode_xml_obj(bool& val, XMLObj *obj); void decode_xml_obj(bufferlist& val, XMLObj *obj); class utime_t; void decode_xml_obj(utime_t& val, XMLObj *obj); template<class T> void decode_xml_obj(std::optional<T>& val, XMLObj *obj) { val.emplace(); decode_xml_obj(*val, obj); } template<class T> void do_decode_xml_obj(std::list<T>& l, const std::string& name, XMLObj *obj) { l.clear(); XMLObjIter iter = obj->find(name); XMLObj *o; while ((o = iter.get_next())) { T val; decode_xml_obj(val, o); l.push_back(val); } } template<class T> bool RGWXMLDecoder::decode_xml(const char *name, T& val, XMLObj *obj, bool mandatory) { XMLObjIter iter = obj->find(name); XMLObj *o = iter.get_next(); if (!o) { if (mandatory) { std::string s = "missing mandatory field " + std::string(name); throw err(s); } val = T(); return false; } try { decode_xml_obj(val, o); } catch (const err& e) { std::string s = std::string(name) + ": "; s.append(e.what()); throw err(s); } return true; } template<class T> bool RGWXMLDecoder::decode_xml(const char *name, std::vector<T>& v, XMLObj *obj, bool mandatory) { XMLObjIter iter = obj->find(name); XMLObj *o = iter.get_next(); v.clear(); if (!o) { if (mandatory) { std::string s = "missing mandatory field " + std::string(name); throw err(s); } return false; } do { T val; try { decode_xml_obj(val, o); } catch (const err& e) { std::string s = std::string(name) + ": "; s.append(e.what()); throw err(s); } v.push_back(val); } while ((o = iter.get_next())); return true; } template<class C> bool RGWXMLDecoder::decode_xml(const char *name, C& container, void (*cb)(C&, XMLObj *), XMLObj *obj, bool mandatory) { container.clear(); XMLObjIter iter = obj->find(name); XMLObj *o = iter.get_next(); if (!o) { if (mandatory) { std::string s = "missing mandatory field " + std::string(name); throw err(s); } return false; } try { decode_xml_obj(container, cb, o); } catch (const err& e) { std::string s = std::string(name) + ": "; s.append(e.what()); throw err(s); } return true; } template<class T> void RGWXMLDecoder::decode_xml(const char *name, T& val, T& default_val, XMLObj *obj) { XMLObjIter iter = obj->find(name); XMLObj *o = iter.get_next(); if (!o) { val = default_val; return; } try { decode_xml_obj(val, o); } catch (const err& e) { val = default_val; std::string s = std::string(name) + ": "; s.append(e.what()); throw err(s); } } template<class T> static void encode_xml(const char *name, const T& val, ceph::Formatter *f) { f->open_object_section(name); val.dump_xml(f); f->close_section(); } template<class T> static void encode_xml(const char *name, const char *ns, const T& val, ceph::Formatter *f) { f->open_object_section_in_ns(name, ns); val.dump_xml(f); f->close_section(); } void encode_xml(const char *name, const std::string& val, ceph::Formatter *f); void encode_xml(const char *name, const char *val, ceph::Formatter *f); void encode_xml(const char *name, bool val, ceph::Formatter *f); void encode_xml(const char *name, int val, ceph::Formatter *f); void encode_xml(const char *name, unsigned val, ceph::Formatter *f); void encode_xml(const char *name, long val, ceph::Formatter *f); void encode_xml(const char *name, unsigned long val, ceph::Formatter *f); void encode_xml(const char *name, long long val, ceph::Formatter *f); void encode_xml(const char *name, const utime_t& val, ceph::Formatter *f); void encode_xml(const char *name, const bufferlist& bl, ceph::Formatter *f); void encode_xml(const char *name, long long unsigned val, ceph::Formatter *f); template<class T> static void do_encode_xml(const char *name, const std::list<T>& l, const char *entry_name, ceph::Formatter *f) { f->open_array_section(name); for (typename std::list<T>::const_iterator iter = l.begin(); iter != l.end(); ++iter) { encode_xml(entry_name, *iter, f); } f->close_section(); } template<class T> static void encode_xml(const char *name, const std::vector<T>& l, ceph::Formatter *f) { for (typename std::vector<T>::const_iterator iter = l.begin(); iter != l.end(); ++iter) { encode_xml(name, *iter, f); } } template<class T> static void encode_xml(const char *name, const std::optional<T>& o, ceph::Formatter *f) { if (!o) { return; } encode_xml(name, *o, f); }
10,985
28.532258
127
h
null
ceph-main/src/rgw/rgw_zone_features.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* 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 <string> #include <boost/container/flat_set.hpp> namespace rgw::zone_features { // zone feature names inline constexpr std::string_view resharding = "resharding"; inline constexpr std::string_view compress_encrypted = "compress-encrypted"; // static list of features supported by this release inline constexpr std::initializer_list<std::string_view> supported = { resharding, compress_encrypted, }; inline constexpr bool supports(std::string_view feature) { for (auto i : supported) { if (feature.compare(i) == 0) { return true; } } return false; } // static list of features enabled by default on new zonegroups inline constexpr std::initializer_list<std::string_view> enabled = { resharding, }; // enable string_view overloads for find() contains() etc struct feature_less : std::less<std::string_view> { using is_transparent = std::true_type; }; using set = boost::container::flat_set<std::string, feature_less>; } // namespace rgw::zone_features
1,293
25.958333
76
h
null
ceph-main/src/rgw/rgw_zone_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 <set> #include <map> #include <list> #include <boost/optional.hpp> #include <fmt/format.h> #include "include/types.h" #include "rgw_bucket_layout.h" #include "rgw_zone_features.h" #include "rgw_pool_types.h" #include "rgw_acl_types.h" #include "rgw_placement_types.h" #include "common/Formatter.h" class JSONObj; namespace rgw_zone_defaults { extern std::string zone_names_oid_prefix; extern std::string region_info_oid_prefix; extern std::string realm_names_oid_prefix; extern std::string zone_group_info_oid_prefix; extern std::string realm_info_oid_prefix; extern std::string default_region_info_oid; extern std::string default_zone_group_info_oid; extern std::string region_map_oid; extern std::string default_realm_info_oid; extern std::string default_zonegroup_name; extern std::string default_zone_name; extern std::string zonegroup_names_oid_prefix; extern std::string RGW_DEFAULT_ZONE_ROOT_POOL; extern std::string RGW_DEFAULT_ZONEGROUP_ROOT_POOL; extern std::string RGW_DEFAULT_REALM_ROOT_POOL; extern std::string RGW_DEFAULT_PERIOD_ROOT_POOL; extern std::string avail_pools; extern std::string default_storage_pool_suffix; } /* namespace rgw_zone_defaults */ struct RGWNameToId { std::string obj_id; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(obj_id, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(obj_id, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWNameToId) struct RGWDefaultSystemMetaObjInfo { std::string default_id; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(default_id, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(default_id, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWDefaultSystemMetaObjInfo) struct RGWZoneStorageClass { boost::optional<rgw_pool> data_pool; boost::optional<std::string> compression_type; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(data_pool, bl); encode(compression_type, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(data_pool, bl); decode(compression_type, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWZoneStorageClass) class RGWZoneStorageClasses { std::map<std::string, RGWZoneStorageClass> m; /* in memory only */ RGWZoneStorageClass *standard_class; public: RGWZoneStorageClasses() { standard_class = &m[RGW_STORAGE_CLASS_STANDARD]; } RGWZoneStorageClasses(const RGWZoneStorageClasses& rhs) { m = rhs.m; standard_class = &m[RGW_STORAGE_CLASS_STANDARD]; } RGWZoneStorageClasses& operator=(const RGWZoneStorageClasses& rhs) { m = rhs.m; standard_class = &m[RGW_STORAGE_CLASS_STANDARD]; return *this; } const RGWZoneStorageClass& get_standard() const { return *standard_class; } bool find(const std::string& sc, const RGWZoneStorageClass** pstorage_class) const { auto iter = m.find(sc); if (iter == m.end()) { return false; } *pstorage_class = &iter->second; return true; } bool exists(const std::string& sc) const { if (sc.empty()) { return true; } auto iter = m.find(sc); return (iter != m.end()); } const std::map<std::string, RGWZoneStorageClass>& get_all() const { return m; } std::map<std::string, RGWZoneStorageClass>& get_all() { return m; } void set_storage_class(const std::string& sc, const rgw_pool* data_pool, const std::string* compression_type) { const std::string *psc = &sc; if (sc.empty()) { psc = &RGW_STORAGE_CLASS_STANDARD; } RGWZoneStorageClass& storage_class = m[*psc]; if (data_pool) { storage_class.data_pool = *data_pool; } if (compression_type) { storage_class.compression_type = *compression_type; } } void remove_storage_class(const std::string& sc) { if (!sc.empty()) { m.erase(sc); } } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(m, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(m, bl); standard_class = &m[RGW_STORAGE_CLASS_STANDARD]; DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWZoneStorageClasses) struct RGWZonePlacementInfo { rgw_pool index_pool; rgw_pool data_extra_pool; /* if not set we should use data_pool */ RGWZoneStorageClasses storage_classes; rgw::BucketIndexType index_type; bool inline_data; RGWZonePlacementInfo() : index_type(rgw::BucketIndexType::Normal), inline_data(true) {} void encode(bufferlist& bl) const { ENCODE_START(8, 1, bl); encode(index_pool.to_str(), bl); rgw_pool standard_data_pool = get_data_pool(RGW_STORAGE_CLASS_STANDARD); encode(standard_data_pool.to_str(), bl); encode(data_extra_pool.to_str(), bl); encode((uint32_t)index_type, bl); std::string standard_compression_type = get_compression_type(RGW_STORAGE_CLASS_STANDARD); encode(standard_compression_type, bl); encode(storage_classes, bl); encode(inline_data, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(8, bl); std::string index_pool_str; std::string data_pool_str; decode(index_pool_str, bl); index_pool = rgw_pool(index_pool_str); decode(data_pool_str, bl); rgw_pool standard_data_pool(data_pool_str); if (struct_v >= 4) { std::string data_extra_pool_str; decode(data_extra_pool_str, bl); data_extra_pool = rgw_pool(data_extra_pool_str); } if (struct_v >= 5) { uint32_t it; decode(it, bl); index_type = (rgw::BucketIndexType)it; } std::string standard_compression_type; if (struct_v >= 6) { decode(standard_compression_type, bl); } if (struct_v >= 7) { decode(storage_classes, bl); } else { storage_classes.set_storage_class(RGW_STORAGE_CLASS_STANDARD, &standard_data_pool, (!standard_compression_type.empty() ? &standard_compression_type : nullptr)); } if (struct_v >= 8) { decode(inline_data, bl); } DECODE_FINISH(bl); } const rgw_pool& get_data_extra_pool() const { static rgw_pool no_pool; if (data_extra_pool.empty()) { return storage_classes.get_standard().data_pool.get_value_or(no_pool); } return data_extra_pool; } const rgw_pool& get_data_pool(const std::string& sc) const { const RGWZoneStorageClass *storage_class; static rgw_pool no_pool; if (!storage_classes.find(sc, &storage_class)) { return storage_classes.get_standard().data_pool.get_value_or(no_pool); } return storage_class->data_pool.get_value_or(no_pool); } const rgw_pool& get_standard_data_pool() const { return get_data_pool(RGW_STORAGE_CLASS_STANDARD); } const std::string& get_compression_type(const std::string& sc) const { const RGWZoneStorageClass *storage_class; static std::string no_compression; if (!storage_classes.find(sc, &storage_class)) { return no_compression; } return storage_class->compression_type.get_value_or(no_compression); } bool storage_class_exists(const std::string& sc) const { return storage_classes.exists(sc); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWZonePlacementInfo) struct RGWZone { std::string id; std::string name; std::list<std::string> endpoints; // std::vector? bool log_meta; bool log_data; bool read_only; std::string tier_type; std::string redirect_zone; /** * Represents the number of shards for the bucket index object, a value of zero * indicates there is no sharding. By default (no sharding, the name of the object * is '.dir.{marker}', with sharding, the name is '.dir.{marker}.{sharding_id}', * sharding_id is zero-based value. It is not recommended to set a too large value * (e.g. thousand) as it increases the cost for bucket listing. */ uint32_t bucket_index_max_shards; // pre-shard buckets on creation to enable some write-parallism by default, // delay the need to reshard as the bucket grows, and (in multisite) get some // bucket index sharding where dynamic resharding is not supported static constexpr uint32_t default_bucket_index_max_shards = 11; bool sync_from_all; std::set<std::string> sync_from; /* list of zones to sync from */ rgw::zone_features::set supported_features; RGWZone() : log_meta(false), log_data(false), read_only(false), bucket_index_max_shards(default_bucket_index_max_shards), sync_from_all(true) {} void encode(bufferlist& bl) const { ENCODE_START(8, 1, bl); encode(name, bl); encode(endpoints, bl); encode(log_meta, bl); encode(log_data, bl); encode(bucket_index_max_shards, bl); encode(id, bl); encode(read_only, bl); encode(tier_type, bl); encode(sync_from_all, bl); encode(sync_from, bl); encode(redirect_zone, bl); encode(supported_features, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(8, bl); decode(name, bl); if (struct_v < 4) { id = name; } decode(endpoints, bl); if (struct_v >= 2) { decode(log_meta, bl); decode(log_data, bl); } if (struct_v >= 3) { decode(bucket_index_max_shards, bl); } if (struct_v >= 4) { decode(id, bl); decode(read_only, bl); } if (struct_v >= 5) { decode(tier_type, bl); } if (struct_v >= 6) { decode(sync_from_all, bl); decode(sync_from, bl); } if (struct_v >= 7) { decode(redirect_zone, bl); } if (struct_v >= 8) { decode(supported_features, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWZone*>& o); bool is_read_only() const { return read_only; } bool syncs_from(const std::string& zone_name) const { return (sync_from_all || sync_from.find(zone_name) != sync_from.end()); } bool supports(std::string_view feature) const { return supported_features.contains(feature); } }; WRITE_CLASS_ENCODER(RGWZone) struct RGWDefaultZoneGroupInfo { std::string default_zonegroup; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(default_zonegroup, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(default_zonegroup, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); //todo: implement ceph-dencoder }; WRITE_CLASS_ENCODER(RGWDefaultZoneGroupInfo) struct RGWTierACLMapping { ACLGranteeTypeEnum type{ACL_TYPE_CANON_USER}; std::string source_id; std::string dest_id; RGWTierACLMapping() = default; RGWTierACLMapping(ACLGranteeTypeEnum t, const std::string& s, const std::string& d) : type(t), source_id(s), dest_id(d) {} void init(const JSONFormattable& config) { const std::string& t = config["type"]; if (t == "email") { type = ACL_TYPE_EMAIL_USER; } else if (t == "uri") { type = ACL_TYPE_GROUP; } else { type = ACL_TYPE_CANON_USER; } source_id = config["source_id"]; dest_id = config["dest_id"]; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode((uint32_t)type, bl); encode(source_id, bl); encode(dest_id, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); uint32_t it; decode(it, bl); type = (ACLGranteeTypeEnum)it; decode(source_id, bl); decode(dest_id, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWTierACLMapping) enum HostStyle { PathStyle = 0, VirtualStyle = 1, }; struct RGWZoneGroupPlacementTierS3 { #define DEFAULT_MULTIPART_SYNC_PART_SIZE (32 * 1024 * 1024) std::string endpoint; RGWAccessKey key; std::string region; HostStyle host_style{PathStyle}; std::string target_storage_class; /* Should below be bucket/zone specific?? */ std::string target_path; std::map<std::string, RGWTierACLMapping> acl_mappings; uint64_t multipart_sync_threshold{DEFAULT_MULTIPART_SYNC_PART_SIZE}; uint64_t multipart_min_part_size{DEFAULT_MULTIPART_SYNC_PART_SIZE}; int update_params(const JSONFormattable& config); int clear_params(const JSONFormattable& config); void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(endpoint, bl); encode(key, bl); encode(region, bl); encode((uint32_t)host_style, bl); // XXX kill C-style casts encode(target_storage_class, bl); encode(target_path, bl); encode(acl_mappings, bl); encode(multipart_sync_threshold, bl); encode(multipart_min_part_size, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(endpoint, bl); decode(key, bl); decode(region, bl); uint32_t it; decode(it, bl); host_style = (HostStyle)it; // XXX can't this be HostStyle(it)? decode(target_storage_class, bl); decode(target_path, bl); decode(acl_mappings, bl); decode(multipart_sync_threshold, bl); decode(multipart_min_part_size, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWZoneGroupPlacementTierS3) struct RGWZoneGroupPlacementTier { std::string tier_type; std::string storage_class; bool retain_head_object = false; struct _tier { RGWZoneGroupPlacementTierS3 s3; } t; int update_params(const JSONFormattable& config); int clear_params(const JSONFormattable& config); void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(tier_type, bl); encode(storage_class, bl); encode(retain_head_object, bl); if (tier_type == "cloud-s3") { encode(t.s3, bl); } ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(tier_type, bl); decode(storage_class, bl); decode(retain_head_object, bl); if (tier_type == "cloud-s3") { decode(t.s3, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWZoneGroupPlacementTier) struct RGWZoneGroupPlacementTarget { std::string name; std::set<std::string> tags; std::set<std::string> storage_classes; std::map<std::string, RGWZoneGroupPlacementTier> tier_targets; bool user_permitted(const std::list<std::string>& user_tags) const { if (tags.empty()) { return true; } for (auto& rule : user_tags) { if (tags.find(rule) != tags.end()) { return true; } } return false; } void encode(bufferlist& bl) const { ENCODE_START(3, 1, bl); encode(name, bl); encode(tags, bl); encode(storage_classes, bl); encode(tier_targets, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(3, bl); decode(name, bl); decode(tags, bl); if (struct_v >= 2) { decode(storage_classes, bl); } if (storage_classes.empty()) { storage_classes.insert(RGW_STORAGE_CLASS_STANDARD); } if (struct_v >= 3) { decode(tier_targets, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWZoneGroupPlacementTarget)
16,654
25.605431
117
h
null
ceph-main/src/rgw/driver/d4n/d4n_datacache.h
#ifndef CEPH_RGWD4NCACHE_H #define CEPH_RGWD4NCACHE_H #include "rgw_common.h" #include <cpp_redis/cpp_redis> #include <string> #include <iostream> class RGWD4NCache { public: CephContext *cct; RGWD4NCache() {} RGWD4NCache(std::string cacheHost, int cachePort):host(cacheHost), port(cachePort) {} void init(CephContext *_cct) { cct = _cct; host = cct->_conf->rgw_d4n_host; port = cct->_conf->rgw_d4n_port; } int findClient(cpp_redis::client *client); int existKey(std::string key); int setObject(std::string oid, rgw::sal::Attrs* attrs); int getObject(std::string oid, rgw::sal::Attrs* newAttrs, std::vector< std::pair<std::string, std::string> >* newMetadata); int copyObject(std::string original_oid, std::string copy_oid, rgw::sal::Attrs* attrs); int delObject(std::string oid); int updateAttr(std::string oid, rgw::sal::Attrs* attr); int delAttrs(std::string oid, std::vector<std::string>& baseFields, std::vector<std::string>& deleteFields); int appendData(std::string oid, buffer::list& data); int deleteData(std::string oid); private: cpp_redis::client client; std::string host = ""; int port = 0; std::vector< std::pair<std::string, std::string> > buildObject(rgw::sal::Attrs* binary); }; #endif
1,308
30.926829
127
h
null
ceph-main/src/rgw/driver/d4n/d4n_directory.h
#ifndef CEPH_RGWD4NDIRECTORY_H #define CEPH_RGWD4NDIRECTORY_H #include "rgw_common.h" #include <cpp_redis/cpp_redis> #include <string> #include <iostream> struct cache_obj { std::string bucket_name; /* s3 bucket name */ std::string obj_name; /* s3 obj name */ }; struct cache_block { cache_obj c_obj; uint64_t size_in_bytes; /* block size_in_bytes */ std::vector<std::string> hosts_list; /* Currently not supported: list of hostnames <ip:port> of block locations */ }; class RGWDirectory { public: RGWDirectory() {} CephContext *cct; }; class RGWBlockDirectory: RGWDirectory { public: RGWBlockDirectory() {} RGWBlockDirectory(std::string blockHost, int blockPort):host(blockHost), port(blockPort) {} void init(CephContext *_cct) { cct = _cct; host = cct->_conf->rgw_d4n_host; port = cct->_conf->rgw_d4n_port; } int findClient(cpp_redis::client *client); int existKey(std::string key); int setValue(cache_block *ptr); int getValue(cache_block *ptr); int delValue(cache_block *ptr); std::string get_host() { return host; } int get_port() { return port; } private: cpp_redis::client client; std::string buildIndex(cache_block *ptr); std::string host = ""; int port = 0; }; #endif
1,294
22.981481
116
h
null
ceph-main/src/rgw/driver/dbstore/dbstore_mgr.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <map> #include <cerrno> #include <cstdlib> #include <string> #include <cstdio> #include <iostream> #include <vector> #include "common/ceph_context.h" #include "common/dbstore.h" #include "sqlite/sqliteDB.h" using namespace rgw::store; using DB = rgw::store::DB; /* XXX: Should be a dbstore config option */ const static std::string default_tenant = "default_ns"; class DBStoreManager { private: std::map<std::string, DB*> DBStoreHandles; DB *default_db = nullptr; CephContext *cct; public: DBStoreManager(CephContext *_cct): DBStoreHandles() { cct = _cct; default_db = createDB(default_tenant); }; DBStoreManager(CephContext *_cct, std::string logfile, int loglevel): DBStoreHandles() { /* No ceph context. Create one with log args provided */ cct = _cct; cct->_log->set_log_file(logfile); cct->_log->reopen_log_file(); cct->_conf->subsys.set_log_level(ceph_subsys_rgw, loglevel); default_db = createDB(default_tenant); }; ~DBStoreManager() { destroyAllHandles(); }; /* XXX: TBD based on testing * 1) Lock to protect DBStoreHandles map. * 2) Refcount of each DBStore to protect from * being deleted while using it. */ DB* getDB () { return default_db; }; DB* getDB (std::string tenant, bool create); DB* createDB (std::string tenant); void deleteDB (std::string tenant); void deleteDB (DB* db); void destroyAllHandles(); };
1,524
25.754386
90
h
null
ceph-main/src/rgw/driver/dbstore/common/connection_pool.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 <concepts> #include <condition_variable> #include <memory> #include <mutex> #include <boost/circular_buffer.hpp> #include "common/dout.h" namespace rgw::dbstore { template <typename Connection> class ConnectionHandle; /// A thread-safe base class that manages a fixed-size pool of generic database /// connections and supports the reclamation of ConnectionHandles. This class /// is the subset of ConnectionPool which doesn't depend on the Factory type. template <typename Connection> class ConnectionPoolBase { public: ConnectionPoolBase(std::size_t max_connections) : connections(max_connections) {} private: friend class ConnectionHandle<Connection>; // TODO: the caller may detect a connection error that prevents the connection // from being reused. allow them to indicate these errors here void put(std::unique_ptr<Connection> connection) { auto lock = std::scoped_lock{mutex}; connections.push_back(std::move(connection)); if (connections.size() == 1) { // was empty cond.notify_one(); } } protected: std::mutex mutex; std::condition_variable cond; boost::circular_buffer<std::unique_ptr<Connection>> connections; }; /// Handle to a database connection borrowed from the pool. Automatically /// returns the connection to its pool on the handle's destruction. template <typename Connection> class ConnectionHandle { ConnectionPoolBase<Connection>* pool = nullptr; std::unique_ptr<Connection> conn; public: ConnectionHandle() noexcept = default; ConnectionHandle(ConnectionPoolBase<Connection>* pool, std::unique_ptr<Connection> conn) noexcept : pool(pool), conn(std::move(conn)) {} ~ConnectionHandle() { if (conn) { pool->put(std::move(conn)); } } ConnectionHandle(ConnectionHandle&&) = default; ConnectionHandle& operator=(ConnectionHandle&& o) noexcept { if (conn) { pool->put(std::move(conn)); } conn = std::move(o.conn); pool = o.pool; return *this; } explicit operator bool() const noexcept { return static_cast<bool>(conn); } Connection& operator*() const noexcept { return *conn; } Connection* operator->() const noexcept { return conn.get(); } Connection* get() const noexcept { return conn.get(); } }; // factory_of concept requires the function signature: // F(const DoutPrefixProvider*) -> std::unique_ptr<T> template <typename F, typename T> concept factory_of = requires (F factory, const DoutPrefixProvider* dpp) { { factory(dpp) } -> std::same_as<std::unique_ptr<T>>; requires std::move_constructible<F>; }; /// Generic database connection pool that enforces a limit on open connections. template <typename Connection, factory_of<Connection> Factory> class ConnectionPool : public ConnectionPoolBase<Connection> { public: ConnectionPool(Factory factory, std::size_t max_connections) : ConnectionPoolBase<Connection>(max_connections), factory(std::move(factory)) {} /// Borrow a connection from the pool. If all existing connections are in use, /// use the connection factory to create another one. If we've reached the /// limit on open connections, wait on a condition variable for the next one /// returned to the pool. auto get(const DoutPrefixProvider* dpp) -> ConnectionHandle<Connection> { auto lock = std::unique_lock{this->mutex}; std::unique_ptr<Connection> conn; if (!this->connections.empty()) { // take an existing connection conn = std::move(this->connections.front()); this->connections.pop_front(); } else if (total < this->connections.capacity()) { // add another connection to the pool conn = factory(dpp); ++total; } else { // wait for the next put() // TODO: support optional_yield ldpp_dout(dpp, 4) << "ConnectionPool waiting on a connection" << dendl; this->cond.wait(lock, [&] { return !this->connections.empty(); }); ldpp_dout(dpp, 4) << "ConnectionPool done waiting" << dendl; conn = std::move(this->connections.front()); this->connections.pop_front(); } return {this, std::move(conn)}; } private: Factory factory; std::size_t total = 0; }; } // namespace rgw::dbstore
4,665
30.527027
80
h
null
ceph-main/src/rgw/driver/dbstore/config/sqlite.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_config.h" class DoutPrefixProvider; namespace rgw::dbstore::config { struct SQLiteImpl; class SQLiteConfigStore : public sal::ConfigStore { public: explicit SQLiteConfigStore(std::unique_ptr<SQLiteImpl> impl); ~SQLiteConfigStore() override; int write_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id) override; int read_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string& realm_id) override; int delete_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y) override; int create_realm(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; int read_realm_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; int read_realm_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; int read_default_realm(const DoutPrefixProvider* dpp, optional_yield y, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; int read_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, std::string& realm_id) override; int realm_notify_new_period(const DoutPrefixProvider* dpp, optional_yield y, const RGWPeriod& period) override; int list_realm_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; int create_period(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWPeriod& info) override; int read_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id, std::optional<uint32_t> epoch, RGWPeriod& info) override; int delete_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id) override; int list_period_ids(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; int write_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zonegroup_id) override; int read_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zonegroup_id) override; int delete_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; int create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; int read_zonegroup_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; int read_zonegroup_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; int read_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; int list_zonegroup_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; int write_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zone_id) override; int read_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zone_id) override; int delete_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; int create_zone(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; int read_zone_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; int read_zone_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; int read_default_zone(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; int list_zone_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; int read_period_config(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWPeriodConfig& info) override; int write_period_config(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, const RGWPeriodConfig& info) override; private: std::unique_ptr<SQLiteImpl> impl; }; // SQLiteConfigStore auto create_sqlite_store(const DoutPrefixProvider* dpp, const std::string& uri) -> std::unique_ptr<config::SQLiteConfigStore>; } // namespace rgw::dbstore::config
8,134
46.023121
85
h
null
ceph-main/src/rgw/driver/dbstore/config/sqlite_schema.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 <initializer_list> namespace rgw::dbstore::config::schema { struct Migration { // human-readable description to help with debugging migration errors const char* description = nullptr; // series of sql statements to apply the schema migration const char* up = nullptr; // series of sql statements to undo the schema migration const char* down = nullptr; }; static constexpr std::initializer_list<Migration> migrations {{ .description = "create the initial ConfigStore tables", .up = R"( CREATE TABLE IF NOT EXISTS Realms ( ID TEXT PRIMARY KEY NOT NULL, Name TEXT UNIQUE NOT NULL, CurrentPeriod TEXT, Epoch INTEGER DEFAULT 0, VersionNumber INTEGER, VersionTag TEXT ); CREATE TABLE IF NOT EXISTS Periods ( ID TEXT NOT NULL, Epoch INTEGER DEFAULT 0, RealmID TEXT NOT NULL REFERENCES Realms (ID), Data TEXT NOT NULL, PRIMARY KEY (ID, Epoch) ); CREATE TABLE IF NOT EXISTS PeriodConfigs ( RealmID TEXT PRIMARY KEY NOT NULL REFERENCES Realms (ID), Data TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS ZoneGroups ( ID TEXT PRIMARY KEY NOT NULL, Name TEXT UNIQUE NOT NULL, RealmID TEXT REFERENCES Realms (ID), Data TEXT NOT NULL, VersionNumber INTEGER, VersionTag TEXT ); CREATE TABLE IF NOT EXISTS Zones ( ID TEXT PRIMARY KEY NOT NULL, Name TEXT UNIQUE NOT NULL, RealmID TEXT REFERENCES Realms (ID), Data TEXT NOT NULL, VersionNumber INTEGER, VersionTag TEXT ); CREATE TABLE IF NOT EXISTS DefaultRealms ( ID TEXT, Empty TEXT PRIMARY KEY ); CREATE TABLE IF NOT EXISTS DefaultZoneGroups ( ID TEXT, RealmID TEXT PRIMARY KEY REFERENCES Realms (ID) ); CREATE TABLE IF NOT EXISTS DefaultZones ( ID TEXT, RealmID TEXT PRIMARY KEY REFERENCES Realms (ID) ); )", .down = R"( DROP TABLE IF EXISTS Realms; DROP TABLE IF EXISTS Periods; DROP TABLE IF EXISTS PeriodConfigs; DROP TABLE IF EXISTS ZoneGroups; DROP TABLE IF EXISTS Zones; DROP TABLE IF EXISTS DefaultRealms; DROP TABLE IF EXISTS DefaultZoneGroups; DROP TABLE IF EXISTS DefaultZones; )" } }; // DefaultRealms static constexpr const char* default_realm_insert1 = "INSERT INTO DefaultRealms (ID, Empty) VALUES ({}, '')"; static constexpr const char* default_realm_upsert1 = R"(INSERT INTO DefaultRealms (ID, Empty) VALUES ({0}, '') ON CONFLICT(Empty) DO UPDATE SET ID = {0})"; static constexpr const char* default_realm_select0 = "SELECT ID FROM DefaultRealms LIMIT 1"; static constexpr const char* default_realm_delete0 = "DELETE FROM DefaultRealms"; // Realms static constexpr const char* realm_update5 = "UPDATE Realms SET CurrentPeriod = {1}, Epoch = {2}, VersionNumber = {3} + 1 \ WHERE ID = {0} AND VersionNumber = {3} AND VersionTag = {4}"; static constexpr const char* realm_rename4 = "UPDATE Realms SET Name = {1}, VersionNumber = {2} + 1 \ WHERE ID = {0} AND VersionNumber = {2} AND VersionTag = {3}"; static constexpr const char* realm_delete3 = "DELETE FROM Realms WHERE ID = {} AND VersionNumber = {} AND VersionTag = {}"; static constexpr const char* realm_insert4 = "INSERT INTO Realms (ID, Name, VersionNumber, VersionTag) \ VALUES ({}, {}, {}, {})"; static constexpr const char* realm_upsert4 = "INSERT INTO Realms (ID, Name, VersionNumber, VersionTag) \ VALUES ({0}, {1}, {2}, {3}) \ ON CONFLICT(ID) DO UPDATE SET Name = {1}, \ VersionNumber = {2}, VersionTag = {3}"; static constexpr const char* realm_select_id1 = "SELECT * FROM Realms WHERE ID = {} LIMIT 1"; static constexpr const char* realm_select_name1 = "SELECT * FROM Realms WHERE Name = {} LIMIT 1"; static constexpr const char* realm_select_default0 = "SELECT r.* FROM Realms r \ INNER JOIN DefaultRealms d \ ON d.ID = r.ID LIMIT 1"; static constexpr const char* realm_select_names2 = "SELECT Name FROM Realms WHERE Name > {} \ ORDER BY Name ASC LIMIT {}"; // Periods static constexpr const char* period_insert4 = "INSERT INTO Periods (ID, Epoch, RealmID, Data) \ VALUES ({}, {}, {}, {})"; static constexpr const char* period_upsert4 = "INSERT INTO Periods (ID, Epoch, RealmID, Data) \ VALUES ({0}, {1}, {2}, {3}) \ ON CONFLICT DO UPDATE SET RealmID = {2}, Data = {3}"; static constexpr const char* period_select_epoch2 = "SELECT * FROM Periods WHERE ID = {} AND Epoch = {} LIMIT 1"; static constexpr const char* period_select_latest1 = "SELECT * FROM Periods WHERE ID = {} ORDER BY Epoch DESC LIMIT 1"; static constexpr const char* period_delete1 = "DELETE FROM Periods WHERE ID = {}"; static constexpr const char* period_select_ids2 = "SELECT ID FROM Periods WHERE ID > {} ORDER BY ID ASC LIMIT {}"; // DefaultZoneGroups static constexpr const char* default_zonegroup_insert2 = "INSERT INTO DefaultZoneGroups (RealmID, ID) VALUES ({}, {})"; static constexpr const char* default_zonegroup_upsert2 = "INSERT INTO DefaultZoneGroups (RealmID, ID) \ VALUES ({0}, {1}) \ ON CONFLICT(RealmID) DO UPDATE SET ID = {1}"; static constexpr const char* default_zonegroup_select1 = "SELECT ID FROM DefaultZoneGroups WHERE RealmID = {}"; static constexpr const char* default_zonegroup_delete1 = "DELETE FROM DefaultZoneGroups WHERE RealmID = {}"; // ZoneGroups static constexpr const char* zonegroup_update5 = "UPDATE ZoneGroups SET RealmID = {1}, Data = {2}, VersionNumber = {3} + 1 \ WHERE ID = {0} AND VersionNumber = {3} AND VersionTag = {4}"; static constexpr const char* zonegroup_rename4 = "UPDATE ZoneGroups SET Name = {1}, VersionNumber = {2} + 1 \ WHERE ID = {0} AND VersionNumber = {2} AND VersionTag = {3}"; static constexpr const char* zonegroup_delete3 = "DELETE FROM ZoneGroups WHERE ID = {} \ AND VersionNumber = {} AND VersionTag = {}"; static constexpr const char* zonegroup_insert6 = "INSERT INTO ZoneGroups (ID, Name, RealmID, Data, VersionNumber, VersionTag) \ VALUES ({}, {}, {}, {}, {}, {})"; static constexpr const char* zonegroup_upsert6 = "INSERT INTO ZoneGroups (ID, Name, RealmID, Data, VersionNumber, VersionTag) \ VALUES ({0}, {1}, {2}, {3}, {4}, {5}) \ ON CONFLICT (ID) DO UPDATE SET Name = {1}, RealmID = {2}, \ Data = {3}, VersionNumber = {4}, VersionTag = {5}"; static constexpr const char* zonegroup_select_id1 = "SELECT * FROM ZoneGroups WHERE ID = {} LIMIT 1"; static constexpr const char* zonegroup_select_name1 = "SELECT * FROM ZoneGroups WHERE Name = {} LIMIT 1"; static constexpr const char* zonegroup_select_default0 = "SELECT z.* FROM ZoneGroups z \ INNER JOIN DefaultZoneGroups d \ ON d.ID = z.ID LIMIT 1"; static constexpr const char* zonegroup_select_names2 = "SELECT Name FROM ZoneGroups WHERE Name > {} \ ORDER BY Name ASC LIMIT {}"; // DefaultZones static constexpr const char* default_zone_insert2 = "INSERT INTO DefaultZones (RealmID, ID) VALUES ({}, {})"; static constexpr const char* default_zone_upsert2 = "INSERT INTO DefaultZones (RealmID, ID) VALUES ({0}, {1}) \ ON CONFLICT(RealmID) DO UPDATE SET ID = {1}"; static constexpr const char* default_zone_select1 = "SELECT ID FROM DefaultZones WHERE RealmID = {}"; static constexpr const char* default_zone_delete1 = "DELETE FROM DefaultZones WHERE RealmID = {}"; // Zones static constexpr const char* zone_update5 = "UPDATE Zones SET RealmID = {1}, Data = {2}, VersionNumber = {3} + 1 \ WHERE ID = {0} AND VersionNumber = {3} AND VersionTag = {4}"; static constexpr const char* zone_rename4 = "UPDATE Zones SET Name = {1}, VersionNumber = {2} + 1 \ WHERE ID = {0} AND VersionNumber = {2} AND VersionTag = {3}"; static constexpr const char* zone_delete3 = "DELETE FROM Zones WHERE ID = {} AND VersionNumber = {} AND VersionTag = {}"; static constexpr const char* zone_insert6 = "INSERT INTO Zones (ID, Name, RealmID, Data, VersionNumber, VersionTag) \ VALUES ({}, {}, {}, {}, {}, {})"; static constexpr const char* zone_upsert6 = "INSERT INTO Zones (ID, Name, RealmID, Data, VersionNumber, VersionTag) \ VALUES ({0}, {1}, {2}, {3}, {4}, {5}) \ ON CONFLICT (ID) DO UPDATE SET Name = {1}, RealmID = {2}, \ Data = {3}, VersionNumber = {4}, VersionTag = {5}"; static constexpr const char* zone_select_id1 = "SELECT * FROM Zones WHERE ID = {} LIMIT 1"; static constexpr const char* zone_select_name1 = "SELECT * FROM Zones WHERE Name = {} LIMIT 1"; static constexpr const char* zone_select_default0 = "SELECT z.* FROM Zones z \ INNER JOIN DefaultZones d \ ON d.ID = z.ID LIMIT 1"; static constexpr const char* zone_select_names2 = "SELECT Name FROM Zones WHERE Name > {} \ ORDER BY Name ASC LIMIT {}"; // PeriodConfigs static constexpr const char* period_config_insert2 = "INSERT INTO PeriodConfigs (RealmID, Data) VALUES ({}, {})"; static constexpr const char* period_config_upsert2 = "INSERT INTO PeriodConfigs (RealmID, Data) VALUES ({0}, {1}) \ ON CONFLICT (RealmID) DO UPDATE SET Data = {1}"; static constexpr const char* period_config_select1 = "SELECT Data FROM PeriodConfigs WHERE RealmID = {} LIMIT 1"; } // namespace rgw::dbstore::config::schema
9,244
29.816667
78
h
null
ceph-main/src/rgw/driver/dbstore/config/store.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 "rgw_sal_config.h" namespace rgw::dbstore { // ConfigStore factory auto create_config_store(const DoutPrefixProvider* dpp, const std::string& uri) -> std::unique_ptr<sal::ConfigStore>; } // namespace rgw::dbstore
671
23
79
h
null
ceph-main/src/rgw/driver/dbstore/sqlite/connection.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 <sqlite3.h> #include <fmt/format.h> #include "sqlite/statement.h" class DoutPrefixProvider; namespace rgw::dbstore::sqlite { // owning sqlite3 pointer struct db_deleter { void operator()(sqlite3* p) const { ::sqlite3_close(p); } }; using db_ptr = std::unique_ptr<sqlite3, db_deleter>; // open the database file or throw on error db_ptr open_database(const char* filename, int flags); struct Connection { db_ptr db; // map of statements, prepared on first use std::map<std::string_view, stmt_ptr> statements; explicit Connection(db_ptr db) : db(std::move(db)) {} }; // sqlite connection factory for ConnectionPool class ConnectionFactory { std::string uri; int flags; public: ConnectionFactory(std::string uri, int flags) : uri(std::move(uri)), flags(flags) {} auto operator()(const DoutPrefixProvider* dpp) -> std::unique_ptr<Connection> { auto db = open_database(uri.c_str(), flags); return std::make_unique<Connection>(std::move(db)); } }; } // namespace rgw::dbstore::sqlite
1,485
21.861538
70
h
null
ceph-main/src/rgw/driver/dbstore/sqlite/error.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 <system_error> #include <sqlite3.h> namespace rgw::dbstore::sqlite { // error category for sqlite extended result codes: // https://www.sqlite.org/rescode.html const std::error_category& error_category(); // sqlite exception type that carries the extended error code and message class error : public std::runtime_error { std::error_code ec; public: error(const char* errmsg, std::error_code ec) : runtime_error(errmsg), ec(ec) {} error(sqlite3* db, std::error_code ec) : error(::sqlite3_errmsg(db), ec) {} error(sqlite3* db, int result) : error(db, {result, error_category()}) {} error(sqlite3* db) : error(db, ::sqlite3_extended_errcode(db)) {} std::error_code code() const { return ec; } }; // sqlite error conditions for primary and extended result codes // // 'primary' error_conditions will match 'primary' error_codes as well as any // 'extended' error_codes whose lowest 8 bits match that primary code. for // example, the error_condition for SQLITE_CONSTRAINT will match the error_codes // SQLITE_CONSTRAINT and SQLITE_CONSTRAINT_* enum class errc { // primary result codes ok = SQLITE_OK, busy = SQLITE_BUSY, constraint = SQLITE_CONSTRAINT, row = SQLITE_ROW, done = SQLITE_DONE, // extended result codes primary_key_constraint = SQLITE_CONSTRAINT_PRIMARYKEY, foreign_key_constraint = SQLITE_CONSTRAINT_FOREIGNKEY, unique_constraint = SQLITE_CONSTRAINT_UNIQUE, // ..add conditions as needed }; inline std::error_code make_error_code(errc e) { return {static_cast<int>(e), error_category()}; } inline std::error_condition make_error_condition(errc e) { return {static_cast<int>(e), error_category()}; } } // namespace rgw::dbstore::sqlite namespace std { // enable implicit conversions from sqlite::errc to std::error_condition template<> struct is_error_condition_enum< rgw::dbstore::sqlite::errc> : public true_type {}; } // namespace std
2,348
27.646341
80
h
null
ceph-main/src/rgw/driver/dbstore/sqlite/statement.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 <span> #include <string> #include <sqlite3.h> class DoutPrefixProvider; namespace rgw::dbstore::sqlite { // owning sqlite3_stmt pointer struct stmt_deleter { void operator()(sqlite3_stmt* p) const { ::sqlite3_finalize(p); } }; using stmt_ptr = std::unique_ptr<sqlite3_stmt, stmt_deleter>; // non-owning sqlite3_stmt pointer that clears binding state on destruction struct stmt_binding_deleter { void operator()(sqlite3_stmt* p) const { ::sqlite3_clear_bindings(p); } }; using stmt_binding = std::unique_ptr<sqlite3_stmt, stmt_binding_deleter>; // non-owning sqlite3_stmt pointer that clears execution state on destruction struct stmt_execution_deleter { void operator()(sqlite3_stmt* p) const { ::sqlite3_reset(p); } }; using stmt_execution = std::unique_ptr<sqlite3_stmt, stmt_execution_deleter>; // prepare the sql statement or throw on error stmt_ptr prepare_statement(const DoutPrefixProvider* dpp, sqlite3* db, std::string_view sql); // bind a NULL input for the given parameter name void bind_null(const DoutPrefixProvider* dpp, const stmt_binding& stmt, const char* name); // bind an input string for the given parameter name void bind_text(const DoutPrefixProvider* dpp, const stmt_binding& stmt, const char* name, std::string_view value); // bind an input integer for the given parameter name void bind_int(const DoutPrefixProvider* dpp, const stmt_binding& stmt, const char* name, int value); // evaluate a prepared statement, expecting no result rows void eval0(const DoutPrefixProvider* dpp, const stmt_execution& stmt); // evaluate a prepared statement, expecting a single result row void eval1(const DoutPrefixProvider* dpp, const stmt_execution& stmt); // return the given column as an integer int column_int(const stmt_execution& stmt, int column); // return the given column as text, or an empty string on NULL std::string column_text(const stmt_execution& stmt, int column); // read the text column from each result row into the given entries, and return // the sub-span of entries that contain results auto read_text_rows(const DoutPrefixProvider* dpp, const stmt_execution& stmt, std::span<std::string> entries) -> std::span<std::string>; // execute a raw query without preparing a statement. the optional callback // can be used to read results void execute(const DoutPrefixProvider* dpp, sqlite3* db, const char* query, sqlite3_callback callback, void* arg); } // namespace rgw::dbstore::sqlite
3,020
33.329545
79
h
null
ceph-main/src/rgw/driver/immutable_config/store.h
// 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_config.h" namespace rgw::sal { /// A read-only ConfigStore that serves the given default zonegroup and zone. class ImmutableConfigStore : public ConfigStore { public: explicit ImmutableConfigStore(const RGWZoneGroup& zonegroup, const RGWZoneParams& zone, const RGWPeriodConfig& period_config); // Realm virtual int write_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id) override; virtual int read_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string& realm_id) override; virtual int delete_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y) override; virtual int create_realm(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWRealm& info, std::unique_ptr<RealmWriter>* writer) override; virtual int read_realm_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWRealm& info, std::unique_ptr<RealmWriter>* writer) override; virtual int read_realm_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, RGWRealm& info, std::unique_ptr<RealmWriter>* writer) override; virtual int read_default_realm(const DoutPrefixProvider* dpp, optional_yield y, RGWRealm& info, std::unique_ptr<RealmWriter>* writer) override; virtual int read_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, std::string& realm_id) override; virtual int realm_notify_new_period(const DoutPrefixProvider* dpp, optional_yield y, const RGWPeriod& period) override; virtual int list_realm_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, ListResult<std::string>& result) override; // Period virtual int create_period(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWPeriod& info) override; virtual int read_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id, std::optional<uint32_t> epoch, RGWPeriod& info) override; virtual int delete_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id) override; virtual int list_period_ids(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, ListResult<std::string>& result) override; // ZoneGroup virtual int write_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zonegroup_id) override; virtual int read_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zonegroup_id) override; virtual int delete_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; virtual int create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneGroup& info, std::unique_ptr<ZoneGroupWriter>* writer) override; virtual int read_zonegroup_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_id, RGWZoneGroup& info, std::unique_ptr<ZoneGroupWriter>* writer) override; virtual int read_zonegroup_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<ZoneGroupWriter>* writer) override; virtual int read_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneGroup& info, std::unique_ptr<ZoneGroupWriter>* writer) override; virtual int list_zonegroup_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, ListResult<std::string>& result) override; // Zone virtual int write_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zone_id) override; virtual int read_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zone_id) override; virtual int delete_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; virtual int create_zone(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneParams& info, std::unique_ptr<ZoneWriter>* writer) override; virtual int read_zone_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_id, RGWZoneParams& info, std::unique_ptr<ZoneWriter>* writer) override; virtual int read_zone_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<ZoneWriter>* writer) override; virtual int read_default_zone(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneParams& info, std::unique_ptr<ZoneWriter>* writer) override; virtual int list_zone_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, ListResult<std::string>& result) override; // PeriodConfig virtual int read_period_config(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWPeriodConfig& info) override; virtual int write_period_config(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, const RGWPeriodConfig& info) override; private: const RGWZoneGroup zonegroup; const RGWZoneParams zone; const RGWPeriodConfig period_config; }; // ImmutableConfigStore /// ImmutableConfigStore factory function auto create_immutable_config_store(const DoutPrefixProvider* dpp, const RGWZoneGroup& zonegroup, const RGWZoneParams& zone, const RGWPeriodConfig& period_config) -> std::unique_ptr<ConfigStore>; } // namespace rgw::sal
9,431
51.110497
88
h
null
ceph-main/src/rgw/driver/json_config/store.h
// 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 "driver/immutable_config/store.h" namespace rgw::sal { /// Create an immutable ConfigStore by parsing the zonegroup and zone from the /// given json filename. auto create_json_config_store(const DoutPrefixProvider* dpp, const std::string& filename) -> std::unique_ptr<ConfigStore>; } // namespace rgw::sal
707
24.285714
78
h
null
ceph-main/src/rgw/driver/rados/rgw_cr_tools.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_cr_rados.h" #include "rgw_tools.h" #include "rgw_lc.h" #include "services/svc_bucket_sync.h" struct rgw_user_create_params { rgw_user user; std::string display_name; std::string email; std::string access_key; std::string secret_key; std::string key_type; /* "swift" or "s3" */ std::string caps; bool generate_key{true}; bool suspended{false}; std::optional<int32_t> max_buckets; bool system{false}; bool exclusive{false}; bool apply_quota{true}; }; using RGWUserCreateCR = RGWSimpleWriteOnlyAsyncCR<rgw_user_create_params>; struct rgw_get_user_info_params { rgw_user user; }; using RGWGetUserInfoCR = RGWSimpleAsyncCR<rgw_get_user_info_params, RGWUserInfo>; struct rgw_get_bucket_info_params { std::string tenant; std::string bucket_name; }; struct rgw_get_bucket_info_result { std::unique_ptr<rgw::sal::Bucket> bucket; }; using RGWGetBucketInfoCR = RGWSimpleAsyncCR<rgw_get_bucket_info_params, rgw_get_bucket_info_result>; struct rgw_bucket_create_local_params { std::shared_ptr<RGWUserInfo> user_info; std::string bucket_name; rgw_placement_rule placement_rule; }; using RGWBucketCreateLocalCR = RGWSimpleWriteOnlyAsyncCR<rgw_bucket_create_local_params>; struct rgw_object_simple_put_params { RGWDataAccess::BucketRef bucket; rgw_obj_key key; bufferlist data; std::map<std::string, bufferlist> attrs; std::optional<std::string> user_data; }; using RGWObjectSimplePutCR = RGWSimpleWriteOnlyAsyncCR<rgw_object_simple_put_params>; struct rgw_bucket_lifecycle_config_params { rgw::sal::Bucket* bucket; rgw::sal::Attrs bucket_attrs; RGWLifecycleConfiguration config; }; using RGWBucketLifecycleConfigCR = RGWSimpleWriteOnlyAsyncCR<rgw_bucket_lifecycle_config_params>; struct rgw_bucket_get_sync_policy_params { std::optional<rgw_zone_id> zone; std::optional<rgw_bucket> bucket; }; struct rgw_bucket_get_sync_policy_result { RGWBucketSyncPolicyHandlerRef policy_handler; }; using RGWBucketGetSyncPolicyHandlerCR = RGWSimpleAsyncCR<rgw_bucket_get_sync_policy_params, rgw_bucket_get_sync_policy_result>;
2,214
24.755814
127
h
null
ceph-main/src/rgw/driver/rados/rgw_datalog.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 <cstdint> #include <list> #include <memory> #include <string> #include <string_view> #include <variant> #include <vector> #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include <boost/smart_ptr/intrusive_ptr.hpp> #include <boost/smart_ptr/intrusive_ref_counter.hpp> #include <fmt/format.h> #include "common/async/yield_context.h" #include "include/buffer.h" #include "include/encoding.h" #include "include/function2.hpp" #include "include/rados/librados.hpp" #include "common/ceph_context.h" #include "common/ceph_json.h" #include "common/ceph_time.h" #include "common/Formatter.h" #include "common/lru_map.h" #include "common/RefCountedObj.h" #include "cls/log/cls_log_types.h" #include "rgw_basic_types.h" #include "rgw_log_backing.h" #include "rgw_sync_policy.h" #include "rgw_zone.h" #include "rgw_trim_bilog.h" namespace bc = boost::container; enum DataLogEntityType { ENTITY_TYPE_UNKNOWN = 0, ENTITY_TYPE_BUCKET = 1, }; struct rgw_data_change { DataLogEntityType entity_type; std::string key; ceph::real_time timestamp; uint64_t gen = 0; void encode(ceph::buffer::list& bl) const { // require decoders to recognize v2 when gen>0 const uint8_t compat = (gen == 0) ? 1 : 2; ENCODE_START(2, compat, bl); auto t = std::uint8_t(entity_type); encode(t, bl); encode(key, bl); encode(timestamp, bl); encode(gen, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(2, bl); std::uint8_t t; decode(t, bl); entity_type = DataLogEntityType(t); decode(key, bl); decode(timestamp, bl); if (struct_v < 2) { gen = 0; } else { decode(gen, bl); } DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); static void generate_test_instances(std::list<rgw_data_change *>& l); }; WRITE_CLASS_ENCODER(rgw_data_change) struct rgw_data_change_log_entry { std::string log_id; ceph::real_time log_timestamp; rgw_data_change entry; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(log_id, bl); encode(log_timestamp, bl); encode(entry, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(1, bl); decode(log_id, bl); decode(log_timestamp, bl); decode(entry, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); }; WRITE_CLASS_ENCODER(rgw_data_change_log_entry) struct RGWDataChangesLogInfo { std::string marker; ceph::real_time last_update; void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); }; struct RGWDataChangesLogMarker { int shard = 0; std::string marker; RGWDataChangesLogMarker() = default; }; class RGWDataChangesLog; struct rgw_data_notify_entry { std::string key; uint64_t gen = 0; void dump(ceph::Formatter* f) const; void decode_json(JSONObj* obj); rgw_data_notify_entry& operator=(const rgw_data_notify_entry&) = default; bool operator <(const rgw_data_notify_entry& d) const { if (key < d.key) { return true; } if (d.key < key) { return false; } return gen < d.gen; } friend std::ostream& operator <<(std::ostream& m, const rgw_data_notify_entry& e) { return m << "[key: " << e.key << ", gen: " << e.gen << "]"; } }; class RGWDataChangesBE; class DataLogBackends final : public logback_generations, private bc::flat_map<uint64_t, boost::intrusive_ptr<RGWDataChangesBE>> { friend class logback_generations; friend class GenTrim; std::mutex m; RGWDataChangesLog& datalog; DataLogBackends(librados::IoCtx& ioctx, std::string oid, fu2::unique_function<std::string( uint64_t, int) const>&& get_oid, int shards, RGWDataChangesLog& datalog) noexcept : logback_generations(ioctx, oid, std::move(get_oid), shards), datalog(datalog) {} public: boost::intrusive_ptr<RGWDataChangesBE> head() { std::unique_lock l(m); auto i = end(); --i; return i->second; } int list(const DoutPrefixProvider *dpp, int shard, int max_entries, std::vector<rgw_data_change_log_entry>& entries, std::string_view marker, std::string* out_marker, bool* truncated, optional_yield y); int trim_entries(const DoutPrefixProvider *dpp, int shard_id, std::string_view marker, optional_yield y); void trim_entries(const DoutPrefixProvider *dpp, int shard_id, std::string_view marker, librados::AioCompletion* c); void set_zero(RGWDataChangesBE* be) { emplace(0, be); } bs::error_code handle_init(entries_t e) noexcept override; bs::error_code handle_new_gens(entries_t e) noexcept override; bs::error_code handle_empty_to(uint64_t new_tail) noexcept override; int trim_generations(const DoutPrefixProvider *dpp, std::optional<uint64_t>& through, optional_yield y); }; struct BucketGen { rgw_bucket_shard shard; uint64_t gen; BucketGen(const rgw_bucket_shard& shard, uint64_t gen) : shard(shard), gen(gen) {} BucketGen(rgw_bucket_shard&& shard, uint64_t gen) : shard(std::move(shard)), gen(gen) {} BucketGen(const BucketGen&) = default; BucketGen(BucketGen&&) = default; BucketGen& operator =(const BucketGen&) = default; BucketGen& operator =(BucketGen&&) = default; ~BucketGen() = default; }; inline bool operator ==(const BucketGen& l, const BucketGen& r) { return (l.shard == r.shard) && (l.gen == r.gen); } inline bool operator <(const BucketGen& l, const BucketGen& r) { if (l.shard < r.shard) { return true; } else if (l.shard == r.shard) { return l.gen < r.gen; } else { return false; } } class RGWDataChangesLog { friend DataLogBackends; CephContext *cct; librados::IoCtx ioctx; rgw::BucketChangeObserver *observer = nullptr; const RGWZone* zone; std::unique_ptr<DataLogBackends> bes; const int num_shards; std::string get_prefix() { auto prefix = cct->_conf->rgw_data_log_obj_prefix; return prefix.empty() ? prefix : "data_log"; } std::string metadata_log_oid() { return get_prefix() + "generations_metadata"; } std::string prefix; ceph::mutex lock = ceph::make_mutex("RGWDataChangesLog::lock"); ceph::shared_mutex modified_lock = ceph::make_shared_mutex("RGWDataChangesLog::modified_lock"); bc::flat_map<int, bc::flat_set<rgw_data_notify_entry>> modified_shards; std::atomic<bool> down_flag = { false }; struct ChangeStatus { std::shared_ptr<const rgw_sync_policy_info> sync_policy; ceph::real_time cur_expiration; ceph::real_time cur_sent; bool pending = false; RefCountedCond* cond = nullptr; ceph::mutex lock = ceph::make_mutex("RGWDataChangesLog::ChangeStatus"); }; using ChangeStatusPtr = std::shared_ptr<ChangeStatus>; lru_map<BucketGen, ChangeStatusPtr> changes; bc::flat_set<BucketGen> cur_cycle; ChangeStatusPtr _get_change(const rgw_bucket_shard& bs, uint64_t gen); void register_renew(const rgw_bucket_shard& bs, const rgw::bucket_log_layout_generation& gen); void update_renewed(const rgw_bucket_shard& bs, uint64_t gen, ceph::real_time expiration); ceph::mutex renew_lock = ceph::make_mutex("ChangesRenewThread::lock"); ceph::condition_variable renew_cond; void renew_run() noexcept; void renew_stop(); std::thread renew_thread; std::function<bool(const rgw_bucket& bucket, optional_yield y, const DoutPrefixProvider *dpp)> bucket_filter; bool going_down() const; bool filter_bucket(const DoutPrefixProvider *dpp, const rgw_bucket& bucket, optional_yield y) const; int renew_entries(const DoutPrefixProvider *dpp); public: RGWDataChangesLog(CephContext* cct); ~RGWDataChangesLog(); int start(const DoutPrefixProvider *dpp, const RGWZone* _zone, const RGWZoneParams& zoneparams, librados::Rados* lr); int choose_oid(const rgw_bucket_shard& bs); int add_entry(const DoutPrefixProvider *dpp, const RGWBucketInfo& bucket_info, const rgw::bucket_log_layout_generation& gen, int shard_id, optional_yield y); int get_log_shard_id(rgw_bucket& bucket, int shard_id); int list_entries(const DoutPrefixProvider *dpp, int shard, int max_entries, std::vector<rgw_data_change_log_entry>& entries, std::string_view marker, std::string* out_marker, bool* truncated, optional_yield y); int trim_entries(const DoutPrefixProvider *dpp, int shard_id, std::string_view marker, optional_yield y); int trim_entries(const DoutPrefixProvider *dpp, int shard_id, std::string_view marker, librados::AioCompletion* c); // :( int get_info(const DoutPrefixProvider *dpp, int shard_id, RGWDataChangesLogInfo *info, optional_yield y); using LogMarker = RGWDataChangesLogMarker; int list_entries(const DoutPrefixProvider *dpp, int max_entries, std::vector<rgw_data_change_log_entry>& entries, LogMarker& marker, bool* ptruncated, optional_yield y); void mark_modified(int shard_id, const rgw_bucket_shard& bs, uint64_t gen); auto read_clear_modified() { std::unique_lock wl{modified_lock}; decltype(modified_shards) modified; modified.swap(modified_shards); modified_shards.clear(); return modified; } void set_observer(rgw::BucketChangeObserver *observer) { this->observer = observer; } void set_bucket_filter(decltype(bucket_filter)&& f) { bucket_filter = std::move(f); } // a marker that compares greater than any other std::string max_marker() const; std::string get_oid(uint64_t gen_id, int shard_id) const; int change_format(const DoutPrefixProvider *dpp, log_type type, optional_yield y); int trim_generations(const DoutPrefixProvider *dpp, std::optional<uint64_t>& through, optional_yield y); }; class RGWDataChangesBE : public boost::intrusive_ref_counter<RGWDataChangesBE> { protected: librados::IoCtx& ioctx; CephContext* const cct; RGWDataChangesLog& datalog; std::string get_oid(int shard_id) { return datalog.get_oid(gen_id, shard_id); } public: using entries = std::variant<std::list<cls_log_entry>, std::vector<ceph::buffer::list>>; const uint64_t gen_id; RGWDataChangesBE(librados::IoCtx& ioctx, RGWDataChangesLog& datalog, uint64_t gen_id) : ioctx(ioctx), cct(static_cast<CephContext*>(ioctx.cct())), datalog(datalog), gen_id(gen_id) {} virtual ~RGWDataChangesBE() = default; virtual void prepare(ceph::real_time now, const std::string& key, ceph::buffer::list&& entry, entries& out) = 0; virtual int push(const DoutPrefixProvider *dpp, int index, entries&& items, optional_yield y) = 0; virtual int push(const DoutPrefixProvider *dpp, int index, ceph::real_time now, const std::string& key, ceph::buffer::list&& bl, optional_yield y) = 0; virtual int list(const DoutPrefixProvider *dpp, int shard, int max_entries, std::vector<rgw_data_change_log_entry>& entries, std::optional<std::string_view> marker, std::string* out_marker, bool* truncated, optional_yield y) = 0; virtual int get_info(const DoutPrefixProvider *dpp, int index, RGWDataChangesLogInfo *info, optional_yield y) = 0; virtual int trim(const DoutPrefixProvider *dpp, int index, std::string_view marker, optional_yield y) = 0; virtual int trim(const DoutPrefixProvider *dpp, int index, std::string_view marker, librados::AioCompletion* c) = 0; virtual std::string_view max_marker() const = 0; // 1 on empty, 0 on non-empty, negative on error. virtual int is_empty(const DoutPrefixProvider *dpp, optional_yield y) = 0; };
11,839
28.89899
111
h
null
ceph-main/src/rgw/driver/rados/rgw_datalog_notify.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include "rgw_datalog.h" namespace bc = boost::container; namespace ceph { class Formatter; } class JSONObj; class RGWCoroutine; class RGWHTTPManager; class RGWRESTConn; struct rgw_data_notify_entry; // json encoder and decoder for notify v1 API struct rgw_data_notify_v1_encoder { const bc::flat_map<int, bc::flat_set<rgw_data_notify_entry>>& shards; }; void encode_json(const char *name, const rgw_data_notify_v1_encoder& e, ceph::Formatter *f); struct rgw_data_notify_v1_decoder { bc::flat_map<int, bc::flat_set<rgw_data_notify_entry>>& shards; }; void decode_json_obj(rgw_data_notify_v1_decoder& d, JSONObj *obj);
845
25.4375
71
h
null
ceph-main/src/rgw/driver/rados/rgw_etag_verifier.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * RGW Etag Verifier is an RGW filter which enables the objects copied using * multisite sync to be verified using their ETag from source i.e. the MD5 * checksum of the object is computed at the destination and is verified to be * identical to the ETag stored in the object HEAD at source cluster. * * For MPU objects, a different filter named RGWMultipartEtagFilter is applied * which re-computes ETag using RGWObjManifest. This computes the ETag using the * same algorithm used at the source cluster i.e. MD5 sum of the individual ETag * on the MPU parts. */ #pragma once #include "rgw_putobj.h" #include "rgw_op.h" #include "common/static_ptr.h" namespace rgw::putobj { class ETagVerifier : public rgw::putobj::Pipe { protected: CephContext* cct; MD5 hash; std::string calculated_etag; public: ETagVerifier(CephContext* cct_, rgw::sal::DataProcessor *next) : Pipe(next), cct(cct_) { // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } virtual void calculate_etag() = 0; std::string get_calculated_etag() { return calculated_etag;} }; /* ETagVerifier */ class ETagVerifier_Atomic : public ETagVerifier { public: ETagVerifier_Atomic(CephContext* cct_, rgw::sal::DataProcessor *next) : ETagVerifier(cct_, next) {} int process(bufferlist&& data, uint64_t logical_offset) override; void calculate_etag() override; }; /* ETagVerifier_Atomic */ class ETagVerifier_MPU : public ETagVerifier { std::vector<uint64_t> part_ofs; uint64_t cur_part_index{0}, next_part_index{1}; MD5 mpu_etag_hash; void process_end_of_MPU_part(); public: ETagVerifier_MPU(CephContext* cct, std::vector<uint64_t> part_ofs, rgw::sal::DataProcessor *next) : ETagVerifier(cct, next), part_ofs(std::move(part_ofs)) { // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } int process(bufferlist&& data, uint64_t logical_offset) override; void calculate_etag() override; }; /* ETagVerifier_MPU */ constexpr auto max_etag_verifier_size = std::max( sizeof(ETagVerifier_Atomic), sizeof(ETagVerifier_MPU) ); using etag_verifier_ptr = ceph::static_ptr<ETagVerifier, max_etag_verifier_size>; int create_etag_verifier(const DoutPrefixProvider *dpp, CephContext* cct, rgw::sal::DataProcessor* next, const bufferlist& manifest_bl, const std::optional<RGWCompressionInfo>& compression, etag_verifier_ptr& verifier); } // namespace rgw::putobj
2,817
29.967033
81
h
null
ceph-main/src/rgw/driver/rados/rgw_lc_tier.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_lc.h" #include "rgw_rest_conn.h" #include "rgw_rados.h" #include "rgw_zone.h" #include "rgw_sal_rados.h" #include "rgw_cr_rest.h" #define DEFAULT_MULTIPART_SYNC_PART_SIZE (32 * 1024 * 1024) #define MULTIPART_MIN_POSSIBLE_PART_SIZE (5 * 1024 * 1024) struct RGWLCCloudTierCtx { CephContext *cct; const DoutPrefixProvider *dpp; /* Source */ rgw_bucket_dir_entry& o; rgw::sal::Driver *driver; RGWBucketInfo& bucket_info; std::string storage_class; rgw::sal::Object *obj; /* Remote */ RGWRESTConn& conn; std::string target_bucket_name; std::string target_storage_class; std::map<std::string, RGWTierACLMapping> acl_mappings; uint64_t multipart_min_part_size; uint64_t multipart_sync_threshold; bool is_multipart_upload{false}; bool target_bucket_created{true}; RGWLCCloudTierCtx(CephContext* _cct, const DoutPrefixProvider *_dpp, rgw_bucket_dir_entry& _o, rgw::sal::Driver *_driver, RGWBucketInfo &_binfo, rgw::sal::Object *_obj, RGWRESTConn& _conn, std::string& _bucket, std::string& _storage_class) : cct(_cct), dpp(_dpp), o(_o), driver(_driver), bucket_info(_binfo), obj(_obj), conn(_conn), target_bucket_name(_bucket), target_storage_class(_storage_class) {} }; /* Transition object to cloud endpoint */ int rgw_cloud_tier_transfer_object(RGWLCCloudTierCtx& tier_ctx, std::set<std::string>& cloud_targets);
1,521
28.269231
102
h
null
ceph-main/src/rgw/driver/rados/rgw_log_backing.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 <optional> #include <iostream> #include <string> #include <string_view> #include <strings.h> #include <boost/container/flat_map.hpp> #include <boost/system/error_code.hpp> #include <fmt/format.h> #include "include/rados/librados.hpp" #include "include/encoding.h" #include "include/expected.hpp" #include "include/function2.hpp" #include "cls/version/cls_version_types.h" #include "common/async/yield_context.h" #include "common/Formatter.h" #include "common/strtol.h" namespace bc = boost::container; namespace bs = boost::system; #include "cls_fifo_legacy.h" /// Type of log backing, stored in the mark used in the quick check, /// and passed to checking functions. enum class log_type { omap = 0, fifo = 1 }; inline void encode(const log_type& type, ceph::buffer::list& bl) { auto t = static_cast<uint8_t>(type); encode(t, bl); } inline void decode(log_type& type, bufferlist::const_iterator& bl) { uint8_t t; decode(t, bl); type = static_cast<log_type>(t); } inline std::optional<log_type> to_log_type(std::string_view s) { if (strncasecmp(s.data(), "omap", s.length()) == 0) { return log_type::omap; } else if (strncasecmp(s.data(), "fifo", s.length()) == 0) { return log_type::fifo; } else { return std::nullopt; } } inline std::ostream& operator <<(std::ostream& m, const log_type& t) { switch (t) { case log_type::omap: return m << "log_type::omap"; case log_type::fifo: return m << "log_type::fifo"; } return m << "log_type::UNKNOWN=" << static_cast<uint32_t>(t); } /// Look over the shards in a log and determine the type. tl::expected<log_type, bs::error_code> log_backing_type(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx, log_type def, int shards, //< Total number of shards /// A function taking a shard number and /// returning an oid. const fu2::unique_function<std::string(int) const>& get_oid, optional_yield y); /// Remove all log shards and associated parts of fifos. bs::error_code log_remove(librados::IoCtx& ioctx, int shards, //< Total number of shards /// A function taking a shard number and /// returning an oid. const fu2::unique_function<std::string(int) const>& get_oid, bool leave_zero, optional_yield y); struct logback_generation { uint64_t gen_id = 0; log_type type; std::optional<ceph::real_time> pruned; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(gen_id, bl); encode(type, bl); encode(pruned, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(gen_id, bl); decode(type, bl); decode(pruned, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(logback_generation) inline std::ostream& operator <<(std::ostream& m, const logback_generation& g) { return m << "[" << g.gen_id << "," << g.type << "," << (g.pruned ? "PRUNED" : "NOT PRUNED") << "]"; } class logback_generations : public librados::WatchCtx2 { public: using entries_t = bc::flat_map<uint64_t, logback_generation>; protected: librados::IoCtx& ioctx; logback_generations(librados::IoCtx& ioctx, std::string oid, fu2::unique_function<std::string( uint64_t, int) const>&& get_oid, int shards) noexcept : ioctx(ioctx), oid(oid), get_oid(std::move(get_oid)), shards(shards) {} uint64_t my_id = ioctx.get_instance_id(); private: const std::string oid; const fu2::unique_function<std::string(uint64_t, int) const> get_oid; protected: const int shards; private: uint64_t watchcookie = 0; obj_version version; std::mutex m; entries_t entries_; tl::expected<std::pair<entries_t, obj_version>, bs::error_code> read(const DoutPrefixProvider *dpp, optional_yield y) noexcept; bs::error_code write(const DoutPrefixProvider *dpp, entries_t&& e, std::unique_lock<std::mutex>&& l_, optional_yield y) noexcept; bs::error_code setup(const DoutPrefixProvider *dpp, log_type def, optional_yield y) noexcept; bs::error_code watch() noexcept; auto lowest_nomempty(const entries_t& es) { return std::find_if(es.begin(), es.end(), [](const auto& e) { return !e.second.pruned; }); } public: /// For the use of watch/notify. void handle_notify(uint64_t notify_id, uint64_t cookie, uint64_t notifier_id, bufferlist& bl) override final; void handle_error(uint64_t cookie, int err) override final; /// Public interface virtual ~logback_generations(); template<typename T, typename... Args> static tl::expected<std::unique_ptr<T>, bs::error_code> init(const DoutPrefixProvider *dpp, librados::IoCtx& ioctx_, std::string oid_, fu2::unique_function<std::string(uint64_t, int) const>&& get_oid_, int shards_, log_type def, optional_yield y, Args&& ...args) noexcept { try { T* lgp = new T(ioctx_, std::move(oid_), std::move(get_oid_), shards_, std::forward<Args>(args)...); std::unique_ptr<T> lg(lgp); lgp = nullptr; auto ec = lg->setup(dpp, def, y); if (ec) return tl::unexpected(ec); // Obnoxiousness for C++ Compiler in Bionic Beaver return tl::expected<std::unique_ptr<T>, bs::error_code>(std::move(lg)); } catch (const std::bad_alloc&) { return tl::unexpected(bs::error_code(ENOMEM, bs::system_category())); } } bs::error_code update(const DoutPrefixProvider *dpp, optional_yield y) noexcept; entries_t entries() const { return entries_; } bs::error_code new_backing(const DoutPrefixProvider *dpp, log_type type, optional_yield y) noexcept; bs::error_code empty_to(const DoutPrefixProvider *dpp, uint64_t gen_id, optional_yield y) noexcept; bs::error_code remove_empty(const DoutPrefixProvider *dpp, optional_yield y) noexcept; // Callbacks, to be defined by descendant. /// Handle initialization on startup /// /// @param e All non-empty generations virtual bs::error_code handle_init(entries_t e) noexcept = 0; /// Handle new generations. /// /// @param e Map of generations added since last update virtual bs::error_code handle_new_gens(entries_t e) noexcept = 0; /// Handle generations being marked empty /// /// @param new_tail Lowest non-empty generation virtual bs::error_code handle_empty_to(uint64_t new_tail) noexcept = 0; }; inline std::string gencursor(uint64_t gen_id, std::string_view cursor) { return (gen_id > 0 ? fmt::format("G{:0>20}@{}", gen_id, cursor) : std::string(cursor)); } inline std::pair<uint64_t, std::string_view> cursorgen(std::string_view cursor_) { if (cursor_.empty()) { return { 0, "" }; } std::string_view cursor = cursor_; if (cursor[0] != 'G') { return { 0, cursor }; } cursor.remove_prefix(1); auto gen_id = ceph::consume<uint64_t>(cursor); if (!gen_id || cursor[0] != '@') { return { 0, cursor_ }; } cursor.remove_prefix(1); return { *gen_id, cursor }; } class LazyFIFO { librados::IoCtx& ioctx; std::string oid; std::mutex m; std::unique_ptr<rgw::cls::fifo::FIFO> fifo; int lazy_init(const DoutPrefixProvider *dpp, optional_yield y) { std::unique_lock l(m); if (fifo) return 0; auto r = rgw::cls::fifo::FIFO::create(dpp, ioctx, oid, &fifo, y); if (r) { fifo.reset(); } return r; } public: LazyFIFO(librados::IoCtx& ioctx, std::string oid) : ioctx(ioctx), oid(std::move(oid)) {} int read_meta(const DoutPrefixProvider *dpp, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; return fifo->read_meta(dpp, y); } int meta(const DoutPrefixProvider *dpp, rados::cls::fifo::info& info, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; info = fifo->meta(); return 0; } int get_part_layout_info(const DoutPrefixProvider *dpp, std::uint32_t& part_header_size, std::uint32_t& part_entry_overhead, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; std::tie(part_header_size, part_entry_overhead) = fifo->get_part_layout_info(); return 0; } int push(const DoutPrefixProvider *dpp, const ceph::buffer::list& bl, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; return fifo->push(dpp, bl, y); } int push(const DoutPrefixProvider *dpp, ceph::buffer::list& bl, librados::AioCompletion* c, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; fifo->push(dpp, bl, c); return 0; } int push(const DoutPrefixProvider *dpp, const std::vector<ceph::buffer::list>& data_bufs, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; return fifo->push(dpp, data_bufs, y); } int push(const DoutPrefixProvider *dpp, const std::vector<ceph::buffer::list>& data_bufs, librados::AioCompletion* c, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; fifo->push(dpp, data_bufs, c); return 0; } int list(const DoutPrefixProvider *dpp, int max_entries, std::optional<std::string_view> markstr, std::vector<rgw::cls::fifo::list_entry>* out, bool* more, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; return fifo->list(dpp, max_entries, markstr, out, more, y); } int list(const DoutPrefixProvider *dpp, int max_entries, std::optional<std::string_view> markstr, std::vector<rgw::cls::fifo::list_entry>* out, bool* more, librados::AioCompletion* c, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; fifo->list(dpp, max_entries, markstr, out, more, c); return 0; } int trim(const DoutPrefixProvider *dpp, std::string_view markstr, bool exclusive, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; return fifo->trim(dpp, markstr, exclusive, y); } int trim(const DoutPrefixProvider *dpp, std::string_view markstr, bool exclusive, librados::AioCompletion* c, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; fifo->trim(dpp, markstr, exclusive, c); return 0; } int get_part_info(const DoutPrefixProvider *dpp, int64_t part_num, rados::cls::fifo::part_header* header, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; return fifo->get_part_info(dpp, part_num, header, y); } int get_part_info(const DoutPrefixProvider *dpp, int64_t part_num, rados::cls::fifo::part_header* header, librados::AioCompletion* c, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; fifo->get_part_info(part_num, header, c); return 0; } int get_head_info(const DoutPrefixProvider *dpp, fu2::unique_function< void(int r, rados::cls::fifo::part_header&&)>&& f, librados::AioCompletion* c, optional_yield y) { auto r = lazy_init(dpp, y); if (r < 0) return r; fifo->get_head_info(dpp, std::move(f), c); return 0; } };
11,255
27.496203
111
h
null
ceph-main/src/rgw/driver/rados/rgw_object_expirer_core.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <atomic> #include <string> #include <cerrno> #include <sstream> #include <iostream> #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 "common/ceph_mutex.h" #include "common/Cond.h" #include "common/Thread.h" #include "global/global_init.h" #include "include/common_fwd.h" #include "include/utime.h" #include "include/str_list.h" #include "rgw_sal_rados.h" class RGWSI_RADOS; class RGWSI_Zone; class RGWBucketInfo; class cls_timeindex_entry; class RGWObjExpStore { CephContext *cct; RGWSI_RADOS *rados_svc; rgw::sal::RadosStore* driver; public: RGWObjExpStore(CephContext *_cct, RGWSI_RADOS *_rados_svc, rgw::sal::RadosStore* _driver) : cct(_cct), rados_svc(_rados_svc), driver(_driver) {} int objexp_hint_add(const DoutPrefixProvider *dpp, const ceph::real_time& delete_at, const std::string& tenant_name, const std::string& bucket_name, const std::string& bucket_id, const rgw_obj_index_key& obj_key); int objexp_hint_list(const DoutPrefixProvider *dpp, const std::string& oid, const ceph::real_time& start_time, const ceph::real_time& end_time, const int max_entries, const std::string& marker, std::list<cls_timeindex_entry>& entries, /* out */ std::string *out_marker, /* out */ bool *truncated); /* out */ int objexp_hint_trim(const DoutPrefixProvider *dpp, const std::string& oid, const ceph::real_time& start_time, const ceph::real_time& end_time, const std::string& from_marker, const std::string& to_marker, optional_yield y); }; class RGWObjectExpirer { protected: rgw::sal::Driver* driver; RGWObjExpStore exp_store; class OEWorker : public Thread, public DoutPrefixProvider { CephContext *cct; RGWObjectExpirer *oe; ceph::mutex lock = ceph::make_mutex("OEWorker"); ceph::condition_variable cond; public: OEWorker(CephContext * const cct, RGWObjectExpirer * const oe) : cct(cct), oe(oe) { } void *entry() override; void stop(); CephContext *get_cct() const override; unsigned get_subsys() const override; std::ostream& gen_prefix(std::ostream& out) const override; }; OEWorker *worker{nullptr}; std::atomic<bool> down_flag = { false }; public: explicit RGWObjectExpirer(rgw::sal::Driver* _driver) : driver(_driver), exp_store(_driver->ctx(), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados, static_cast<rgw::sal::RadosStore*>(driver)), worker(NULL) { } ~RGWObjectExpirer() { stop_processor(); } int hint_add(const DoutPrefixProvider *dpp, const ceph::real_time& delete_at, const std::string& tenant_name, const std::string& bucket_name, const std::string& bucket_id, const rgw_obj_index_key& obj_key) { return exp_store.objexp_hint_add(dpp, delete_at, tenant_name, bucket_name, bucket_id, obj_key); } int garbage_single_object(const DoutPrefixProvider *dpp, objexp_hint_entry& hint); void garbage_chunk(const DoutPrefixProvider *dpp, std::list<cls_timeindex_entry>& entries, /* in */ bool& need_trim); /* out */ void trim_chunk(const DoutPrefixProvider *dpp, const std::string& shard, const utime_t& from, const utime_t& to, const std::string& from_marker, const std::string& to_marker, optional_yield y); bool process_single_shard(const DoutPrefixProvider *dpp, const std::string& shard, const utime_t& last_run, const utime_t& round_start, optional_yield y); bool inspect_all_shards(const DoutPrefixProvider *dpp, const utime_t& last_run, const utime_t& round_start, optional_yield y); bool going_down(); void start_processor(); void stop_processor(); };
4,865
32.102041
134
h
null
ceph-main/src/rgw/driver/rados/rgw_otp.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_fwd.h" #include "cls/otp/cls_otp_types.h" #include "services/svc_meta_be_otp.h" #include "rgw_basic_types.h" #include "rgw_metadata.h" class RGWObjVersionTracker; class RGWMetadataHandler; class RGWOTPMetadataHandler; class RGWSI_Zone; class RGWSI_OTP; class RGWSI_MetaBackend; class RGWOTPMetadataHandlerBase : public RGWMetadataHandler_GenericMetaBE { public: virtual ~RGWOTPMetadataHandlerBase() {} virtual int init(RGWSI_Zone *zone, RGWSI_MetaBackend *_meta_be, RGWSI_OTP *_otp) = 0; }; class RGWOTPMetaHandlerAllocator { public: static RGWMetadataHandler *alloc(); }; struct RGWOTPInfo { rgw_user uid; otp_devices_list_t devices; }; class RGWOTPCtl { struct Svc { RGWSI_Zone *zone{nullptr}; RGWSI_OTP *otp{nullptr}; } svc; RGWOTPMetadataHandler *meta_handler; RGWSI_MetaBackend_Handler *be_handler; public: RGWOTPCtl(RGWSI_Zone *zone_svc, RGWSI_OTP *otp_svc); void init(RGWOTPMetadataHandler *_meta_handler); struct GetParams { RGWObjVersionTracker *objv_tracker{nullptr}; ceph::real_time *mtime{nullptr}; GetParams() {} GetParams& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } GetParams& set_mtime(ceph::real_time *_mtime) { mtime = _mtime; return *this; } }; struct PutParams { RGWObjVersionTracker *objv_tracker{nullptr}; ceph::real_time mtime; PutParams() {} PutParams& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } PutParams& set_mtime(const ceph::real_time& _mtime) { mtime = _mtime; return *this; } }; struct RemoveParams { RGWObjVersionTracker *objv_tracker{nullptr}; RemoveParams() {} RemoveParams& set_objv_tracker(RGWObjVersionTracker *_objv_tracker) { objv_tracker = _objv_tracker; return *this; } }; int read_all(const rgw_user& uid, RGWOTPInfo *info, optional_yield y, const DoutPrefixProvider *dpp, const GetParams& params = {}); int store_all(const DoutPrefixProvider *dpp, const RGWOTPInfo& info, optional_yield y, const PutParams& params = {}); int remove_all(const DoutPrefixProvider *dpp, const rgw_user& user, optional_yield y, const RemoveParams& params = {}); };
2,559
22.063063
75
h
null
ceph-main/src/rgw/driver/rados/rgw_pubsub_push.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 <memory> #include <stdexcept> #include "include/buffer_fwd.h" #include "include/common_fwd.h" #include "common/async/yield_context.h" // TODO the env should be used as a template parameter to differentiate the source that triggers the pushes class RGWDataSyncEnv; class RGWHTTPArgs; struct rgw_pubsub_s3_event; // endpoint base class all endpoint - types should derive from it class RGWPubSubEndpoint { public: RGWPubSubEndpoint() = default; // endpoint should not be copied RGWPubSubEndpoint(const RGWPubSubEndpoint&) = delete; const RGWPubSubEndpoint& operator=(const RGWPubSubEndpoint&) = delete; typedef std::unique_ptr<RGWPubSubEndpoint> Ptr; // factory method for the actual notification endpoint // derived class specific arguments are passed in http args format // may throw a configuration_error if creation fails static Ptr create(const std::string& endpoint, const std::string& topic, const RGWHTTPArgs& args, CephContext *cct=nullptr); // this method is used in order to send notification (S3 compliant) and wait for completion // in async manner via a coroutine when invoked in the frontend environment virtual int send_to_completion_async(CephContext* cct, const rgw_pubsub_s3_event& event, optional_yield y) = 0; // present as string virtual std::string to_str() const { return ""; } virtual ~RGWPubSubEndpoint() = default; // exception object for configuration error struct configuration_error : public std::logic_error { configuration_error(const std::string& what_arg) : std::logic_error("pubsub endpoint configuration error: " + what_arg) {} }; };
1,776
36.020833
126
h
null
ceph-main/src/rgw/driver/rados/rgw_putobj_processor.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 <optional> #include "rgw_putobj.h" #include "services/svc_rados.h" #include "services/svc_tier_rados.h" #include "rgw_sal.h" #include "rgw_obj_manifest.h" namespace rgw { namespace sal { class RadosStore; } class Aio; namespace putobj { // an object processor with special handling for the first chunk of the head. // the virtual process_first_chunk() function returns a processor to handle the // rest of the object class HeadObjectProcessor : public rgw::sal::ObjectProcessor { uint64_t head_chunk_size; // buffer to capture the first chunk of the head object bufferlist head_data; // initialized after process_first_chunk() to process everything else rgw::sal::DataProcessor *processor = nullptr; uint64_t data_offset = 0; // maximum offset of data written (ie compressed) protected: uint64_t get_actual_size() const { return data_offset; } // process the first chunk of data and return a processor for the rest virtual int process_first_chunk(bufferlist&& data, rgw::sal::DataProcessor **processor) = 0; public: HeadObjectProcessor(uint64_t head_chunk_size) : head_chunk_size(head_chunk_size) {} void set_head_chunk_size(uint64_t size) { head_chunk_size = size; } // cache first chunk for process_first_chunk(), then forward everything else // to the returned processor int process(bufferlist&& data, uint64_t logical_offset) final override; }; using RawObjSet = std::set<rgw_raw_obj>; // a data sink that writes to rados objects and deletes them on cancelation class RadosWriter : public rgw::sal::DataProcessor { Aio *const aio; RGWRados *const store; const RGWBucketInfo& bucket_info; RGWObjectCtx& obj_ctx; const rgw_obj head_obj; RGWSI_RADOS::Obj stripe_obj; // current stripe object RawObjSet written; // set of written objects for deletion const DoutPrefixProvider *dpp; optional_yield y; public: RadosWriter(Aio *aio, RGWRados *store, const RGWBucketInfo& bucket_info, RGWObjectCtx& obj_ctx, const rgw_obj& _head_obj, const DoutPrefixProvider *dpp, optional_yield y) : aio(aio), store(store), bucket_info(bucket_info), obj_ctx(obj_ctx), head_obj(_head_obj), dpp(dpp), y(y) {} ~RadosWriter(); // add alloc hint to osd void add_write_hint(librados::ObjectWriteOperation& op); // change the current stripe object int set_stripe_obj(const rgw_raw_obj& obj); // write the data at the given offset of the current stripe object int process(bufferlist&& data, uint64_t stripe_offset) override; // write the data as an exclusive create and wait for it to complete int write_exclusive(const bufferlist& data); int drain(); // when the operation completes successfully, clear the set of written objects // so they aren't deleted on destruction void clear_written() { written.clear(); } }; // a rados object processor that stripes according to RGWObjManifest class ManifestObjectProcessor : public HeadObjectProcessor, public StripeGenerator { protected: RGWRados* const store; RGWBucketInfo& bucket_info; rgw_placement_rule tail_placement_rule; rgw_user owner; RGWObjectCtx& obj_ctx; rgw_obj head_obj; RadosWriter writer; RGWObjManifest manifest; RGWObjManifest::generator manifest_gen; ChunkProcessor chunk; StripeProcessor stripe; const DoutPrefixProvider *dpp; // implements StripeGenerator int next(uint64_t offset, uint64_t *stripe_size) override; public: ManifestObjectProcessor(Aio *aio, RGWRados* store, RGWBucketInfo& bucket_info, const rgw_placement_rule *ptail_placement_rule, const rgw_user& owner, RGWObjectCtx& _obj_ctx, const rgw_obj& _head_obj, const DoutPrefixProvider* dpp, optional_yield y) : HeadObjectProcessor(0), store(store), bucket_info(bucket_info), owner(owner), obj_ctx(_obj_ctx), head_obj(_head_obj), writer(aio, store, bucket_info, obj_ctx, head_obj, dpp, y), chunk(&writer, 0), stripe(&chunk, this, 0), dpp(dpp) { if (ptail_placement_rule) { tail_placement_rule = *ptail_placement_rule; } } void set_owner(const rgw_user& _owner) { owner = _owner; } void set_tail_placement(const rgw_placement_rule& tpr) { tail_placement_rule = tpr; } void set_tail_placement(const rgw_placement_rule&& tpr) { tail_placement_rule = tpr; } }; // a processor that completes with an atomic write to the head object as part of // a bucket index transaction class AtomicObjectProcessor : public ManifestObjectProcessor { const std::optional<uint64_t> olh_epoch; const std::string unique_tag; bufferlist first_chunk; // written with the head in complete() int process_first_chunk(bufferlist&& data, rgw::sal::DataProcessor **processor) override; public: AtomicObjectProcessor(Aio *aio, RGWRados* store, RGWBucketInfo& bucket_info, const rgw_placement_rule *ptail_placement_rule, const rgw_user& owner, RGWObjectCtx& obj_ctx, const rgw_obj& _head_obj, std::optional<uint64_t> olh_epoch, const std::string& unique_tag, const DoutPrefixProvider *dpp, optional_yield y) : ManifestObjectProcessor(aio, store, bucket_info, ptail_placement_rule, owner, obj_ctx, _head_obj, dpp, y), olh_epoch(olh_epoch), unique_tag(unique_tag) {} // prepare a trivial manifest int prepare(optional_yield y) override; // write the head object atomically in a bucket index transaction 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; }; // a processor for multipart parts, which don't require atomic completion. the // part's head is written with an exclusive create to detect racing uploads of // the same part/upload id, which are restarted with a random oid prefix class MultipartObjectProcessor : public ManifestObjectProcessor { const rgw_obj target_obj; // target multipart object const std::string upload_id; const int part_num; const std::string part_num_str; RGWMPObj mp; // write the first chunk and wait on aio->drain() for its completion. // on EEXIST, retry with random prefix int process_first_chunk(bufferlist&& data, rgw::sal::DataProcessor **processor) override; // prepare the head stripe and manifest int prepare_head(); public: MultipartObjectProcessor(Aio *aio, RGWRados* store, RGWBucketInfo& bucket_info, const rgw_placement_rule *ptail_placement_rule, const rgw_user& owner, RGWObjectCtx& obj_ctx, const rgw_obj& _head_obj, const std::string& upload_id, uint64_t part_num, const std::string& part_num_str, const DoutPrefixProvider *dpp, optional_yield y) : ManifestObjectProcessor(aio, store, bucket_info, ptail_placement_rule, owner, obj_ctx, _head_obj, dpp, y), target_obj(head_obj), upload_id(upload_id), part_num(part_num), part_num_str(part_num_str), mp(head_obj.key.name, upload_id) {} // prepare a multipart manifest int prepare(optional_yield y) override; // write the head object attributes in a bucket index transaction, then // register the completed part with the multipart meta object 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 AppendObjectProcessor : public ManifestObjectProcessor { uint64_t cur_part_num; uint64_t position; uint64_t cur_size; uint64_t *cur_accounted_size; std::string cur_etag; const std::string unique_tag; RGWObjManifest *cur_manifest; int process_first_chunk(bufferlist&& data, rgw::sal::DataProcessor **processor) override; public: AppendObjectProcessor(Aio *aio, RGWRados* store, RGWBucketInfo& bucket_info, const rgw_placement_rule *ptail_placement_rule, const rgw_user& owner, RGWObjectCtx& obj_ctx, const rgw_obj& _head_obj, const std::string& unique_tag, uint64_t position, uint64_t *cur_accounted_size, const DoutPrefixProvider *dpp, optional_yield y) : ManifestObjectProcessor(aio, store, bucket_info, ptail_placement_rule, owner, obj_ctx, _head_obj, dpp, y), position(position), cur_size(0), cur_accounted_size(cur_accounted_size), unique_tag(unique_tag), cur_manifest(nullptr) {} int prepare(optional_yield y) override; 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; }; } // namespace putobj } // namespace rgw
10,568
36.34629
93
h
null
ceph-main/src/rgw/driver/rados/rgw_rest_bucket.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_Bucket : public RGWHandler_Auth_S3 { protected: RGWOp *op_get() override; RGWOp *op_put() override; RGWOp *op_post() override; RGWOp *op_delete() override; public: using RGWHandler_Auth_S3::RGWHandler_Auth_S3; ~RGWHandler_Bucket() override = default; int read_permissions(RGWOp*, optional_yield y) override { return 0; } }; class RGWRESTMgr_Bucket : public RGWRESTMgr { public: RGWRESTMgr_Bucket() = default; ~RGWRESTMgr_Bucket() 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_Bucket(auth_registry); } };
941
24.459459
80
h
null
ceph-main/src/rgw/driver/rados/rgw_rest_log.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_datalog.h" #include "rgw_rest.h" #include "rgw_rest_s3.h" #include "rgw_metadata.h" #include "rgw_mdlog.h" #include "rgw_data_sync.h" class RGWOp_BILog_List : public RGWRESTOp { bool sent_header; uint32_t format_ver{0}; bool truncated{false}; std::optional<rgw::bucket_log_layout_generation> next_log_layout; public: RGWOp_BILog_List() : sent_header(false) {} ~RGWOp_BILog_List() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("bilog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void send_response() override; virtual void send_response(std::list<rgw_bi_log_entry>& entries, std::string& marker); virtual void send_response_end(); void execute(optional_yield y) override; const char* name() const override { return "list_bucket_index_log"; } }; class RGWOp_BILog_Info : public RGWRESTOp { std::string bucket_ver; std::string master_ver; std::string max_marker; bool syncstopped; uint64_t oldest_gen = 0; uint64_t latest_gen = 0; std::vector<store_gen_shards> generations; public: RGWOp_BILog_Info() : bucket_ver(), master_ver(), syncstopped(false) {} ~RGWOp_BILog_Info() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("bilog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void send_response() override; void execute(optional_yield y) override; const char* name() const override { return "bucket_index_log_info"; } }; class RGWOp_BILog_Delete : public RGWRESTOp { public: RGWOp_BILog_Delete() {} ~RGWOp_BILog_Delete() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("bilog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "trim_bucket_index_log"; } }; class RGWOp_MDLog_List : public RGWRESTOp { std::list<cls_log_entry> entries; std::string last_marker; bool truncated; public: RGWOp_MDLog_List() : truncated(false) {} ~RGWOp_MDLog_List() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void execute(optional_yield y) override; void send_response() override; const char* name() const override { return "list_metadata_log"; } }; class RGWOp_MDLog_Info : public RGWRESTOp { unsigned num_objects; RGWPeriodHistory::Cursor period; public: RGWOp_MDLog_Info() : num_objects(0) {} ~RGWOp_MDLog_Info() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void execute(optional_yield y) override; void send_response() override; const char* name() const override { return "get_metadata_log_info"; } }; class RGWOp_MDLog_ShardInfo : public RGWRESTOp { RGWMetadataLogInfo info; public: RGWOp_MDLog_ShardInfo() {} ~RGWOp_MDLog_ShardInfo() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void execute(optional_yield y) override; void send_response() override; const char* name() const override { return "get_metadata_log_shard_info"; } }; class RGWOp_MDLog_Lock : public RGWRESTOp { public: RGWOp_MDLog_Lock() {} ~RGWOp_MDLog_Lock() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "lock_mdlog_object"; } }; class RGWOp_MDLog_Unlock : public RGWRESTOp { public: RGWOp_MDLog_Unlock() {} ~RGWOp_MDLog_Unlock() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "unlock_mdlog_object"; } }; class RGWOp_MDLog_Notify : public RGWRESTOp { public: RGWOp_MDLog_Notify() {} ~RGWOp_MDLog_Notify() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "mdlog_notify"; } RGWOpType get_type() override { return RGW_OP_SYNC_MDLOG_NOTIFY; } }; class RGWOp_MDLog_Delete : public RGWRESTOp { public: RGWOp_MDLog_Delete() {} ~RGWOp_MDLog_Delete() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("mdlog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "trim_metadata_log"; } }; class RGWOp_DATALog_List : public RGWRESTOp { std::vector<rgw_data_change_log_entry> entries; std::string last_marker; bool truncated; bool extra_info; public: RGWOp_DATALog_List() : truncated(false), extra_info(false) {} ~RGWOp_DATALog_List() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("datalog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void execute(optional_yield y) override; void send_response() override; const char* name() const override { return "list_data_changes_log"; } }; class RGWOp_DATALog_Info : public RGWRESTOp { unsigned num_objects; public: RGWOp_DATALog_Info() : num_objects(0) {} ~RGWOp_DATALog_Info() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("datalog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void execute(optional_yield y) override; void send_response() override; const char* name() const override { return "get_data_changes_log_info"; } }; class RGWOp_DATALog_ShardInfo : public RGWRESTOp { RGWDataChangesLogInfo info; public: RGWOp_DATALog_ShardInfo() {} ~RGWOp_DATALog_ShardInfo() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("datalog", RGW_CAP_READ); } int verify_permission(optional_yield y) override { return check_caps(s->user->get_caps()); } void execute(optional_yield y) override; void send_response() override; const char* name() const override { return "get_data_changes_log_shard_info"; } }; class RGWOp_DATALog_Notify : public RGWRESTOp { public: RGWOp_DATALog_Notify() {} ~RGWOp_DATALog_Notify() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("datalog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "datalog_notify"; } RGWOpType get_type() override { return RGW_OP_SYNC_DATALOG_NOTIFY; } }; class RGWOp_DATALog_Notify2 : public RGWRESTOp { rgw_data_notify_entry data_notify; public: RGWOp_DATALog_Notify2() {} ~RGWOp_DATALog_Notify2() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("datalog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "datalog_notify2"; } RGWOpType get_type() override { return RGW_OP_SYNC_DATALOG_NOTIFY2; } }; class RGWOp_DATALog_Delete : public RGWRESTOp { public: RGWOp_DATALog_Delete() {} ~RGWOp_DATALog_Delete() override {} int check_caps(const RGWUserCaps& caps) override { return caps.check_cap("datalog", RGW_CAP_WRITE); } void execute(optional_yield y) override; const char* name() const override { return "trim_data_changes_log"; } }; class RGWHandler_Log : public RGWHandler_Auth_S3 { protected: RGWOp *op_get() override; RGWOp *op_delete() override; RGWOp *op_post() override; int read_permissions(RGWOp*, optional_yield) override { return 0; } public: using RGWHandler_Auth_S3::RGWHandler_Auth_S3; ~RGWHandler_Log() override = default; }; class RGWRESTMgr_Log : public RGWRESTMgr { public: RGWRESTMgr_Log() = default; ~RGWRESTMgr_Log() override = default; RGWHandler_REST* get_handler(rgw::sal::Driver* driver, req_state* const, const rgw::auth::StrategyRegistry& auth_registry, const std::string& frontend_prefixs) override { return new RGWHandler_Log(auth_registry); } };
9,229
26.307692
88
h
null
ceph-main/src/rgw/driver/rados/rgw_rest_pubsub.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "rgw_rest_s3.h" // s3 compliant notification handler factory class RGWHandler_REST_PSNotifs_S3 : public RGWHandler_REST_S3 { protected: int init_permissions(RGWOp* op, optional_yield y) override {return 0;} int read_permissions(RGWOp* op, optional_yield y) override {return 0;} bool supports_quota() override {return false;} RGWOp* op_get() override; RGWOp* op_put() override; RGWOp* op_delete() override; public: using RGWHandler_REST_S3::RGWHandler_REST_S3; virtual ~RGWHandler_REST_PSNotifs_S3() = default; // following are used to generate the operations when invoked by another REST handler static RGWOp* create_get_op(); static RGWOp* create_put_op(); static RGWOp* create_delete_op(); }; // AWS compliant topics handler factory class RGWHandler_REST_PSTopic_AWS : public RGWHandler_REST { const rgw::auth::StrategyRegistry& auth_registry; protected: RGWOp* op_post() override; public: RGWHandler_REST_PSTopic_AWS(const rgw::auth::StrategyRegistry& _auth_registry) : auth_registry(_auth_registry) {} virtual ~RGWHandler_REST_PSTopic_AWS() = default; int postauth_init(optional_yield) override { return 0; } int authorize(const DoutPrefixProvider* dpp, optional_yield y) override; static bool action_exists(const req_state* s); };
1,405
35.051282
87
h
null
ceph-main/src/rgw/driver/rados/rgw_rest_user.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_User : public RGWHandler_Auth_S3 { protected: RGWOp *op_get() override; RGWOp *op_put() override; RGWOp *op_post() override; RGWOp *op_delete() override; public: using RGWHandler_Auth_S3::RGWHandler_Auth_S3; ~RGWHandler_User() override = default; int read_permissions(RGWOp*, optional_yield) override { return 0; } }; class RGWRESTMgr_User : public RGWRESTMgr { public: RGWRESTMgr_User() = default; ~RGWRESTMgr_User() 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_User(auth_registry); } };
927
24.081081
80
h
null
ceph-main/src/rgw/driver/rados/rgw_service.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 <vector> #include <memory> #include "common/async/yield_context.h" #include "rgw_common.h" struct RGWServices_Def; class RGWServiceInstance { friend struct RGWServices_Def; protected: CephContext *cct; enum StartState { StateInit = 0, StateStarting = 1, StateStarted = 2, } start_state{StateInit}; virtual void shutdown() {} virtual int do_start(optional_yield, const DoutPrefixProvider *dpp) { return 0; } public: RGWServiceInstance(CephContext *_cct) : cct(_cct) {} virtual ~RGWServiceInstance(); int start(optional_yield y, const DoutPrefixProvider *dpp); bool is_started() { return (start_state == StateStarted); } CephContext *ctx() { return cct; } }; class RGWSI_Finisher; class RGWSI_Bucket; class RGWSI_Bucket_SObj; class RGWSI_Bucket_Sync; class RGWSI_Bucket_Sync_SObj; class RGWSI_BucketIndex; class RGWSI_BucketIndex_RADOS; class RGWSI_BILog_RADOS; class RGWSI_Cls; class RGWSI_ConfigKey; class RGWSI_ConfigKey_RADOS; class RGWSI_MDLog; class RGWSI_Meta; class RGWSI_MetaBackend; class RGWSI_MetaBackend_SObj; class RGWSI_MetaBackend_OTP; class RGWSI_Notify; class RGWSI_OTP; class RGWSI_RADOS; class RGWSI_Zone; class RGWSI_ZoneUtils; class RGWSI_Quota; class RGWSI_SyncModules; class RGWSI_SysObj; class RGWSI_SysObj_Core; class RGWSI_SysObj_Cache; class RGWSI_User; class RGWSI_User_RADOS; class RGWDataChangesLog; class RGWSI_Role_RADOS; struct RGWServices_Def { bool can_shutdown{false}; bool has_shutdown{false}; std::unique_ptr<RGWSI_Finisher> finisher; std::unique_ptr<RGWSI_Bucket_SObj> bucket_sobj; std::unique_ptr<RGWSI_Bucket_Sync_SObj> bucket_sync_sobj; std::unique_ptr<RGWSI_BucketIndex_RADOS> bi_rados; std::unique_ptr<RGWSI_BILog_RADOS> bilog_rados; std::unique_ptr<RGWSI_Cls> cls; std::unique_ptr<RGWSI_ConfigKey_RADOS> config_key_rados; std::unique_ptr<RGWSI_MDLog> mdlog; std::unique_ptr<RGWSI_Meta> meta; std::unique_ptr<RGWSI_MetaBackend_SObj> meta_be_sobj; std::unique_ptr<RGWSI_MetaBackend_OTP> meta_be_otp; std::unique_ptr<RGWSI_Notify> notify; std::unique_ptr<RGWSI_OTP> otp; std::unique_ptr<RGWSI_RADOS> rados; std::unique_ptr<RGWSI_Zone> zone; std::unique_ptr<RGWSI_ZoneUtils> zone_utils; std::unique_ptr<RGWSI_Quota> quota; std::unique_ptr<RGWSI_SyncModules> sync_modules; std::unique_ptr<RGWSI_SysObj> sysobj; std::unique_ptr<RGWSI_SysObj_Core> sysobj_core; std::unique_ptr<RGWSI_SysObj_Cache> sysobj_cache; std::unique_ptr<RGWSI_User_RADOS> user_rados; std::unique_ptr<RGWDataChangesLog> datalog_rados; std::unique_ptr<RGWSI_Role_RADOS> role_rados; RGWServices_Def(); ~RGWServices_Def(); int init(CephContext *cct, bool have_cache, bool raw_storage, bool run_sync, optional_yield y, const DoutPrefixProvider *dpp); void shutdown(); }; struct RGWServices { RGWServices_Def _svc; CephContext *cct; RGWSI_Finisher *finisher{nullptr}; RGWSI_Bucket *bucket{nullptr}; RGWSI_Bucket_SObj *bucket_sobj{nullptr}; RGWSI_Bucket_Sync *bucket_sync{nullptr}; RGWSI_Bucket_Sync_SObj *bucket_sync_sobj{nullptr}; RGWSI_BucketIndex *bi{nullptr}; RGWSI_BucketIndex_RADOS *bi_rados{nullptr}; RGWSI_BILog_RADOS *bilog_rados{nullptr}; RGWSI_Cls *cls{nullptr}; RGWSI_ConfigKey_RADOS *config_key_rados{nullptr}; RGWSI_ConfigKey *config_key{nullptr}; RGWDataChangesLog *datalog_rados{nullptr}; RGWSI_MDLog *mdlog{nullptr}; RGWSI_Meta *meta{nullptr}; RGWSI_MetaBackend *meta_be_sobj{nullptr}; RGWSI_MetaBackend *meta_be_otp{nullptr}; RGWSI_Notify *notify{nullptr}; RGWSI_OTP *otp{nullptr}; RGWSI_RADOS *rados{nullptr}; RGWSI_Zone *zone{nullptr}; RGWSI_ZoneUtils *zone_utils{nullptr}; RGWSI_Quota *quota{nullptr}; RGWSI_SyncModules *sync_modules{nullptr}; RGWSI_SysObj *sysobj{nullptr}; RGWSI_SysObj_Cache *cache{nullptr}; RGWSI_SysObj_Core *core{nullptr}; RGWSI_User *user{nullptr}; RGWSI_Role_RADOS *role{nullptr}; int do_init(CephContext *cct, bool have_cache, bool raw_storage, bool run_sync, optional_yield y, const DoutPrefixProvider *dpp); int init(CephContext *cct, bool have_cache, bool run_sync, optional_yield y, const DoutPrefixProvider *dpp) { return do_init(cct, have_cache, false, run_sync, y, dpp); } int init_raw(CephContext *cct, bool have_cache, optional_yield y, const DoutPrefixProvider *dpp) { return do_init(cct, have_cache, true, false, y, dpp); } void shutdown() { _svc.shutdown(); } }; class RGWMetadataManager; class RGWMetadataHandler; class RGWUserCtl; class RGWBucketCtl; class RGWOTPCtl; struct RGWCtlDef { struct _meta { std::unique_ptr<RGWMetadataManager> mgr; std::unique_ptr<RGWMetadataHandler> bucket; std::unique_ptr<RGWMetadataHandler> bucket_instance; std::unique_ptr<RGWMetadataHandler> user; std::unique_ptr<RGWMetadataHandler> otp; std::unique_ptr<RGWMetadataHandler> role; _meta(); ~_meta(); } meta; std::unique_ptr<RGWUserCtl> user; std::unique_ptr<RGWBucketCtl> bucket; std::unique_ptr<RGWOTPCtl> otp; RGWCtlDef(); ~RGWCtlDef(); int init(RGWServices& svc, rgw::sal::Driver* driver, const DoutPrefixProvider *dpp); }; struct RGWCtl { CephContext *cct{nullptr}; RGWServices *svc{nullptr}; RGWCtlDef _ctl; struct _meta { RGWMetadataManager *mgr{nullptr}; RGWMetadataHandler *bucket{nullptr}; RGWMetadataHandler *bucket_instance{nullptr}; RGWMetadataHandler *user{nullptr}; RGWMetadataHandler *otp{nullptr}; RGWMetadataHandler *role{nullptr}; } meta; RGWUserCtl *user{nullptr}; RGWBucketCtl *bucket{nullptr}; RGWOTPCtl *otp{nullptr}; int init(RGWServices *_svc, rgw::sal::Driver* driver, const DoutPrefixProvider *dpp); };
5,845
26.064815
131
h
null
ceph-main/src/rgw/driver/rados/rgw_sync_error_repo.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include <optional> #include "include/rados/librados_fwd.hpp" #include "include/buffer_fwd.h" #include "common/ceph_time.h" class RGWSI_RADOS; class RGWCoroutine; struct rgw_raw_obj; struct rgw_bucket_shard; namespace rgw::error_repo { // binary-encode a bucket/shard/gen and return it as a string std::string encode_key(const rgw_bucket_shard& bs, std::optional<uint64_t> gen); // try to decode a key. returns -EINVAL if not in binary format int decode_key(std::string encoded, rgw_bucket_shard& bs, std::optional<uint64_t>& gen); // decode a timestamp as a uint64_t for CMPXATTR_MODE_U64 ceph::real_time decode_value(const ceph::bufferlist& bl); // write an omap key iff the given timestamp is newer int write(librados::ObjectWriteOperation& op, const std::string& key, ceph::real_time timestamp); RGWCoroutine* write_cr(RGWSI_RADOS* rados, const rgw_raw_obj& obj, const std::string& key, ceph::real_time timestamp); // remove an omap key iff there isn't a newer timestamp int remove(librados::ObjectWriteOperation& op, const std::string& key, ceph::real_time timestamp); RGWCoroutine* remove_cr(RGWSI_RADOS* rados, const rgw_raw_obj& obj, const std::string& key, ceph::real_time timestamp); } // namespace rgw::error_repo
1,892
30.55
70
h
null
ceph-main/src/rgw/driver/rados/rgw_sync_module_es_rest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_rest.h" class RGWElasticSyncModuleInstance; class RGWRESTMgr_MDSearch_S3 : public RGWRESTMgr { public: explicit RGWRESTMgr_MDSearch_S3() {} RGWHandler_REST *get_handler(rgw::sal::Driver* driver, req_state* s, const rgw::auth::StrategyRegistry& auth_registry, const std::string& frontend_prefix) override; };
521
26.473684
80
h
null
ceph-main/src/rgw/driver/rados/rgw_sync_trace.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <atomic> #include "common/ceph_mutex.h" #include "common/shunique_lock.h" #include "common/admin_socket.h" #include <set> #include <ostream> #include <string> #include <shared_mutex> #include <boost/circular_buffer.hpp> #define SSTR(o) ({ \ std::stringstream ss; \ ss << o; \ ss.str(); \ }) #define RGW_SNS_FLAG_ACTIVE 1 #define RGW_SNS_FLAG_ERROR 2 class RGWRados; class RGWSyncTraceManager; class RGWSyncTraceNode; class RGWSyncTraceServiceMapThread; using RGWSyncTraceNodeRef = std::shared_ptr<RGWSyncTraceNode>; class RGWSyncTraceNode final { friend class RGWSyncTraceManager; CephContext *cct; RGWSyncTraceNodeRef parent; uint16_t state{0}; std::string status; ceph::mutex lock = ceph::make_mutex("RGWSyncTraceNode::lock"); std::string type; std::string id; std::string prefix; std::string resource_name; uint64_t handle; boost::circular_buffer<std::string> history; // private constructor, create with RGWSyncTraceManager::add_node() RGWSyncTraceNode(CephContext *_cct, uint64_t _handle, const RGWSyncTraceNodeRef& _parent, const std::string& _type, const std::string& _id); public: void set_resource_name(const std::string& s) { resource_name = s; } const std::string& get_resource_name() { return resource_name; } void set_flag(uint16_t s) { state |= s; } void unset_flag(uint16_t s) { state &= ~s; } bool test_flags(uint16_t f) { return (state & f) == f; } void log(int level, const std::string& s); std::string to_str() { return prefix + " " + status; } const std::string& get_prefix() { return prefix; } std::ostream& operator<<(std::ostream& os) { os << to_str(); return os; } boost::circular_buffer<std::string>& get_history() { return history; } bool match(const std::string& search_term, bool search_history); }; class RGWSyncTraceManager : public AdminSocketHook { friend class RGWSyncTraceNode; mutable std::shared_timed_mutex lock; using shunique_lock = ceph::shunique_lock<decltype(lock)>; CephContext *cct; RGWSyncTraceServiceMapThread *service_map_thread{nullptr}; std::map<uint64_t, RGWSyncTraceNodeRef> nodes; boost::circular_buffer<RGWSyncTraceNodeRef> complete_nodes; std::atomic<uint64_t> count = { 0 }; std::list<std::array<std::string, 3> > admin_commands; uint64_t alloc_handle() { return ++count; } void finish_node(RGWSyncTraceNode *node); public: RGWSyncTraceManager(CephContext *_cct, int max_lru) : cct(_cct), complete_nodes(max_lru) {} ~RGWSyncTraceManager(); void init(RGWRados *store); const RGWSyncTraceNodeRef root_node; RGWSyncTraceNodeRef add_node(const RGWSyncTraceNodeRef& parent, const std::string& type, const std::string& id = ""); int hook_to_admin_command(); int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& out) override; std::string get_active_names(); };
3,267
22.014085
93
h
null
ceph-main/src/rgw/driver/rados/rgw_trim_bilog.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) 2017 Red Hat, Inc * * Author: Casey Bodley <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #pragma once #include <memory> #include <string_view> #include "include/common_fwd.h" #include "include/encoding.h" #include "common/ceph_time.h" #include "common/dout.h" #include "rgw_common.h" class RGWCoroutine; class RGWHTTPManager; namespace rgw { namespace sal { class RadosStore; } /// Interface to inform the trim process about which buckets are most active struct BucketChangeObserver { virtual ~BucketChangeObserver() = default; virtual void on_bucket_changed(const std::string_view& bucket_instance) = 0; }; /// Configuration for BucketTrimManager struct BucketTrimConfig { /// time interval in seconds between bucket trim attempts uint32_t trim_interval_sec{0}; /// maximum number of buckets to track with BucketChangeObserver size_t counter_size{0}; /// maximum number of buckets to process each trim interval uint32_t buckets_per_interval{0}; /// minimum number of buckets to choose from the global bucket instance list uint32_t min_cold_buckets_per_interval{0}; /// maximum number of buckets to process in parallel uint32_t concurrent_buckets{0}; /// timeout in ms for bucket trim notify replies uint64_t notify_timeout_ms{0}; /// maximum number of recently trimmed buckets to remember (should be small /// enough for a linear search) size_t recent_size{0}; /// maximum duration to consider a trim as 'recent' (should be some multiple /// of the trim interval, at least) ceph::timespan recent_duration{0}; }; /// fill out the BucketTrimConfig from the ceph context void configure_bucket_trim(CephContext *cct, BucketTrimConfig& config); /// Determines the buckets on which to focus trim activity, using two sources of /// input: the frequency of entries read from the data changes log, and a global /// listing of the bucket.instance metadata. This allows us to trim active /// buckets quickly, while also ensuring that all buckets will eventually trim class BucketTrimManager : public BucketChangeObserver, public DoutPrefixProvider { class Impl; std::unique_ptr<Impl> impl; public: BucketTrimManager(sal::RadosStore *store, const BucketTrimConfig& config); ~BucketTrimManager(); int init(); /// increment a counter for the given bucket instance void on_bucket_changed(const std::string_view& bucket_instance) override; /// create a coroutine to run the bucket trim process every trim interval RGWCoroutine* create_bucket_trim_cr(RGWHTTPManager *http); /// create a coroutine to trim buckets directly via radosgw-admin RGWCoroutine* create_admin_bucket_trim_cr(RGWHTTPManager *http); CephContext *get_cct() const override; unsigned get_subsys() const; std::ostream& gen_prefix(std::ostream& out) const; }; /// provides persistent storage for the trim manager's current position in the /// list of bucket instance metadata struct BucketTrimStatus { std::string marker; //< metadata key of current bucket instance void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(marker, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(marker, p); DECODE_FINISH(p); } static const std::string oid; }; } // namespace rgw WRITE_CLASS_ENCODER(rgw::BucketTrimStatus); int bilog_trim(const DoutPrefixProvider* p, rgw::sal::RadosStore* store, RGWBucketInfo& bucket_info, uint64_t gen, int shard_id, std::string_view start_marker, std::string_view end_marker);
3,920
31.139344
82
h
null
ceph-main/src/rgw/driver/rados/rgw_trim_datalog.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 <vector> #include "common/dout.h" class RGWCoroutine; class RGWRados; class RGWHTTPManager; class utime_t; namespace rgw { namespace sal { class RadosStore; } } // DataLogTrimCR factory function extern RGWCoroutine* create_data_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval); // factory function for datalog trim via radosgw-admin RGWCoroutine* create_admin_data_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, std::vector<std::string>& markers);
965
32.310345
104
h
null
ceph-main/src/rgw/driver/rados/rgw_trim_mdlog.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once class RGWCoroutine; class DoutPrefixProvider; class RGWRados; class RGWHTTPManager; class utime_t; namespace rgw { namespace sal { class RadosStore; } } // MetaLogTrimCR factory function RGWCoroutine* create_meta_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards, utime_t interval); // factory function for mdlog trim via radosgw-admin RGWCoroutine* create_admin_meta_log_trim_cr(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* store, RGWHTTPManager *http, int num_shards);
908
33.961538
74
h
null
ceph-main/src/rgw/driver/rados/sync_fairness.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> namespace rgw::sal { class RadosStore; } struct rgw_raw_obj; class RGWCoroutine; /// watch/notify protocol to coordinate the sharing of sync locks /// /// each gateway generates a set of random bids, and broadcasts them regularly /// to other active gateways. in response, the peer gateways send their own set /// of bids /// /// sync will only lock and process log shards where it holds the highest bid namespace rgw::sync_fairness { class BidManager { public: virtual ~BidManager() {} /// establish a watch, creating the control object if necessary virtual int start() = 0; /// returns true if we're the highest bidder on the given shard index virtual bool is_highest_bidder(std::size_t index) = 0; /// return a coroutine that broadcasts our current bids and records the /// bids from other peers that respond virtual RGWCoroutine* notify_cr() = 0; }; // rados BidManager factory auto create_rados_bid_manager(sal::RadosStore* store, const rgw_raw_obj& watch_obj, std::size_t num_shards) -> std::unique_ptr<BidManager>; } // namespace rgw::sync_fairness
1,584
28.351852
79
h
null
ceph-main/src/rgw/driver/rados/config/impl.h
// 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 "include/rados/librados.hpp" #include "common/dout.h" #include "rgw_basic_types.h" #include "rgw_tools.h" #include "rgw_sal_config.h" namespace rgw::rados { // write options that control object creation enum class Create { MustNotExist, // fail with EEXIST if the object already exists MayExist, // create if the object didn't exist, overwrite if it did MustExist, // fail with ENOENT if the object doesn't exist }; struct ConfigImpl { librados::Rados rados; const rgw_pool realm_pool; const rgw_pool period_pool; const rgw_pool zonegroup_pool; const rgw_pool zone_pool; ConfigImpl(const ceph::common::ConfigProxy& conf); int read(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, bufferlist& bl, RGWObjVersionTracker* objv); template <typename T> int read(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, T& data, RGWObjVersionTracker* objv) { bufferlist bl; int r = read(dpp, y, pool, oid, bl, objv); if (r < 0) { return r; } try { auto p = bl.cbegin(); decode(data, p); } catch (const buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: failed to decode obj from " << pool << ":" << oid << dendl; return -EIO; } return 0; } int write(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, Create create, const bufferlist& bl, RGWObjVersionTracker* objv); template <typename T> int write(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, Create create, const T& data, RGWObjVersionTracker* objv) { bufferlist bl; encode(data, bl); return write(dpp, y, pool, oid, create, bl, objv); } int remove(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, RGWObjVersionTracker* objv); int list(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& marker, std::regular_invocable<std::string> auto filter, std::span<std::string> entries, sal::ListResult<std::string>& result) { librados::IoCtx ioctx; int r = rgw_init_ioctx(dpp, &rados, pool, ioctx, true, false); if (r < 0) { return r; } librados::ObjectCursor oc; if (!oc.from_str(marker)) { ldpp_dout(dpp, 10) << "failed to parse cursor: " << marker << dendl; return -EINVAL; } std::size_t count = 0; try { auto iter = ioctx.nobjects_begin(oc); const auto end = ioctx.nobjects_end(); for (; count < entries.size() && iter != end; ++iter) { std::string entry = filter(iter->get_oid()); if (!entry.empty()) { entries[count++] = std::move(entry); } } if (iter == end) { result.next.clear(); } else { result.next = iter.get_cursor().to_str(); } } catch (const std::exception& e) { ldpp_dout(dpp, 10) << "NObjectIterator exception " << e.what() << dendl; return -EIO; } result.entries = entries.first(count); return 0; } int notify(const DoutPrefixProvider* dpp, optional_yield y, const rgw_pool& pool, const std::string& oid, bufferlist& bl, uint64_t timeout_ms); }; inline std::string_view name_or_default(std::string_view name, std::string_view default_name) { if (!name.empty()) { return name; } return default_name; } } // namespace rgw::rados
4,066
28.05
78
h
null
ceph-main/src/rgw/driver/rados/config/store.h
// 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 <list> #include <memory> #include <string> #include "rgw_common.h" #include "rgw_sal_config.h" class DoutPrefixProvider; class optional_yield; namespace rgw::rados { struct ConfigImpl; class RadosConfigStore : public sal::ConfigStore { public: explicit RadosConfigStore(std::unique_ptr<ConfigImpl> impl); virtual ~RadosConfigStore() override; // Realm virtual int write_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id) override; virtual int read_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string& realm_id) override; virtual int delete_default_realm_id(const DoutPrefixProvider* dpp, optional_yield y) override; virtual int create_realm(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_realm_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_realm_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_default_realm(const DoutPrefixProvider* dpp, optional_yield y, RGWRealm& info, std::unique_ptr<sal::RealmWriter>* writer) override; virtual int read_realm_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_name, std::string& realm_id) override; virtual int realm_notify_new_period(const DoutPrefixProvider* dpp, optional_yield y, const RGWPeriod& period) override; virtual int list_realm_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // Period virtual int create_period(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWPeriod& info) override; virtual int read_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id, std::optional<uint32_t> epoch, RGWPeriod& info) override; virtual int delete_period(const DoutPrefixProvider* dpp, optional_yield y, std::string_view period_id) override; virtual int list_period_ids(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // ZoneGroup virtual int write_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zonegroup_id) override; virtual int read_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zonegroup_id) override; virtual int delete_default_zonegroup_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; virtual int create_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int read_zonegroup_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int read_zonegroup_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zonegroup_name, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int read_default_zonegroup(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneGroup& info, std::unique_ptr<sal::ZoneGroupWriter>* writer) override; virtual int list_zonegroup_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // Zone virtual int write_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, std::string_view zone_id) override; virtual int read_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, std::string& zone_id) override; virtual int delete_default_zone_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id) override; virtual int create_zone(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, const RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int read_zone_by_id(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int read_zone_by_name(const DoutPrefixProvider* dpp, optional_yield y, std::string_view zone_name, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int read_default_zone(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWZoneParams& info, std::unique_ptr<sal::ZoneWriter>* writer) override; virtual int list_zone_names(const DoutPrefixProvider* dpp, optional_yield y, const std::string& marker, std::span<std::string> entries, sal::ListResult<std::string>& result) override; // PeriodConfig virtual int read_period_config(const DoutPrefixProvider* dpp, optional_yield y, std::string_view realm_id, RGWPeriodConfig& info) override; virtual int write_period_config(const DoutPrefixProvider* dpp, optional_yield y, bool exclusive, std::string_view realm_id, const RGWPeriodConfig& info) override; private: std::unique_ptr<ConfigImpl> impl; }; // RadosConfigStore /// RadosConfigStore factory function auto create_config_store(const DoutPrefixProvider* dpp) -> std::unique_ptr<RadosConfigStore>; } // namespace rgw::rados
9,218
49.377049
93
h
null
ceph-main/src/rgw/jwt-cpp/base.h
#pragma once #include <string> #include <array> namespace jwt { namespace alphabet { struct base64 { static const std::array<char, 64>& data() { static std::array<char, 64> data = { {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}}; return data; }; static const std::string& fill() { static std::string fill = "="; return fill; } }; struct base64url { static const std::array<char, 64>& data() { static std::array<char, 64> data = { {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'}}; return data; }; static const std::string& fill() { static std::string fill = "%3d"; return fill; } }; } class base { public: template<typename T> static std::string encode(const std::string& bin) { return encode(bin, T::data(), T::fill()); } template<typename T> static std::string decode(const std::string& base) { return decode(base, T::data(), T::fill()); } private: static std::string encode(const std::string& bin, const std::array<char, 64>& alphabet, const std::string& fill) { size_t size = bin.size(); std::string res; // clear incomplete bytes size_t fast_size = size - size % 3; for (size_t i = 0; i < fast_size;) { uint32_t octet_a = (unsigned char)bin[i++]; uint32_t octet_b = (unsigned char)bin[i++]; uint32_t octet_c = (unsigned char)bin[i++]; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; res += alphabet[(triple >> 3 * 6) & 0x3F]; res += alphabet[(triple >> 2 * 6) & 0x3F]; res += alphabet[(triple >> 1 * 6) & 0x3F]; res += alphabet[(triple >> 0 * 6) & 0x3F]; } if (fast_size == size) return res; size_t mod = size % 3; uint32_t octet_a = fast_size < size ? (unsigned char)bin[fast_size++] : 0; uint32_t octet_b = fast_size < size ? (unsigned char)bin[fast_size++] : 0; uint32_t octet_c = fast_size < size ? (unsigned char)bin[fast_size++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; switch (mod) { case 1: res += alphabet[(triple >> 3 * 6) & 0x3F]; res += alphabet[(triple >> 2 * 6) & 0x3F]; res += fill; res += fill; break; case 2: res += alphabet[(triple >> 3 * 6) & 0x3F]; res += alphabet[(triple >> 2 * 6) & 0x3F]; res += alphabet[(triple >> 1 * 6) & 0x3F]; res += fill; break; default: break; } return res; } static std::string decode(const std::string& base, const std::array<char, 64>& alphabet, const std::string& fill) { size_t size = base.size(); size_t fill_cnt = 0; while (size > fill.size()) { if (base.substr(size - fill.size(), fill.size()) == fill) { fill_cnt++; size -= fill.size(); if(fill_cnt > 2) throw std::runtime_error("Invalid input"); } else break; } if ((size + fill_cnt) % 4 != 0) throw std::runtime_error("Invalid input"); size_t out_size = size / 4 * 3; std::string res; res.reserve(out_size); auto get_sextet = [&](size_t offset) { for (size_t i = 0; i < alphabet.size(); i++) { if (alphabet[i] == base[offset]) return i; } throw std::runtime_error("Invalid input"); }; size_t fast_size = size - size % 4; for (size_t i = 0; i < fast_size;) { uint32_t sextet_a = get_sextet(i++); uint32_t sextet_b = get_sextet(i++); uint32_t sextet_c = get_sextet(i++); uint32_t sextet_d = get_sextet(i++); uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); res += (triple >> 2 * 8) & 0xFF; res += (triple >> 1 * 8) & 0xFF; res += (triple >> 0 * 8) & 0xFF; } if (fill_cnt == 0) return res; uint32_t triple = (get_sextet(fast_size) << 3 * 6) + (get_sextet(fast_size + 1) << 2 * 6); switch (fill_cnt) { case 1: triple |= (get_sextet(fast_size + 2) << 1 * 6); res += (triple >> 2 * 8) & 0xFF; res += (triple >> 1 * 8) & 0xFF; break; case 2: res += (triple >> 2 * 8) & 0xFF; break; default: break; } return res; } }; }
5,000
28.591716
117
h
null
ceph-main/src/rgw/services/svc_bucket.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_service.h" #include "svc_bucket_types.h" class RGWSI_Bucket : public RGWServiceInstance { public: RGWSI_Bucket(CephContext *cct) : RGWServiceInstance(cct) {} virtual ~RGWSI_Bucket() {} static std::string get_entrypoint_meta_key(const rgw_bucket& bucket); static std::string get_bi_meta_key(const rgw_bucket& bucket); virtual RGWSI_Bucket_BE_Handler& get_ep_be_handler() = 0; virtual RGWSI_BucketInstance_BE_Handler& get_bi_be_handler() = 0; virtual int read_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWBucketEntryPoint *entry_point, RGWObjVersionTracker *objv_tracker, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none) = 0; virtual int store_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWBucketEntryPoint& info, bool exclusive, real_time mtime, std::map<std::string, bufferlist> *pattrs, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int remove_bucket_entrypoint_info(RGWSI_Bucket_EP_Ctx& ctx, const std::string& key, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int read_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp, rgw_cache_entry_info *cache_info = nullptr, boost::optional<obj_version> refresh_version = boost::none) = 0; virtual int read_bucket_info(RGWSI_Bucket_X_Ctx& ep_ctx, const rgw_bucket& bucket, RGWBucketInfo *info, real_time *pmtime, std::map<std::string, bufferlist> *pattrs, boost::optional<obj_version> refresh_version, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int store_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, RGWBucketInfo& info, std::optional<RGWBucketInfo *> orig_info, /* nullopt: orig_info was not fetched, nullptr: orig_info was not found (new bucket instance */ bool exclusive, real_time mtime, std::map<std::string, bufferlist> *pattrs, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int remove_bucket_instance_info(RGWSI_Bucket_BI_Ctx& ctx, const std::string& key, const RGWBucketInfo& bucket_info, RGWObjVersionTracker *objv_tracker, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int read_bucket_stats(RGWSI_Bucket_X_Ctx& ctx, const rgw_bucket& bucket, RGWBucketEnt *ent, optional_yield y, const DoutPrefixProvider *dpp) = 0; virtual int read_buckets_stats(RGWSI_Bucket_X_Ctx& ctx, std::map<std::string, RGWBucketEnt>& m, optional_yield y, const DoutPrefixProvider *dpp) = 0; };
5,165
45.125
134
h