repo
stringlengths
1
152
file
stringlengths
15
205
code
stringlengths
0
41.6M
file_length
int64
0
41.6M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
90 values
null
ceph-main/src/rgw/rgw_acl.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 <string_view> #include <include/types.h> #include <boost/optional.hpp> #include <boost/algorithm/string/predicate.hpp> #include "common/debug.h" #include "rgw_basic_types.h" //includes rgw_acl_types.h class ACLGrant { protected: ACLGranteeType type; rgw_user id; std::string email; mutable rgw_user email_id; ACLPermission permission; std::string name; ACLGroupTypeEnum group; std::string url_spec; public: ACLGrant() : group(ACL_GROUP_NONE) {} virtual ~ACLGrant() {} /* there's an assumption here that email/uri/id encodings are different and there can't be any overlap */ bool get_id(rgw_user& _id) const { switch(type.get_type()) { case ACL_TYPE_EMAIL_USER: _id = email; // implies from_str() that parses the 't:u' syntax return true; case ACL_TYPE_GROUP: case ACL_TYPE_REFERER: return false; default: _id = id; return true; } } const rgw_user* get_id() const { switch(type.get_type()) { case ACL_TYPE_EMAIL_USER: email_id.from_str(email); return &email_id; case ACL_TYPE_GROUP: case ACL_TYPE_REFERER: return nullptr; default: return &id; } } ACLGranteeType& get_type() { return type; } const ACLGranteeType& get_type() const { return type; } ACLPermission& get_permission() { return permission; } const ACLPermission& get_permission() const { return permission; } ACLGroupTypeEnum get_group() const { return group; } const std::string& get_referer() const { return url_spec; } void encode(bufferlist& bl) const { ENCODE_START(5, 3, bl); encode(type, bl); std::string s; id.to_str(s); encode(s, bl); std::string uri; encode(uri, bl); encode(email, bl); encode(permission, bl); encode(name, bl); __u32 g = (__u32)group; encode(g, bl); encode(url_spec, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(5, 3, 3, bl); decode(type, bl); std::string s; decode(s, bl); id.from_str(s); std::string uri; decode(uri, bl); decode(email, bl); decode(permission, bl); decode(name, bl); if (struct_v > 1) { __u32 g; decode(g, bl); group = (ACLGroupTypeEnum)g; } else { group = uri_to_group(uri); } if (struct_v >= 5) { decode(url_spec, bl); } else { url_spec.clear(); } DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<ACLGrant*>& o); ACLGroupTypeEnum uri_to_group(std::string& uri); void set_canon(const rgw_user& _id, const std::string& _name, const uint32_t perm) { type.set(ACL_TYPE_CANON_USER); id = _id; name = _name; permission.set_permissions(perm); } void set_group(ACLGroupTypeEnum _group, const uint32_t perm) { type.set(ACL_TYPE_GROUP); group = _group; permission.set_permissions(perm); } void set_referer(const std::string& _url_spec, const uint32_t perm) { type.set(ACL_TYPE_REFERER); url_spec = _url_spec; permission.set_permissions(perm); } friend bool operator==(const ACLGrant& lhs, const ACLGrant& rhs); friend bool operator!=(const ACLGrant& lhs, const ACLGrant& rhs); }; WRITE_CLASS_ENCODER(ACLGrant) struct ACLReferer { std::string url_spec; uint32_t perm; ACLReferer() : perm(0) {} ACLReferer(const std::string& url_spec, const uint32_t perm) : url_spec(url_spec), perm(perm) { } bool is_match(std::string_view http_referer) const { const auto http_host = get_http_host(http_referer); if (!http_host || http_host->length() < url_spec.length()) { return false; } if ("*" == url_spec) { return true; } if (http_host->compare(url_spec) == 0) { return true; } if ('.' == url_spec[0]) { /* Wildcard support: a referer matches the spec when its last char are * perfectly equal to spec. */ return boost::algorithm::ends_with(http_host.value(), url_spec); } return false; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(url_spec, bl); encode(perm, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl); decode(url_spec, bl); decode(perm, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; friend bool operator==(const ACLReferer& lhs, const ACLReferer& rhs); friend bool operator!=(const ACLReferer& lhs, const ACLReferer& rhs); private: boost::optional<std::string_view> get_http_host(const std::string_view url) const { size_t pos = url.find("://"); if (pos == std::string_view::npos || boost::algorithm::starts_with(url, "://") || boost::algorithm::ends_with(url, "://") || boost::algorithm::ends_with(url, "@")) { return boost::none; } std::string_view url_sub = url.substr(pos + strlen("://")); pos = url_sub.find('@'); if (pos != std::string_view::npos) { url_sub = url_sub.substr(pos + 1); } pos = url_sub.find_first_of("/:"); if (pos == std::string_view::npos) { /* no port or path exists */ return url_sub; } return url_sub.substr(0, pos); } }; WRITE_CLASS_ENCODER(ACLReferer) namespace rgw { namespace auth { class Identity; } } using ACLGrantMap = std::multimap<std::string, ACLGrant>; class RGWAccessControlList { protected: CephContext *cct; /* FIXME: in the feature we should consider switching to uint32_t also * in data structures. */ std::map<std::string, int> acl_user_map; std::map<uint32_t, int> acl_group_map; std::list<ACLReferer> referer_list; ACLGrantMap grant_map; void _add_grant(ACLGrant *grant); public: explicit RGWAccessControlList(CephContext *_cct) : cct(_cct) {} RGWAccessControlList() : cct(NULL) {} void set_ctx(CephContext *ctx) { cct = ctx; } virtual ~RGWAccessControlList() {} uint32_t get_perm(const DoutPrefixProvider* dpp, const rgw::auth::Identity& auth_identity, uint32_t perm_mask); uint32_t get_group_perm(const DoutPrefixProvider *dpp, ACLGroupTypeEnum group, uint32_t perm_mask) const; uint32_t get_referer_perm(const DoutPrefixProvider *dpp, uint32_t current_perm, std::string http_referer, uint32_t perm_mask); void encode(bufferlist& bl) const { ENCODE_START(4, 3, bl); bool maps_initialized = true; encode(maps_initialized, bl); encode(acl_user_map, bl); encode(grant_map, bl); encode(acl_group_map, bl); encode(referer_list, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(4, 3, 3, bl); bool maps_initialized; decode(maps_initialized, bl); decode(acl_user_map, bl); decode(grant_map, bl); if (struct_v >= 2) { decode(acl_group_map, bl); } else if (!maps_initialized) { ACLGrantMap::iterator iter; for (iter = grant_map.begin(); iter != grant_map.end(); ++iter) { ACLGrant& grant = iter->second; _add_grant(&grant); } } if (struct_v >= 4) { decode(referer_list, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWAccessControlList*>& o); void add_grant(ACLGrant *grant); void remove_canon_user_grant(rgw_user& user_id); ACLGrantMap& get_grant_map() { return grant_map; } const ACLGrantMap& get_grant_map() const { return grant_map; } void create_default(const rgw_user& id, std::string name) { acl_user_map.clear(); acl_group_map.clear(); referer_list.clear(); ACLGrant grant; grant.set_canon(id, name, RGW_PERM_FULL_CONTROL); add_grant(&grant); } friend bool operator==(const RGWAccessControlList& lhs, const RGWAccessControlList& rhs); friend bool operator!=(const RGWAccessControlList& lhs, const RGWAccessControlList& rhs); }; WRITE_CLASS_ENCODER(RGWAccessControlList) class ACLOwner { protected: rgw_user id; std::string display_name; public: ACLOwner() {} ACLOwner(const rgw_user& _id) : id(_id) {} ~ACLOwner() {} void encode(bufferlist& bl) const { ENCODE_START(3, 2, bl); std::string s; id.to_str(s); encode(s, bl); encode(display_name, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(3, 2, 2, bl); std::string s; decode(s, bl); id.from_str(s); decode(display_name, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<ACLOwner*>& o); void set_id(const rgw_user& _id) { id = _id; } void set_name(const std::string& name) { display_name = name; } rgw_user& get_id() { return id; } const rgw_user& get_id() const { return id; } std::string& get_display_name() { return display_name; } const std::string& get_display_name() const { return display_name; } friend bool operator==(const ACLOwner& lhs, const ACLOwner& rhs); friend bool operator!=(const ACLOwner& lhs, const ACLOwner& rhs); }; WRITE_CLASS_ENCODER(ACLOwner) class RGWAccessControlPolicy { protected: CephContext *cct; RGWAccessControlList acl; ACLOwner owner; public: explicit RGWAccessControlPolicy(CephContext *_cct) : cct(_cct), acl(_cct) {} RGWAccessControlPolicy() : cct(NULL), acl(NULL) {} virtual ~RGWAccessControlPolicy() {} void set_ctx(CephContext *ctx) { cct = ctx; acl.set_ctx(ctx); } uint32_t get_perm(const DoutPrefixProvider* dpp, const rgw::auth::Identity& auth_identity, uint32_t perm_mask, const char * http_referer, bool ignore_public_acls=false); bool verify_permission(const DoutPrefixProvider* dpp, const rgw::auth::Identity& auth_identity, uint32_t user_perm_mask, uint32_t perm, const char * http_referer = nullptr, bool ignore_public_acls=false); void encode(bufferlist& bl) const { ENCODE_START(2, 2, bl); encode(owner, bl); encode(acl, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl); decode(owner, bl); decode(acl, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWAccessControlPolicy*>& o); void decode_owner(bufferlist::const_iterator& bl) { // sometimes we only need that, should be faster DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl); decode(owner, bl); DECODE_FINISH(bl); } void set_owner(ACLOwner& o) { owner = o; } ACLOwner& get_owner() { return owner; } void create_default(const rgw_user& id, std::string& name) { acl.create_default(id, name); owner.set_id(id); owner.set_name(name); } RGWAccessControlList& get_acl() { return acl; } const RGWAccessControlList& get_acl() const { return acl; } virtual bool compare_group_name(std::string& id, ACLGroupTypeEnum group) { return false; } bool is_public(const DoutPrefixProvider *dpp) const; friend bool operator==(const RGWAccessControlPolicy& lhs, const RGWAccessControlPolicy& rhs); friend bool operator!=(const RGWAccessControlPolicy& lhs, const RGWAccessControlPolicy& rhs); }; WRITE_CLASS_ENCODER(RGWAccessControlPolicy)
11,762
27.344578
107
h
null
ceph-main/src/rgw/rgw_acl_s3.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <string.h> #include <iostream> #include <map> #include "include/types.h" #include "rgw_acl_s3.h" #include "rgw_user.h" #include "rgw_sal.h" #define dout_subsys ceph_subsys_rgw #define RGW_URI_ALL_USERS "http://acs.amazonaws.com/groups/global/AllUsers" #define RGW_URI_AUTH_USERS "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" using namespace std; static string rgw_uri_all_users = RGW_URI_ALL_USERS; static string rgw_uri_auth_users = RGW_URI_AUTH_USERS; void ACLPermission_S3::to_xml(ostream& out) { if ((flags & RGW_PERM_FULL_CONTROL) == RGW_PERM_FULL_CONTROL) { out << "<Permission>FULL_CONTROL</Permission>"; } else { if (flags & RGW_PERM_READ) out << "<Permission>READ</Permission>"; if (flags & RGW_PERM_WRITE) out << "<Permission>WRITE</Permission>"; if (flags & RGW_PERM_READ_ACP) out << "<Permission>READ_ACP</Permission>"; if (flags & RGW_PERM_WRITE_ACP) out << "<Permission>WRITE_ACP</Permission>"; } } bool ACLPermission_S3:: xml_end(const char *el) { const char *s = data.c_str(); if (strcasecmp(s, "READ") == 0) { flags |= RGW_PERM_READ; return true; } else if (strcasecmp(s, "WRITE") == 0) { flags |= RGW_PERM_WRITE; return true; } else if (strcasecmp(s, "READ_ACP") == 0) { flags |= RGW_PERM_READ_ACP; return true; } else if (strcasecmp(s, "WRITE_ACP") == 0) { flags |= RGW_PERM_WRITE_ACP; return true; } else if (strcasecmp(s, "FULL_CONTROL") == 0) { flags |= RGW_PERM_FULL_CONTROL; return true; } return false; } class ACLGranteeType_S3 { public: static const char *to_string(ACLGranteeType& type) { switch (type.get_type()) { case ACL_TYPE_CANON_USER: return "CanonicalUser"; case ACL_TYPE_EMAIL_USER: return "AmazonCustomerByEmail"; case ACL_TYPE_GROUP: return "Group"; default: return "unknown"; } } static void set(const char *s, ACLGranteeType& type) { if (!s) { type.set(ACL_TYPE_UNKNOWN); return; } if (strcmp(s, "CanonicalUser") == 0) type.set(ACL_TYPE_CANON_USER); else if (strcmp(s, "AmazonCustomerByEmail") == 0) type.set(ACL_TYPE_EMAIL_USER); else if (strcmp(s, "Group") == 0) type.set(ACL_TYPE_GROUP); else type.set(ACL_TYPE_UNKNOWN); } }; class ACLID_S3 : public XMLObj { public: ACLID_S3() {} ~ACLID_S3() override {} string& to_str() { return data; } }; class ACLURI_S3 : public XMLObj { public: ACLURI_S3() {} ~ACLURI_S3() override {} }; class ACLEmail_S3 : public XMLObj { public: ACLEmail_S3() {} ~ACLEmail_S3() override {} }; class ACLDisplayName_S3 : public XMLObj { public: ACLDisplayName_S3() {} ~ACLDisplayName_S3() override {} }; bool ACLOwner_S3::xml_end(const char *el) { ACLID_S3 *acl_id = static_cast<ACLID_S3 *>(find_first("ID")); ACLID_S3 *acl_name = static_cast<ACLID_S3 *>(find_first("DisplayName")); // ID is mandatory if (!acl_id) return false; id = acl_id->get_data(); // DisplayName is optional if (acl_name) display_name = acl_name->get_data(); else display_name = ""; return true; } void ACLOwner_S3::to_xml(ostream& out) { string s; id.to_str(s); if (s.empty()) return; out << "<Owner>" << "<ID>" << s << "</ID>"; if (!display_name.empty()) out << "<DisplayName>" << display_name << "</DisplayName>"; out << "</Owner>"; } bool ACLGrant_S3::xml_end(const char *el) { ACLGrantee_S3 *acl_grantee; ACLID_S3 *acl_id; ACLURI_S3 *acl_uri; ACLEmail_S3 *acl_email; ACLPermission_S3 *acl_permission; ACLDisplayName_S3 *acl_name; string uri; acl_grantee = static_cast<ACLGrantee_S3 *>(find_first("Grantee")); if (!acl_grantee) return false; string type_str; if (!acl_grantee->get_attr("xsi:type", type_str)) return false; ACLGranteeType_S3::set(type_str.c_str(), type); acl_permission = static_cast<ACLPermission_S3 *>(find_first("Permission")); if (!acl_permission) return false; permission = *acl_permission; id.clear(); name.clear(); email.clear(); switch (type.get_type()) { case ACL_TYPE_CANON_USER: acl_id = static_cast<ACLID_S3 *>(acl_grantee->find_first("ID")); if (!acl_id) return false; id = acl_id->to_str(); acl_name = static_cast<ACLDisplayName_S3 *>(acl_grantee->find_first("DisplayName")); if (acl_name) name = acl_name->get_data(); break; case ACL_TYPE_GROUP: acl_uri = static_cast<ACLURI_S3 *>(acl_grantee->find_first("URI")); if (!acl_uri) return false; uri = acl_uri->get_data(); group = uri_to_group(uri); break; case ACL_TYPE_EMAIL_USER: acl_email = static_cast<ACLEmail_S3 *>(acl_grantee->find_first("EmailAddress")); if (!acl_email) return false; email = acl_email->get_data(); break; default: // unknown user type return false; }; return true; } void ACLGrant_S3::to_xml(CephContext *cct, ostream& out) { ACLPermission_S3& perm = static_cast<ACLPermission_S3 &>(permission); /* only show s3 compatible permissions */ if (!(perm.get_permissions() & RGW_PERM_ALL_S3)) return; string uri; out << "<Grant>" << "<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"" << ACLGranteeType_S3::to_string(type) << "\">"; switch (type.get_type()) { case ACL_TYPE_CANON_USER: out << "<ID>" << id << "</ID>"; if (name.size()) { out << "<DisplayName>" << name << "</DisplayName>"; } break; case ACL_TYPE_EMAIL_USER: out << "<EmailAddress>" << email << "</EmailAddress>"; break; case ACL_TYPE_GROUP: if (!group_to_uri(group, uri)) { ldout(cct, 0) << "ERROR: group_to_uri failed with group=" << (int)group << dendl; break; } out << "<URI>" << uri << "</URI>"; break; default: break; } out << "</Grantee>"; perm.to_xml(out); out << "</Grant>"; } bool ACLGrant_S3::group_to_uri(ACLGroupTypeEnum group, string& uri) { switch (group) { case ACL_GROUP_ALL_USERS: uri = rgw_uri_all_users; return true; case ACL_GROUP_AUTHENTICATED_USERS: uri = rgw_uri_auth_users; return true; default: return false; } } bool RGWAccessControlList_S3::xml_end(const char *el) { XMLObjIter iter = find("Grant"); ACLGrant_S3 *grant = static_cast<ACLGrant_S3 *>(iter.get_next()); while (grant) { add_grant(grant); grant = static_cast<ACLGrant_S3 *>(iter.get_next()); } return true; } void RGWAccessControlList_S3::to_xml(ostream& out) { multimap<string, ACLGrant>::iterator iter; out << "<AccessControlList>"; for (iter = grant_map.begin(); iter != grant_map.end(); ++iter) { ACLGrant_S3& grant = static_cast<ACLGrant_S3 &>(iter->second); grant.to_xml(cct, out); } out << "</AccessControlList>"; } struct s3_acl_header { int rgw_perm; const char *http_header; }; static const char *get_acl_header(const RGWEnv *env, const struct s3_acl_header *perm) { const char *header = perm->http_header; return env->get(header, NULL); } static int parse_grantee_str(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, string& grantee_str, const struct s3_acl_header *perm, ACLGrant& grant) { string id_type, id_val_quoted; int rgw_perm = perm->rgw_perm; int ret; ret = parse_key_value(grantee_str, id_type, id_val_quoted); if (ret < 0) return ret; string id_val = rgw_trim_quotes(id_val_quoted); if (strcasecmp(id_type.c_str(), "emailAddress") == 0) { std::unique_ptr<rgw::sal::User> user; ret = driver->get_user_by_email(dpp, id_val, null_yield, &user); if (ret < 0) return ret; grant.set_canon(user->get_id(), user->get_display_name(), rgw_perm); } else if (strcasecmp(id_type.c_str(), "id") == 0) { std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(id_val)); ret = user->load_user(dpp, null_yield); if (ret < 0) return ret; grant.set_canon(user->get_id(), user->get_display_name(), rgw_perm); } else if (strcasecmp(id_type.c_str(), "uri") == 0) { ACLGroupTypeEnum gid = grant.uri_to_group(id_val); if (gid == ACL_GROUP_NONE) return -EINVAL; grant.set_group(gid, rgw_perm); } else { return -EINVAL; } return 0; } static int parse_acl_header(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const RGWEnv *env, const struct s3_acl_header *perm, std::list<ACLGrant>& _grants) { std::list<string> grantees; std::string hacl_str; const char *hacl = get_acl_header(env, perm); if (hacl == NULL) return 0; hacl_str = hacl; get_str_list(hacl_str, ",", grantees); for (list<string>::iterator it = grantees.begin(); it != grantees.end(); ++it) { ACLGrant grant; int ret = parse_grantee_str(dpp, driver, *it, perm, grant); if (ret < 0) return ret; _grants.push_back(grant); } return 0; } int RGWAccessControlList_S3::create_canned(ACLOwner& owner, ACLOwner& bucket_owner, const string& canned_acl) { acl_user_map.clear(); grant_map.clear(); ACLGrant owner_grant; rgw_user bid = bucket_owner.get_id(); string bname = bucket_owner.get_display_name(); /* owner gets full control */ owner_grant.set_canon(owner.get_id(), owner.get_display_name(), RGW_PERM_FULL_CONTROL); add_grant(&owner_grant); if (canned_acl.size() == 0 || canned_acl.compare("private") == 0) { return 0; } ACLGrant bucket_owner_grant; ACLGrant group_grant; if (canned_acl.compare("public-read") == 0) { group_grant.set_group(ACL_GROUP_ALL_USERS, RGW_PERM_READ); add_grant(&group_grant); } else if (canned_acl.compare("public-read-write") == 0) { group_grant.set_group(ACL_GROUP_ALL_USERS, RGW_PERM_READ); add_grant(&group_grant); group_grant.set_group(ACL_GROUP_ALL_USERS, RGW_PERM_WRITE); add_grant(&group_grant); } else if (canned_acl.compare("authenticated-read") == 0) { group_grant.set_group(ACL_GROUP_AUTHENTICATED_USERS, RGW_PERM_READ); add_grant(&group_grant); } else if (canned_acl.compare("bucket-owner-read") == 0) { bucket_owner_grant.set_canon(bid, bname, RGW_PERM_READ); if (bid.compare(owner.get_id()) != 0) add_grant(&bucket_owner_grant); } else if (canned_acl.compare("bucket-owner-full-control") == 0) { bucket_owner_grant.set_canon(bid, bname, RGW_PERM_FULL_CONTROL); if (bid.compare(owner.get_id()) != 0) add_grant(&bucket_owner_grant); } else { return -EINVAL; } return 0; } int RGWAccessControlList_S3::create_from_grants(std::list<ACLGrant>& grants) { if (grants.empty()) return -EINVAL; acl_user_map.clear(); grant_map.clear(); for (std::list<ACLGrant>::iterator it = grants.begin(); it != grants.end(); ++it) { ACLGrant g = *it; add_grant(&g); } return 0; } bool RGWAccessControlPolicy_S3::xml_end(const char *el) { RGWAccessControlList_S3 *s3acl = static_cast<RGWAccessControlList_S3 *>(find_first("AccessControlList")); if (!s3acl) return false; acl = *s3acl; ACLOwner *owner_p = static_cast<ACLOwner_S3 *>(find_first("Owner")); if (!owner_p) return false; owner = *owner_p; return true; } void RGWAccessControlPolicy_S3::to_xml(ostream& out) { out << "<AccessControlPolicy xmlns=\"" << XMLNS_AWS_S3 << "\">"; ACLOwner_S3& _owner = static_cast<ACLOwner_S3 &>(owner); RGWAccessControlList_S3& _acl = static_cast<RGWAccessControlList_S3 &>(acl); _owner.to_xml(out); _acl.to_xml(out); out << "</AccessControlPolicy>"; } static const s3_acl_header acl_header_perms[] = { {RGW_PERM_READ, "HTTP_X_AMZ_GRANT_READ"}, {RGW_PERM_WRITE, "HTTP_X_AMZ_GRANT_WRITE"}, {RGW_PERM_READ_ACP,"HTTP_X_AMZ_GRANT_READ_ACP"}, {RGW_PERM_WRITE_ACP, "HTTP_X_AMZ_GRANT_WRITE_ACP"}, {RGW_PERM_FULL_CONTROL, "HTTP_X_AMZ_GRANT_FULL_CONTROL"}, {0, NULL} }; int RGWAccessControlPolicy_S3::create_from_headers(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const RGWEnv *env, ACLOwner& _owner) { std::list<ACLGrant> grants; int r = 0; for (const struct s3_acl_header *p = acl_header_perms; p->rgw_perm; p++) { r = parse_acl_header(dpp, driver, env, p, grants); if (r < 0) { return r; } } RGWAccessControlList_S3& _acl = static_cast<RGWAccessControlList_S3 &>(acl); r = _acl.create_from_grants(grants); owner = _owner; return r; } /* can only be called on object that was parsed */ int RGWAccessControlPolicy_S3::rebuild(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, ACLOwner *owner, RGWAccessControlPolicy& dest, std::string &err_msg) { if (!owner) return -EINVAL; ACLOwner *requested_owner = static_cast<ACLOwner_S3 *>(find_first("Owner")); if (requested_owner) { rgw_user& requested_id = requested_owner->get_id(); if (!requested_id.empty() && requested_id.compare(owner->get_id()) != 0) return -EPERM; } std::unique_ptr<rgw::sal::User> user = driver->get_user(owner->get_id()); if (user->load_user(dpp, null_yield) < 0) { ldpp_dout(dpp, 10) << "owner info does not exist" << dendl; err_msg = "Invalid id"; return -EINVAL; } ACLOwner& dest_owner = dest.get_owner(); dest_owner.set_id(owner->get_id()); dest_owner.set_name(user->get_display_name()); ldpp_dout(dpp, 20) << "owner id=" << owner->get_id() << dendl; ldpp_dout(dpp, 20) << "dest owner id=" << dest.get_owner().get_id() << dendl; RGWAccessControlList& dst_acl = dest.get_acl(); multimap<string, ACLGrant>& grant_map = acl.get_grant_map(); multimap<string, ACLGrant>::iterator iter; for (iter = grant_map.begin(); iter != grant_map.end(); ++iter) { ACLGrant& src_grant = iter->second; ACLGranteeType& type = src_grant.get_type(); ACLGrant new_grant; bool grant_ok = false; rgw_user uid; RGWUserInfo grant_user; switch (type.get_type()) { case ACL_TYPE_EMAIL_USER: { string email; rgw_user u; if (!src_grant.get_id(u)) { ldpp_dout(dpp, 0) << "ERROR: src_grant.get_id() failed" << dendl; return -EINVAL; } email = u.id; ldpp_dout(dpp, 10) << "grant user email=" << email << dendl; if (driver->get_user_by_email(dpp, email, null_yield, &user) < 0) { ldpp_dout(dpp, 10) << "grant user email not found or other error" << dendl; err_msg = "The e-mail address you provided does not match any account on record."; return -ERR_UNRESOLVABLE_EMAIL; } grant_user = user->get_info(); uid = grant_user.user_id; } case ACL_TYPE_CANON_USER: { if (type.get_type() == ACL_TYPE_CANON_USER) { if (!src_grant.get_id(uid)) { ldpp_dout(dpp, 0) << "ERROR: src_grant.get_id() failed" << dendl; err_msg = "Invalid id"; return -EINVAL; } } if (grant_user.user_id.empty()) { user = driver->get_user(uid); if (user->load_user(dpp, null_yield) < 0) { ldpp_dout(dpp, 10) << "grant user does not exist:" << uid << dendl; err_msg = "Invalid id"; return -EINVAL; } else { grant_user = user->get_info(); } } ACLPermission& perm = src_grant.get_permission(); new_grant.set_canon(uid, grant_user.display_name, perm.get_permissions()); grant_ok = true; rgw_user new_id; new_grant.get_id(new_id); ldpp_dout(dpp, 10) << "new grant: " << new_id << ":" << grant_user.display_name << dendl; } break; case ACL_TYPE_GROUP: { string uri; if (ACLGrant_S3::group_to_uri(src_grant.get_group(), uri)) { new_grant = src_grant; grant_ok = true; ldpp_dout(dpp, 10) << "new grant: " << uri << dendl; } else { ldpp_dout(dpp, 10) << "bad grant group:" << (int)src_grant.get_group() << dendl; err_msg = "Invalid group uri"; return -EINVAL; } } default: break; } if (grant_ok) { dst_acl.add_grant(&new_grant); } } return 0; } bool RGWAccessControlPolicy_S3::compare_group_name(string& id, ACLGroupTypeEnum group) { switch (group) { case ACL_GROUP_ALL_USERS: return (id.compare(RGW_USER_ANON_ID) == 0); case ACL_GROUP_AUTHENTICATED_USERS: return (id.compare(rgw_uri_auth_users) == 0); default: return id.empty(); } // shouldn't get here return false; } XMLObj *RGWACLXMLParser_S3::alloc_obj(const char *el) { XMLObj * obj = NULL; if (strcmp(el, "AccessControlPolicy") == 0) { obj = new RGWAccessControlPolicy_S3(cct); } else if (strcmp(el, "Owner") == 0) { obj = new ACLOwner_S3(); } else if (strcmp(el, "AccessControlList") == 0) { obj = new RGWAccessControlList_S3(cct); } else if (strcmp(el, "ID") == 0) { obj = new ACLID_S3(); } else if (strcmp(el, "DisplayName") == 0) { obj = new ACLDisplayName_S3(); } else if (strcmp(el, "Grant") == 0) { obj = new ACLGrant_S3(); } else if (strcmp(el, "Grantee") == 0) { obj = new ACLGrantee_S3(); } else if (strcmp(el, "Permission") == 0) { obj = new ACLPermission_S3(); } else if (strcmp(el, "URI") == 0) { obj = new ACLURI_S3(); } else if (strcmp(el, "EmailAddress") == 0) { obj = new ACLEmail_S3(); } return obj; } ACLGroupTypeEnum ACLGrant_S3::uri_to_group(string& uri) { if (uri.compare(rgw_uri_all_users) == 0) return ACL_GROUP_ALL_USERS; else if (uri.compare(rgw_uri_auth_users) == 0) return ACL_GROUP_AUTHENTICATED_USERS; return ACL_GROUP_NONE; }
17,626
26.371118
135
cc
null
ceph-main/src/rgw/rgw_acl_s3.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <map> #include <string> #include <iosfwd> #include <include/types.h> #include "include/str_list.h" #include "rgw_xml.h" #include "rgw_acl.h" #include "rgw_sal_fwd.h" class RGWUserCtl; class ACLPermission_S3 : public ACLPermission, public XMLObj { public: ACLPermission_S3() {} virtual ~ACLPermission_S3() override {} bool xml_end(const char *el) override; void to_xml(std::ostream& out); }; class ACLGrantee_S3 : public ACLGrantee, public XMLObj { public: ACLGrantee_S3() {} virtual ~ACLGrantee_S3() override {} bool xml_start(const char *el, const char **attr); }; class ACLGrant_S3 : public ACLGrant, public XMLObj { public: ACLGrant_S3() {} virtual ~ACLGrant_S3() override {} void to_xml(CephContext *cct, std::ostream& out); bool xml_end(const char *el) override; bool xml_start(const char *el, const char **attr); static ACLGroupTypeEnum uri_to_group(std::string& uri); static bool group_to_uri(ACLGroupTypeEnum group, std::string& uri); }; class RGWAccessControlList_S3 : public RGWAccessControlList, public XMLObj { public: explicit RGWAccessControlList_S3(CephContext *_cct) : RGWAccessControlList(_cct) {} virtual ~RGWAccessControlList_S3() override {} bool xml_end(const char *el) override; void to_xml(std::ostream& out); int create_canned(ACLOwner& owner, ACLOwner& bucket_owner, const std::string& canned_acl); int create_from_grants(std::list<ACLGrant>& grants); }; class ACLOwner_S3 : public ACLOwner, public XMLObj { public: ACLOwner_S3() {} virtual ~ACLOwner_S3() override {} bool xml_end(const char *el) override; void to_xml(std::ostream& out); }; class RGWEnv; class RGWAccessControlPolicy_S3 : public RGWAccessControlPolicy, public XMLObj { public: explicit RGWAccessControlPolicy_S3(CephContext *_cct) : RGWAccessControlPolicy(_cct) {} virtual ~RGWAccessControlPolicy_S3() override {} bool xml_end(const char *el) override; void to_xml(std::ostream& out); int rebuild(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, ACLOwner *owner, RGWAccessControlPolicy& dest, std::string &err_msg); bool compare_group_name(std::string& id, ACLGroupTypeEnum group) override; virtual int create_canned(ACLOwner& _owner, ACLOwner& bucket_owner, const std::string& canned_acl) { RGWAccessControlList_S3& _acl = static_cast<RGWAccessControlList_S3 &>(acl); if (_owner.get_id() == rgw_user("anonymous")) { owner = bucket_owner; } else { owner = _owner; } int ret = _acl.create_canned(owner, bucket_owner, canned_acl); return ret; } int create_from_headers(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const RGWEnv *env, ACLOwner& _owner); }; /** * Interfaces with the webserver's XML handling code * to parse it in a way that makes sense for the rgw. */ class RGWACLXMLParser_S3 : public RGWXMLParser { CephContext *cct; XMLObj *alloc_obj(const char *el) override; public: explicit RGWACLXMLParser_S3(CephContext *_cct) : cct(_cct) {} };
3,136
26.043103
102
h
null
ceph-main/src/rgw/rgw_acl_swift.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <string.h> #include <vector> #include <boost/algorithm/string/predicate.hpp> #include "common/ceph_json.h" #include "rgw_common.h" #include "rgw_user.h" #include "rgw_acl_swift.h" #include "rgw_sal.h" #define dout_subsys ceph_subsys_rgw #define SWIFT_PERM_READ RGW_PERM_READ_OBJS #define SWIFT_PERM_WRITE RGW_PERM_WRITE_OBJS /* FIXME: do we really need separate RW? */ #define SWIFT_PERM_RWRT (SWIFT_PERM_READ | SWIFT_PERM_WRITE) #define SWIFT_PERM_ADMIN RGW_PERM_FULL_CONTROL #define SWIFT_GROUP_ALL_USERS ".r:*" using namespace std; static int parse_list(const char* uid_list, std::vector<std::string>& uids) /* out */ { char *s = strdup(uid_list); if (!s) { return -ENOMEM; } char *tokctx; const char *p = strtok_r(s, " ,", &tokctx); while (p) { if (*p) { string acl = p; uids.push_back(acl); } p = strtok_r(NULL, " ,", &tokctx); } free(s); return 0; } static bool is_referrer(const std::string& designator) { return designator.compare(".r") == 0 || designator.compare(".ref") == 0 || designator.compare(".referer") == 0 || designator.compare(".referrer") == 0; } static bool uid_is_public(const string& uid) { if (uid[0] != '.' || uid[1] != 'r') return false; int pos = uid.find(':'); if (pos < 0 || pos == (int)uid.size()) return false; string sub = uid.substr(0, pos); string after = uid.substr(pos + 1); if (after.compare("*") != 0) return false; return is_referrer(sub); } static boost::optional<ACLGrant> referrer_to_grant(std::string url_spec, const uint32_t perm) { /* This function takes url_spec as non-ref std::string because of the trim * operation that is essential to preserve compliance with Swift. It can't * be easily accomplished with std::string_view. */ try { bool is_negative; ACLGrant grant; if ('-' == url_spec[0]) { url_spec = url_spec.substr(1); boost::algorithm::trim(url_spec); is_negative = true; } else { is_negative = false; } if (url_spec != RGW_REFERER_WILDCARD) { if ('*' == url_spec[0]) { url_spec = url_spec.substr(1); boost::algorithm::trim(url_spec); } if (url_spec.empty() || url_spec == ".") { return boost::none; } } else { /* Please be aware we're specially handling the .r:* in _add_grant() * of RGWAccessControlList as the S3 API has a similar concept, and * thus we can have a small portion of compatibility. */ } grant.set_referer(url_spec, is_negative ? 0 : perm); return grant; } catch (const std::out_of_range&) { return boost::none; } } static ACLGrant user_to_grant(const DoutPrefixProvider *dpp, CephContext* const cct, rgw::sal::Driver* driver, const std::string& uid, const uint32_t perm) { RGWUserInfo grant_user; ACLGrant grant; std::unique_ptr<rgw::sal::User> user; user = driver->get_user(rgw_user(uid)); if (user->load_user(dpp, null_yield) < 0) { ldpp_dout(dpp, 10) << "grant user does not exist: " << uid << dendl; /* skipping silently */ grant.set_canon(user->get_id(), std::string(), perm); } else { grant.set_canon(user->get_id(), user->get_display_name(), perm); } return grant; } int RGWAccessControlPolicy_SWIFT::add_grants(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const std::vector<std::string>& uids, const uint32_t perm) { for (const auto& uid : uids) { boost::optional<ACLGrant> grant; ldpp_dout(dpp, 20) << "trying to add grant for ACL uid=" << uid << dendl; /* Let's check whether the item has a separator potentially indicating * a special meaning (like an HTTP referral-based grant). */ const size_t pos = uid.find(':'); if (std::string::npos == pos) { /* No, it don't have -- we've got just a regular user identifier. */ grant = user_to_grant(dpp, cct, driver, uid, perm); } else { /* Yes, *potentially* an HTTP referral. */ auto designator = uid.substr(0, pos); auto designatee = uid.substr(pos + 1); /* Swift strips whitespaces at both beginning and end. */ boost::algorithm::trim(designator); boost::algorithm::trim(designatee); if (! boost::algorithm::starts_with(designator, ".")) { grant = user_to_grant(dpp, cct, driver, uid, perm); } else if ((perm & SWIFT_PERM_WRITE) == 0 && is_referrer(designator)) { /* HTTP referrer-based ACLs aren't acceptable for writes. */ grant = referrer_to_grant(designatee, perm); } } if (grant) { acl.add_grant(&*grant); } else { return -EINVAL; } } return 0; } int RGWAccessControlPolicy_SWIFT::create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const rgw_user& id, const std::string& name, const char* read_list, const char* write_list, uint32_t& rw_mask) { acl.create_default(id, name); owner.set_id(id); owner.set_name(name); rw_mask = 0; if (read_list) { std::vector<std::string> uids; int r = parse_list(read_list, uids); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: parse_list for read returned r=" << r << dendl; return r; } r = add_grants(dpp, driver, uids, SWIFT_PERM_READ); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: add_grants for read returned r=" << r << dendl; return r; } rw_mask |= SWIFT_PERM_READ; } if (write_list) { std::vector<std::string> uids; int r = parse_list(write_list, uids); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: parse_list for write returned r=" << r << dendl; return r; } r = add_grants(dpp, driver, uids, SWIFT_PERM_WRITE); if (r < 0) { ldpp_dout(dpp, 0) << "ERROR: add_grants for write returned r=" << r << dendl; return r; } rw_mask |= SWIFT_PERM_WRITE; } return 0; } void RGWAccessControlPolicy_SWIFT::filter_merge(uint32_t rw_mask, RGWAccessControlPolicy_SWIFT *old) { /* rw_mask&SWIFT_PERM_READ => setting read acl, * rw_mask&SWIFT_PERM_WRITE => setting write acl * when bit is cleared, copy matching elements from old. */ if (rw_mask == (SWIFT_PERM_READ|SWIFT_PERM_WRITE)) { return; } rw_mask ^= (SWIFT_PERM_READ|SWIFT_PERM_WRITE); for (auto &iter: old->acl.get_grant_map()) { ACLGrant& grant = iter.second; uint32_t perm = grant.get_permission().get_permissions(); rgw_user id; string url_spec; if (!grant.get_id(id)) { if (grant.get_group() != ACL_GROUP_ALL_USERS) { url_spec = grant.get_referer(); if (url_spec.empty()) { continue; } if (perm == 0) { /* We need to carry also negative, HTTP referrer-based ACLs. */ perm = SWIFT_PERM_READ; } } } if (perm & rw_mask) { acl.add_grant(&grant); } } } void RGWAccessControlPolicy_SWIFT::to_str(string& read, string& write) { multimap<string, ACLGrant>& m = acl.get_grant_map(); multimap<string, ACLGrant>::iterator iter; for (iter = m.begin(); iter != m.end(); ++iter) { ACLGrant& grant = iter->second; const uint32_t perm = grant.get_permission().get_permissions(); rgw_user id; string url_spec; if (!grant.get_id(id)) { if (grant.get_group() == ACL_GROUP_ALL_USERS) { id = SWIFT_GROUP_ALL_USERS; } else { url_spec = grant.get_referer(); if (url_spec.empty()) { continue; } id = (perm != 0) ? ".r:" + url_spec : ".r:-" + url_spec; } } if (perm & SWIFT_PERM_READ) { if (!read.empty()) { read.append(","); } read.append(id.to_str()); } else if (perm & SWIFT_PERM_WRITE) { if (!write.empty()) { write.append(","); } write.append(id.to_str()); } else if (perm == 0 && !url_spec.empty()) { /* only X-Container-Read headers support referers */ if (!read.empty()) { read.append(","); } read.append(id.to_str()); } } } void RGWAccessControlPolicy_SWIFTAcct::add_grants(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const std::vector<std::string>& uids, const uint32_t perm) { for (const auto& uid : uids) { ACLGrant grant; if (uid_is_public(uid)) { grant.set_group(ACL_GROUP_ALL_USERS, perm); acl.add_grant(&grant); } else { std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(uid)); if (user->load_user(dpp, null_yield) < 0) { ldpp_dout(dpp, 10) << "grant user does not exist:" << uid << dendl; /* skipping silently */ grant.set_canon(user->get_id(), std::string(), perm); acl.add_grant(&grant); } else { grant.set_canon(user->get_id(), user->get_display_name(), perm); acl.add_grant(&grant); } } } } bool RGWAccessControlPolicy_SWIFTAcct::create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const rgw_user& id, const std::string& name, const std::string& acl_str) { acl.create_default(id, name); owner.set_id(id); owner.set_name(name); JSONParser parser; if (!parser.parse(acl_str.c_str(), acl_str.length())) { ldpp_dout(dpp, 0) << "ERROR: JSONParser::parse returned error=" << dendl; return false; } JSONObjIter iter = parser.find_first("admin"); if (!iter.end() && (*iter)->is_array()) { std::vector<std::string> admin; decode_json_obj(admin, *iter); ldpp_dout(dpp, 0) << "admins: " << admin << dendl; add_grants(dpp, driver, admin, SWIFT_PERM_ADMIN); } iter = parser.find_first("read-write"); if (!iter.end() && (*iter)->is_array()) { std::vector<std::string> readwrite; decode_json_obj(readwrite, *iter); ldpp_dout(dpp, 0) << "read-write: " << readwrite << dendl; add_grants(dpp, driver, readwrite, SWIFT_PERM_RWRT); } iter = parser.find_first("read-only"); if (!iter.end() && (*iter)->is_array()) { std::vector<std::string> readonly; decode_json_obj(readonly, *iter); ldpp_dout(dpp, 0) << "read-only: " << readonly << dendl; add_grants(dpp, driver, readonly, SWIFT_PERM_READ); } return true; } boost::optional<std::string> RGWAccessControlPolicy_SWIFTAcct::to_str() const { std::vector<std::string> admin; std::vector<std::string> readwrite; std::vector<std::string> readonly; /* Parition the grant map into three not-overlapping groups. */ for (const auto& item : get_acl().get_grant_map()) { const ACLGrant& grant = item.second; const uint32_t perm = grant.get_permission().get_permissions(); rgw_user id; if (!grant.get_id(id)) { if (grant.get_group() != ACL_GROUP_ALL_USERS) { continue; } id = SWIFT_GROUP_ALL_USERS; } else if (owner.get_id() == id) { continue; } if (SWIFT_PERM_ADMIN == (perm & SWIFT_PERM_ADMIN)) { admin.insert(admin.end(), id.to_str()); } else if (SWIFT_PERM_RWRT == (perm & SWIFT_PERM_RWRT)) { readwrite.insert(readwrite.end(), id.to_str()); } else if (SWIFT_PERM_READ == (perm & SWIFT_PERM_READ)) { readonly.insert(readonly.end(), id.to_str()); } else { // FIXME: print a warning } } /* If there is no grant to serialize, let's exit earlier to not return * an empty JSON object which brakes the functional tests of Swift. */ if (admin.empty() && readwrite.empty() && readonly.empty()) { return boost::none; } /* Serialize the groups. */ JSONFormatter formatter; formatter.open_object_section("acl"); if (!readonly.empty()) { encode_json("read-only", readonly, &formatter); } if (!readwrite.empty()) { encode_json("read-write", readwrite, &formatter); } if (!admin.empty()) { encode_json("admin", admin, &formatter); } formatter.close_section(); std::ostringstream oss; formatter.flush(oss); return oss.str(); }
12,827
28.220957
87
cc
null
ceph-main/src/rgw/rgw_acl_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 #include <map> #include <vector> #include <string> #include <include/types.h> #include <boost/optional.hpp> #include "rgw_acl.h" class RGWUserCtl; class RGWAccessControlPolicy_SWIFT : public RGWAccessControlPolicy { int add_grants(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const std::vector<std::string>& uids, uint32_t perm); public: explicit RGWAccessControlPolicy_SWIFT(CephContext* const cct) : RGWAccessControlPolicy(cct) { } ~RGWAccessControlPolicy_SWIFT() override = default; int create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const rgw_user& id, const std::string& name, const char* read_list, const char* write_list, uint32_t& rw_mask); void filter_merge(uint32_t mask, RGWAccessControlPolicy_SWIFT *policy); void to_str(std::string& read, std::string& write); }; class RGWAccessControlPolicy_SWIFTAcct : public RGWAccessControlPolicy { public: explicit RGWAccessControlPolicy_SWIFTAcct(CephContext * const cct) : RGWAccessControlPolicy(cct) { } ~RGWAccessControlPolicy_SWIFTAcct() override {} void add_grants(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const std::vector<std::string>& uids, uint32_t perm); bool create(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, const rgw_user& id, const std::string& name, const std::string& acl_str); boost::optional<std::string> to_str() const; };
1,709
27.983051
73
h
null
ceph-main/src/rgw/rgw_acl_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 <list> #include <fmt/format.h> #include "include/types.h" #include "common/Formatter.h" #define RGW_PERM_NONE 0x00 #define RGW_PERM_READ 0x01 #define RGW_PERM_WRITE 0x02 #define RGW_PERM_READ_ACP 0x04 #define RGW_PERM_WRITE_ACP 0x08 #define RGW_PERM_READ_OBJS 0x10 #define RGW_PERM_WRITE_OBJS 0x20 #define RGW_PERM_FULL_CONTROL ( RGW_PERM_READ | RGW_PERM_WRITE | \ RGW_PERM_READ_ACP | RGW_PERM_WRITE_ACP ) #define RGW_PERM_ALL_S3 RGW_PERM_FULL_CONTROL #define RGW_PERM_INVALID 0xFF00 static constexpr char RGW_REFERER_WILDCARD[] = "*"; struct RGWAccessKey { std::string id; // AccessKey std::string key; // SecretKey std::string subuser; RGWAccessKey() {} RGWAccessKey(std::string _id, std::string _key) : id(std::move(_id)), key(std::move(_key)) {} void encode(bufferlist& bl) const { ENCODE_START(2, 2, bl); encode(id, bl); encode(key, bl); encode(subuser, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN_32(2, 2, 2, bl); decode(id, bl); decode(key, bl); decode(subuser, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void dump_plain(Formatter *f) const; void dump(Formatter *f, const std::string& user, bool swift) const; static void generate_test_instances(std::list<RGWAccessKey*>& o); void decode_json(JSONObj *obj); void decode_json(JSONObj *obj, bool swift); }; WRITE_CLASS_ENCODER(RGWAccessKey) struct RGWSubUser { std::string name; uint32_t perm_mask; RGWSubUser() : perm_mask(0) {} void encode(bufferlist& bl) const { ENCODE_START(2, 2, bl); encode(name, bl); encode(perm_mask, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN_32(2, 2, 2, bl); decode(name, bl); decode(perm_mask, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void dump(Formatter *f, const std::string& user) const; static void generate_test_instances(std::list<RGWSubUser*>& o); void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWSubUser) class RGWUserCaps { std::map<std::string, uint32_t> caps; int get_cap(const std::string& cap, std::string& type, uint32_t *perm); int add_cap(const std::string& cap); int remove_cap(const std::string& cap); public: static int parse_cap_perm(const std::string& str, uint32_t *perm); int add_from_string(const std::string& str); int remove_from_string(const std::string& str); void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(caps, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(caps, bl); DECODE_FINISH(bl); } int check_cap(const std::string& cap, uint32_t perm) const; bool is_valid_cap_type(const std::string& tp); void dump(Formatter *f) const; void dump(Formatter *f, const char *name) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWUserCaps) enum ACLGranteeTypeEnum { /* numbers are encoded, should not change */ ACL_TYPE_CANON_USER = 0, ACL_TYPE_EMAIL_USER = 1, ACL_TYPE_GROUP = 2, ACL_TYPE_UNKNOWN = 3, ACL_TYPE_REFERER = 4, }; enum ACLGroupTypeEnum { /* numbers are encoded should not change */ ACL_GROUP_NONE = 0, ACL_GROUP_ALL_USERS = 1, ACL_GROUP_AUTHENTICATED_USERS = 2, }; class ACLPermission { protected: int flags; public: ACLPermission() : flags(0) {} ~ACLPermission() {} uint32_t get_permissions() const { return flags; } void set_permissions(uint32_t perm) { flags = perm; } void encode(bufferlist& bl) const { ENCODE_START(2, 2, bl); encode(flags, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl); decode(flags, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<ACLPermission*>& o); friend bool operator==(const ACLPermission& lhs, const ACLPermission& rhs); friend bool operator!=(const ACLPermission& lhs, const ACLPermission& rhs); }; WRITE_CLASS_ENCODER(ACLPermission) class ACLGranteeType { protected: __u32 type; public: ACLGranteeType() : type(ACL_TYPE_UNKNOWN) {} virtual ~ACLGranteeType() {} // virtual const char *to_string() = 0; ACLGranteeTypeEnum get_type() const { return (ACLGranteeTypeEnum)type; } void set(ACLGranteeTypeEnum t) { type = t; } // virtual void set(const char *s) = 0; void encode(bufferlist& bl) const { ENCODE_START(2, 2, bl); encode(type, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl); decode(type, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<ACLGranteeType*>& o); friend bool operator==(const ACLGranteeType& lhs, const ACLGranteeType& rhs); friend bool operator!=(const ACLGranteeType& lhs, const ACLGranteeType& rhs); }; WRITE_CLASS_ENCODER(ACLGranteeType) class ACLGrantee { public: ACLGrantee() {} ~ACLGrantee() {} };
5,909
26.616822
79
h
null
ceph-main/src/rgw/rgw_admin.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <errno.h> #include <iostream> #include <sstream> #include <string> #include <boost/optional.hpp> extern "C" { #include <liboath/oath.h> } #include <fmt/format.h> #include "auth/Crypto.h" #include "compressor/Compressor.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/safe_io.h" #include "common/fault_injector.h" #include "include/util.h" #include "cls/rgw/cls_rgw_types.h" #include "cls/rgw/cls_rgw_client.h" #include "include/utime.h" #include "include/str_list.h" #include "rgw_user.h" #include "rgw_otp.h" #include "rgw_rados.h" #include "rgw_acl.h" #include "rgw_acl_s3.h" #include "rgw_datalog.h" #include "rgw_lc.h" #include "rgw_log.h" #include "rgw_formats.h" #include "rgw_usage.h" #include "rgw_orphan.h" #include "rgw_sync.h" #include "rgw_trim_bilog.h" #include "rgw_trim_datalog.h" #include "rgw_trim_mdlog.h" #include "rgw_data_sync.h" #include "rgw_rest_conn.h" #include "rgw_realm_watcher.h" #include "rgw_role.h" #include "rgw_reshard.h" #include "rgw_http_client_curl.h" #include "rgw_zone.h" #include "rgw_pubsub.h" #include "rgw_bucket_sync.h" #include "rgw_sync_checkpoint.h" #include "rgw_lua.h" #include "rgw_sal.h" #include "rgw_sal_config.h" #include "services/svc_sync_modules.h" #include "services/svc_cls.h" #include "services/svc_bilog_rados.h" #include "services/svc_mdlog.h" #include "services/svc_meta_be_otp.h" #include "services/svc_user.h" #include "services/svc_zone.h" #include "driver/rados/rgw_bucket.h" #include "driver/rados/rgw_sal_rados.h" #define dout_context g_ceph_context #define SECRET_KEY_LEN 40 #define PUBLIC_ID_LEN 20 using namespace std; static rgw::sal::Driver* driver = NULL; static constexpr auto dout_subsys = ceph_subsys_rgw; static const DoutPrefixProvider* dpp() { struct GlobalPrefix : public DoutPrefixProvider { CephContext *get_cct() const override { return dout_context; } unsigned get_subsys() const override { return dout_subsys; } std::ostream& gen_prefix(std::ostream& out) const override { return out; } }; static GlobalPrefix global_dpp; return &global_dpp; } #define CHECK_TRUE(x, msg, err) \ do { \ if (!x) { \ cerr << msg << std::endl; \ return err; \ } \ } while (0) #define CHECK_SUCCESS(x, msg) \ do { \ int _x_val = (x); \ if (_x_val < 0) { \ cerr << msg << ": " << cpp_strerror(-_x_val) << std::endl; \ return _x_val; \ } \ } while (0) static inline int posix_errortrans(int r) { switch(r) { case ERR_NO_SUCH_BUCKET: r = ENOENT; break; default: break; } return r; } static const std::string LUA_CONTEXT_LIST("prerequest, postrequest, background, getdata, putdata"); void usage() { cout << "usage: radosgw-admin <cmd> [options...]" << std::endl; cout << "commands:\n"; cout << " user create create a new user\n" ; cout << " user modify modify user\n"; cout << " user info get user info\n"; cout << " user rename rename user\n"; cout << " user rm remove user\n"; cout << " user suspend suspend a user\n"; cout << " user enable re-enable user after suspension\n"; cout << " user check check user info\n"; cout << " user stats show user stats as accounted by quota subsystem\n"; cout << " user list list users\n"; cout << " caps add add user capabilities\n"; cout << " caps rm remove user capabilities\n"; cout << " subuser create create a new subuser\n" ; cout << " subuser modify modify subuser\n"; cout << " subuser rm remove subuser\n"; cout << " key create create access key\n"; cout << " key rm remove access key\n"; cout << " bucket list list buckets (specify --allow-unordered for\n"; cout << " faster, unsorted listing)\n"; cout << " bucket limit check show bucket sharding stats\n"; cout << " bucket link link bucket to specified user\n"; cout << " bucket unlink unlink bucket from specified user\n"; cout << " bucket stats returns bucket statistics\n"; cout << " bucket rm remove bucket\n"; cout << " bucket check check bucket index\n"; cout << " bucket chown link bucket to specified user and update its object ACLs\n"; cout << " bucket reshard reshard bucket\n"; cout << " bucket rewrite rewrite all objects in the specified bucket\n"; cout << " bucket sync checkpoint poll a bucket's sync status until it catches up to its remote\n"; cout << " bucket sync disable disable bucket sync\n"; cout << " bucket sync enable enable bucket sync\n"; cout << " bucket radoslist list rados objects backing bucket's objects\n"; cout << " bi get retrieve bucket index object entries\n"; cout << " bi put store bucket index object entries\n"; cout << " bi list list raw bucket index entries\n"; cout << " bi purge purge bucket index entries\n"; cout << " object rm remove object\n"; cout << " object put put object\n"; cout << " object stat stat an object for its metadata\n"; cout << " object unlink unlink object from bucket index\n"; cout << " object rewrite rewrite the specified object\n"; cout << " object reindex reindex the object(s) indicated by --bucket and either --object or --objects-file\n"; cout << " objects expire run expired objects cleanup\n"; cout << " objects expire-stale list list stale expired objects (caused by reshard)\n"; cout << " objects expire-stale rm remove stale expired objects\n"; cout << " period rm remove a period\n"; cout << " period get get period info\n"; cout << " period get-current get current period info\n"; cout << " period pull pull a period\n"; cout << " period push push a period\n"; cout << " period list list all periods\n"; cout << " period update update the staging period\n"; cout << " period commit commit the staging period\n"; cout << " quota set set quota params\n"; cout << " quota enable enable quota\n"; cout << " quota disable disable quota\n"; cout << " ratelimit get get ratelimit params\n"; cout << " ratelimit set set ratelimit params\n"; cout << " ratelimit enable enable ratelimit\n"; cout << " ratelimit disable disable ratelimit\n"; cout << " global quota get view global quota params\n"; cout << " global quota set set global quota params\n"; cout << " global quota enable enable a global quota\n"; cout << " global quota disable disable a global quota\n"; cout << " global ratelimit get view global ratelimit params\n"; cout << " global ratelimit set set global ratelimit params\n"; cout << " global ratelimit enable enable a ratelimit quota\n"; cout << " global ratelimit disable disable a ratelimit quota\n"; cout << " realm create create a new realm\n"; cout << " realm rm remove a realm\n"; cout << " realm get show realm info\n"; cout << " realm get-default get default realm name\n"; cout << " realm list list realms\n"; cout << " realm list-periods list all realm periods\n"; cout << " realm rename rename a realm\n"; cout << " realm set set realm info (requires infile)\n"; cout << " realm default set realm as default\n"; cout << " realm pull pull a realm and its current period\n"; cout << " zonegroup add add a zone to a zonegroup\n"; cout << " zonegroup create create a new zone group info\n"; cout << " zonegroup default set default zone group\n"; cout << " zonegroup delete delete a zone group info\n"; cout << " zonegroup get show zone group info\n"; cout << " zonegroup modify modify an existing zonegroup\n"; cout << " zonegroup set set zone group info (requires infile)\n"; cout << " zonegroup rm remove a zone from a zonegroup\n"; cout << " zonegroup rename rename a zone group\n"; cout << " zonegroup list list all zone groups set on this cluster\n"; cout << " zonegroup placement list list zonegroup's placement targets\n"; cout << " zonegroup placement get get a placement target of a specific zonegroup\n"; cout << " zonegroup placement add add a placement target id to a zonegroup\n"; cout << " zonegroup placement modify modify a placement target of a specific zonegroup\n"; cout << " zonegroup placement rm remove a placement target from a zonegroup\n"; cout << " zonegroup placement default set a zonegroup's default placement target\n"; cout << " zone create create a new zone\n"; cout << " zone rm remove a zone\n"; cout << " zone get show zone cluster params\n"; cout << " zone modify modify an existing zone\n"; cout << " zone set set zone cluster params (requires infile)\n"; cout << " zone list list all zones set on this cluster\n"; cout << " zone rename rename a zone\n"; cout << " zone placement list list zone's placement targets\n"; cout << " zone placement get get a zone placement target\n"; cout << " zone placement add add a zone placement target\n"; cout << " zone placement modify modify a zone placement target\n"; cout << " zone placement rm remove a zone placement target\n"; cout << " metadata sync status get metadata sync status\n"; cout << " metadata sync init init metadata sync\n"; cout << " metadata sync run run metadata sync\n"; cout << " data sync status get data sync status of the specified source zone\n"; cout << " data sync init init data sync for the specified source zone\n"; cout << " data sync run run data sync for the specified source zone\n"; cout << " pool add add an existing pool for data placement\n"; cout << " pool rm remove an existing pool from data placement set\n"; cout << " pools list list placement active set\n"; cout << " policy read bucket/object policy\n"; cout << " log list list log objects\n"; cout << " log show dump a log from specific object or (bucket + date\n"; cout << " + bucket-id)\n"; cout << " (NOTE: required to specify formatting of date\n"; cout << " to \"YYYY-MM-DD-hh\")\n"; cout << " log rm remove log object\n"; cout << " usage show show usage (by user, by bucket, date range)\n"; cout << " usage trim trim usage (by user, by bucket, date range)\n"; cout << " usage clear reset all the usage stats for the cluster\n"; cout << " gc list dump expired garbage collection objects (specify\n"; cout << " --include-all to list all entries, including unexpired)\n"; cout << " gc process manually process garbage (specify\n"; cout << " --include-all to process all entries, including unexpired)\n"; cout << " lc list list all bucket lifecycle progress\n"; cout << " lc get get a lifecycle bucket configuration\n"; cout << " lc process manually process lifecycle\n"; cout << " lc reshard fix fix LC for a resharded bucket\n"; cout << " metadata get get metadata info\n"; cout << " metadata put put metadata info\n"; cout << " metadata rm remove metadata info\n"; cout << " metadata list list metadata info\n"; cout << " mdlog list list metadata log\n"; cout << " mdlog autotrim auto trim metadata log\n"; cout << " mdlog trim trim metadata log (use marker)\n"; cout << " mdlog status read metadata log status\n"; cout << " bilog list list bucket index log\n"; cout << " bilog trim trim bucket index log (use start-marker, end-marker)\n"; cout << " bilog status read bucket index log status\n"; cout << " bilog autotrim auto trim bucket index log\n"; cout << " datalog list list data log\n"; cout << " datalog trim trim data log\n"; cout << " datalog status read data log status\n"; cout << " datalog type change datalog type to --log_type={fifo,omap}\n"; cout << " orphans find deprecated -- init and run search for leaked rados objects (use job-id, pool)\n"; cout << " orphans finish deprecated -- clean up search for leaked rados objects\n"; cout << " orphans list-jobs deprecated -- list the current job-ids for orphans search\n"; cout << " * the three 'orphans' sub-commands are now deprecated; consider using the `rgw-orphan-list` tool\n"; cout << " role create create a AWS role for use with STS\n"; cout << " role delete remove a role\n"; cout << " role get get a role\n"; cout << " role list list roles with specified path prefix\n"; cout << " role-trust-policy modify modify the assume role policy of an existing role\n"; cout << " role-policy put add/update permission policy to role\n"; cout << " role-policy list list policies attached to a role\n"; cout << " role-policy get get the specified inline policy document embedded with the given role\n"; cout << " role-policy delete remove policy attached to a role\n"; cout << " role update update max_session_duration of a role\n"; cout << " reshard add schedule a resharding of a bucket\n"; cout << " reshard list list all bucket resharding or scheduled to be resharded\n"; cout << " reshard status read bucket resharding status\n"; cout << " reshard process process of scheduled reshard jobs\n"; cout << " reshard cancel cancel resharding a bucket\n"; cout << " reshard stale-instances list list stale-instances from bucket resharding\n"; cout << " reshard stale-instances delete cleanup stale-instances from bucket resharding\n"; cout << " sync error list list sync error\n"; cout << " sync error trim trim sync error\n"; cout << " mfa create create a new MFA TOTP token\n"; cout << " mfa list list MFA TOTP tokens\n"; cout << " mfa get show MFA TOTP token\n"; cout << " mfa remove delete MFA TOTP token\n"; cout << " mfa check check MFA TOTP token\n"; cout << " mfa resync re-sync MFA TOTP token\n"; cout << " topic list list bucket notifications topics\n"; cout << " topic get get a bucket notifications topic\n"; cout << " topic rm remove a bucket notifications topic\n"; cout << " script put upload a lua script to a context\n"; cout << " script get get the lua script of a context\n"; cout << " script rm remove the lua scripts of a context\n"; cout << " script-package add add a lua package to the scripts allowlist\n"; cout << " script-package rm remove a lua package from the scripts allowlist\n"; cout << " script-package list get the lua packages allowlist\n"; cout << " notification list list bucket notifications configuration\n"; cout << " notification get get a bucket notifications configuration\n"; cout << " notification rm remove a bucket notifications configuration\n"; cout << "options:\n"; cout << " --tenant=<tenant> tenant name\n"; cout << " --user_ns=<namespace> namespace of user (oidc in case of users authenticated with oidc provider)\n"; cout << " --uid=<id> user id\n"; cout << " --new-uid=<id> new user id\n"; cout << " --subuser=<name> subuser name\n"; cout << " --access-key=<key> S3 access key\n"; cout << " --email=<email> user's email address\n"; cout << " --secret/--secret-key=<key>\n"; cout << " specify secret key\n"; cout << " --gen-access-key generate random access key (for S3)\n"; cout << " --gen-secret generate random secret key\n"; cout << " --key-type=<type> key type, options are: swift, s3\n"; cout << " --temp-url-key[-2]=<key> temp url key\n"; cout << " --access=<access> Set access permissions for sub-user, should be one\n"; cout << " of read, write, readwrite, full\n"; cout << " --display-name=<name> user's display name\n"; cout << " --max-buckets max number of buckets for a user\n"; cout << " --admin set the admin flag on the user\n"; cout << " --system set the system flag on the user\n"; cout << " --op-mask set the op mask on the user\n"; cout << " --bucket=<bucket> Specify the bucket name. Also used by the quota command.\n"; cout << " --pool=<pool> Specify the pool name. Also used to scan for leaked rados objects.\n"; cout << " --object=<object> object name\n"; cout << " --objects-file=<file> file containing a list of object names to process\n"; cout << " --object-version=<version> object version\n"; cout << " --date=<date> date in the format yyyy-mm-dd\n"; cout << " --start-date=<date> start date in the format yyyy-mm-dd\n"; cout << " --end-date=<date> end date in the format yyyy-mm-dd\n"; cout << " --bucket-id=<bucket-id> bucket id\n"; cout << " --bucket-new-name=<bucket>\n"; cout << " for bucket link: optional new name\n"; cout << " --shard-id=<shard-id> optional for: \n"; cout << " mdlog list\n"; cout << " data sync status\n"; cout << " required for: \n"; cout << " mdlog trim\n"; cout << " --gen=<gen-id> optional for: \n"; cout << " bilog list\n"; cout << " bilog trim\n"; cout << " bilog status\n"; cout << " --max-entries=<entries> max entries for listing operations\n"; cout << " --metadata-key=<key> key to retrieve metadata from with metadata get\n"; cout << " --remote=<remote> zone or zonegroup id of remote gateway\n"; cout << " --period=<id> period id\n"; cout << " --url=<url> url for pushing/pulling period/realm\n"; cout << " --epoch=<number> period epoch\n"; cout << " --commit commit the period during 'period update'\n"; cout << " --staging get staging period info\n"; cout << " --master set as master\n"; cout << " --master-zone=<id> master zone id\n"; cout << " --rgw-realm=<name> realm name\n"; cout << " --realm-id=<id> realm id\n"; cout << " --realm-new-name=<name> realm new name\n"; cout << " --rgw-zonegroup=<name> zonegroup name\n"; cout << " --zonegroup-id=<id> zonegroup id\n"; cout << " --zonegroup-new-name=<name>\n"; cout << " zonegroup new name\n"; cout << " --rgw-zone=<name> name of zone in which radosgw is running\n"; cout << " --zone-id=<id> zone id\n"; cout << " --zone-new-name=<name> zone new name\n"; cout << " --source-zone specify the source zone (for data sync)\n"; cout << " --default set entity (realm, zonegroup, zone) as default\n"; cout << " --read-only set zone as read-only (when adding to zonegroup)\n"; cout << " --redirect-zone specify zone id to redirect when response is 404 (not found)\n"; cout << " --placement-id placement id for zonegroup placement commands\n"; cout << " --storage-class storage class for zonegroup placement commands\n"; cout << " --tags=<list> list of tags for zonegroup placement add and modify commands\n"; cout << " --tags-add=<list> list of tags to add for zonegroup placement modify command\n"; cout << " --tags-rm=<list> list of tags to remove for zonegroup placement modify command\n"; cout << " --endpoints=<list> zone endpoints\n"; cout << " --index-pool=<pool> placement target index pool\n"; cout << " --data-pool=<pool> placement target data pool\n"; cout << " --data-extra-pool=<pool> placement target data extra (non-ec) pool\n"; cout << " --placement-index-type=<type>\n"; cout << " placement target index type (normal, indexless, or #id)\n"; cout << " --placement-inline-data=<true>\n"; cout << " set whether the placement target is configured to store a data\n"; cout << " chunk inline in head objects\n"; cout << " --compression=<type> placement target compression type (plugin name or empty/none)\n"; cout << " --tier-type=<type> zone tier type\n"; cout << " --tier-config=<k>=<v>[,...]\n"; cout << " set zone tier config keys, values\n"; cout << " --tier-config-rm=<k>[,...]\n"; cout << " unset zone tier config keys\n"; cout << " --sync-from-all[=false] set/reset whether zone syncs from all zonegroup peers\n"; cout << " --sync-from=[zone-name][,...]\n"; cout << " set list of zones to sync from\n"; cout << " --sync-from-rm=[zone-name][,...]\n"; cout << " remove zones from list of zones to sync from\n"; cout << " --bucket-index-max-shards override a zone/zonegroup's default bucket index shard count\n"; cout << " --fix besides checking bucket index, will also fix it\n"; cout << " --check-objects bucket check: rebuilds bucket index according to\n"; cout << " actual objects state\n"; cout << " --format=<format> specify output format for certain operations: xml,\n"; cout << " json\n"; cout << " --purge-data when specified, user removal will also purge all the\n"; cout << " user data\n"; cout << " --purge-keys when specified, subuser removal will also purge all the\n"; cout << " subuser keys\n"; cout << " --purge-objects remove a bucket's objects before deleting it\n"; cout << " (NOTE: required to delete a non-empty bucket)\n"; cout << " --sync-stats option to 'user stats', update user stats with current\n"; cout << " stats reported by user's buckets indexes\n"; cout << " --reset-stats option to 'user stats', reset stats in accordance with user buckets\n"; cout << " --show-config show configuration\n"; cout << " --show-log-entries=<flag> enable/disable dump of log entries on log show\n"; cout << " --show-log-sum=<flag> enable/disable dump of log summation on log show\n"; cout << " --skip-zero-entries log show only dumps entries that don't have zero value\n"; cout << " in one of the numeric field\n"; cout << " --infile=<file> file to read in when setting data\n"; cout << " --categories=<list> comma separated list of categories, used in usage show\n"; cout << " --caps=<caps> list of caps (e.g., \"usage=read, write; user=read\")\n"; cout << " --op-mask=<op-mask> permission of user's operations (e.g., \"read, write, delete, *\")\n"; cout << " --yes-i-really-mean-it required for certain operations\n"; cout << " --warnings-only when specified with bucket limit check, list\n"; cout << " only buckets nearing or over the current max\n"; cout << " objects per shard value\n"; cout << " --bypass-gc when specified with bucket deletion, triggers\n"; cout << " object deletions by not involving GC\n"; cout << " --inconsistent-index when specified with bucket deletion and bypass-gc set to true,\n"; cout << " ignores bucket index consistency\n"; cout << " --min-rewrite-size min object size for bucket rewrite (default 4M)\n"; cout << " --max-rewrite-size max object size for bucket rewrite (default ULLONG_MAX)\n"; cout << " --min-rewrite-stripe-size min stripe size for object rewrite (default 0)\n"; cout << " --trim-delay-ms time interval in msec to limit the frequency of sync error log entries trimming operations,\n"; cout << " the trimming process will sleep the specified msec for every 1000 entries trimmed\n"; cout << " --max-concurrent-ios maximum concurrent ios for bucket operations (default: 32)\n"; cout << " --enable-feature enable a zone/zonegroup feature\n"; cout << " --disable-feature disable a zone/zonegroup feature\n"; cout << "\n"; cout << "<date> := \"YYYY-MM-DD[ hh:mm:ss]\"\n"; cout << "\nQuota options:\n"; cout << " --max-objects specify max objects (negative value to disable)\n"; cout << " --max-size specify max size (in B/K/M/G/T, negative value to disable)\n"; cout << " --quota-scope scope of quota (bucket, user)\n"; cout << "\nRate limiting options:\n"; cout << " --max-read-ops specify max requests per minute for READ ops per RGW (GET and HEAD request methods), 0 means unlimited\n"; cout << " --max-read-bytes specify max bytes per minute for READ ops per RGW (GET and HEAD request methods), 0 means unlimited\n"; cout << " --max-write-ops specify max requests per minute for WRITE ops per RGW (Not GET or HEAD request methods), 0 means unlimited\n"; cout << " --max-write-bytes specify max bytes per minute for WRITE ops per RGW (Not GET or HEAD request methods), 0 means unlimited\n"; cout << " --ratelimit-scope scope of rate limiting: bucket, user, anonymous\n"; cout << " anonymous can be configured only with global rate limit\n"; cout << "\nOrphans search options:\n"; cout << " --num-shards num of shards to use for keeping the temporary scan info\n"; cout << " --orphan-stale-secs num of seconds to wait before declaring an object to be an orphan (default: 86400)\n"; cout << " --job-id set the job id (for orphans find)\n"; cout << " --detail detailed mode, log and stat head objects as well\n"; cout << "\nOrphans list-jobs options:\n"; cout << " --extra-info provide extra info in job list\n"; cout << "\nRole options:\n"; cout << " --role-name name of the role to create\n"; cout << " --path path to the role\n"; cout << " --assume-role-policy-doc the trust relationship policy document that grants an entity permission to assume the role\n"; cout << " --policy-name name of the policy document\n"; cout << " --policy-doc permission policy document\n"; cout << " --path-prefix path prefix for filtering roles\n"; cout << "\nMFA options:\n"; cout << " --totp-serial a string that represents the ID of a TOTP token\n"; cout << " --totp-seed the secret seed that is used to calculate the TOTP\n"; cout << " --totp-seconds the time resolution that is being used for TOTP generation\n"; cout << " --totp-window the number of TOTP tokens that are checked before and after the current token when validating token\n"; cout << " --totp-pin the valid value of a TOTP token at a certain time\n"; cout << "\nBucket notifications options:\n"; cout << " --topic bucket notifications topic name\n"; cout << " --notification-id bucket notifications id\n"; cout << "\nScript options:\n"; cout << " --context context in which the script runs. one of: "+LUA_CONTEXT_LIST+"\n"; cout << " --package name of the lua package that should be added/removed to/from the allowlist\n"; cout << " --allow-compilation package is allowed to compile C code as part of its installation\n"; cout << "\nradoslist options:\n"; cout << " --rgw-obj-fs the field separator that will separate the rados\n"; cout << " object name from the rgw object name;\n"; cout << " additionally rados objects for incomplete\n"; cout << " multipart uploads will not be output\n"; cout << "\n"; generic_client_usage(); } class SimpleCmd { public: struct Def { string cmd; std::any opt; }; using Aliases = std::vector<std::set<string> >; using Commands = std::vector<Def>; private: struct Node { map<string, Node> next; set<string> expected; /* separate un-normalized list */ std::any opt; }; Node cmd_root; map<string, string> alias_map; string normalize_alias(const string& s) const { auto iter = alias_map.find(s); if (iter == alias_map.end()) { return s; } return iter->second; } void init_alias_map(Aliases& aliases) { for (auto& alias_set : aliases) { std::optional<string> first; for (auto& alias : alias_set) { if (!first) { first = alias; } else { alias_map[alias] = *first; } } } } bool gen_next_expected(Node *node, vector<string> *expected, bool ret) { for (auto& next_cmd : node->expected) { expected->push_back(next_cmd); } return ret; } Node root; public: SimpleCmd() {} SimpleCmd(std::optional<Commands> cmds, std::optional<Aliases> aliases) { if (aliases) { add_aliases(*aliases); } if (cmds) { add_commands(*cmds); } } void add_aliases(Aliases& aliases) { init_alias_map(aliases); } void add_commands(std::vector<Def>& cmds) { for (auto& cmd : cmds) { vector<string> words; get_str_vec(cmd.cmd, " ", words); auto node = &cmd_root; for (auto& word : words) { auto norm = normalize_alias(word); auto parent = node; node->expected.insert(word); node = &node->next[norm]; if (norm == "[*]") { /* optional param at the end */ parent->next["*"] = *node; /* can be also looked up by '*' */ parent->opt = cmd.opt; } } node->opt = cmd.opt; } } template <class Container> bool find_command(Container& args, std::any *opt_cmd, vector<string> *extra_args, string *error, vector<string> *expected) { auto node = &cmd_root; std::optional<std::any> found_opt; for (auto& arg : args) { string norm = normalize_alias(arg); auto iter = node->next.find(norm); if (iter == node->next.end()) { iter = node->next.find("*"); if (iter == node->next.end()) { *error = string("ERROR: Unrecognized argument: '") + arg + "'"; return gen_next_expected(node, expected, false); } extra_args->push_back(arg); if (!found_opt) { found_opt = node->opt; } } node = &(iter->second); } *opt_cmd = found_opt.value_or(node->opt); if (!opt_cmd->has_value()) { *error ="ERROR: Unknown command"; return gen_next_expected(node, expected, false); } return true; } }; namespace rgw_admin { enum class OPT { NO_CMD, USER_CREATE, USER_INFO, USER_MODIFY, USER_RENAME, USER_RM, USER_SUSPEND, USER_ENABLE, USER_CHECK, USER_STATS, USER_LIST, SUBUSER_CREATE, SUBUSER_MODIFY, SUBUSER_RM, KEY_CREATE, KEY_RM, BUCKETS_LIST, BUCKET_LIMIT_CHECK, BUCKET_LINK, BUCKET_UNLINK, BUCKET_LAYOUT, BUCKET_STATS, BUCKET_CHECK, BUCKET_SYNC_CHECKPOINT, BUCKET_SYNC_INFO, BUCKET_SYNC_STATUS, BUCKET_SYNC_MARKERS, BUCKET_SYNC_INIT, BUCKET_SYNC_RUN, BUCKET_SYNC_DISABLE, BUCKET_SYNC_ENABLE, BUCKET_RM, BUCKET_REWRITE, BUCKET_RESHARD, BUCKET_CHOWN, BUCKET_RADOS_LIST, BUCKET_SHARD_OBJECTS, BUCKET_OBJECT_SHARD, POLICY, POOL_ADD, POOL_RM, POOLS_LIST, LOG_LIST, LOG_SHOW, LOG_RM, USAGE_SHOW, USAGE_TRIM, USAGE_CLEAR, OBJECT_PUT, OBJECT_RM, OBJECT_UNLINK, OBJECT_STAT, OBJECT_REWRITE, OBJECT_REINDEX, OBJECTS_EXPIRE, OBJECTS_EXPIRE_STALE_LIST, OBJECTS_EXPIRE_STALE_RM, BI_GET, BI_PUT, BI_LIST, BI_PURGE, OLH_GET, OLH_READLOG, QUOTA_SET, QUOTA_ENABLE, QUOTA_DISABLE, GC_LIST, GC_PROCESS, LC_LIST, LC_GET, LC_PROCESS, LC_RESHARD_FIX, ORPHANS_FIND, ORPHANS_FINISH, ORPHANS_LIST_JOBS, RATELIMIT_GET, RATELIMIT_SET, RATELIMIT_ENABLE, RATELIMIT_DISABLE, ZONEGROUP_ADD, ZONEGROUP_CREATE, ZONEGROUP_DEFAULT, ZONEGROUP_DELETE, ZONEGROUP_GET, ZONEGROUP_MODIFY, ZONEGROUP_SET, ZONEGROUP_LIST, ZONEGROUP_REMOVE, ZONEGROUP_RENAME, ZONEGROUP_PLACEMENT_ADD, ZONEGROUP_PLACEMENT_MODIFY, ZONEGROUP_PLACEMENT_RM, ZONEGROUP_PLACEMENT_LIST, ZONEGROUP_PLACEMENT_GET, ZONEGROUP_PLACEMENT_DEFAULT, ZONE_CREATE, ZONE_DELETE, ZONE_GET, ZONE_MODIFY, ZONE_SET, ZONE_LIST, ZONE_RENAME, ZONE_DEFAULT, ZONE_PLACEMENT_ADD, ZONE_PLACEMENT_MODIFY, ZONE_PLACEMENT_RM, ZONE_PLACEMENT_LIST, ZONE_PLACEMENT_GET, CAPS_ADD, CAPS_RM, METADATA_GET, METADATA_PUT, METADATA_RM, METADATA_LIST, METADATA_SYNC_STATUS, METADATA_SYNC_INIT, METADATA_SYNC_RUN, MDLOG_LIST, MDLOG_AUTOTRIM, MDLOG_TRIM, MDLOG_FETCH, MDLOG_STATUS, SYNC_ERROR_LIST, SYNC_ERROR_TRIM, SYNC_GROUP_CREATE, SYNC_GROUP_MODIFY, SYNC_GROUP_GET, SYNC_GROUP_REMOVE, SYNC_GROUP_FLOW_CREATE, SYNC_GROUP_FLOW_REMOVE, SYNC_GROUP_PIPE_CREATE, SYNC_GROUP_PIPE_MODIFY, SYNC_GROUP_PIPE_REMOVE, SYNC_POLICY_GET, BILOG_LIST, BILOG_TRIM, BILOG_STATUS, BILOG_AUTOTRIM, DATA_SYNC_STATUS, DATA_SYNC_INIT, DATA_SYNC_RUN, DATALOG_LIST, DATALOG_STATUS, DATALOG_AUTOTRIM, DATALOG_TRIM, DATALOG_TYPE, DATALOG_PRUNE, REALM_CREATE, REALM_DELETE, REALM_GET, REALM_GET_DEFAULT, REALM_LIST, REALM_LIST_PERIODS, REALM_RENAME, REALM_SET, REALM_DEFAULT, REALM_PULL, PERIOD_DELETE, PERIOD_GET, PERIOD_GET_CURRENT, PERIOD_PULL, PERIOD_PUSH, PERIOD_LIST, PERIOD_UPDATE, PERIOD_COMMIT, GLOBAL_QUOTA_GET, GLOBAL_QUOTA_SET, GLOBAL_QUOTA_ENABLE, GLOBAL_QUOTA_DISABLE, GLOBAL_RATELIMIT_GET, GLOBAL_RATELIMIT_SET, GLOBAL_RATELIMIT_ENABLE, GLOBAL_RATELIMIT_DISABLE, SYNC_INFO, SYNC_STATUS, ROLE_CREATE, ROLE_DELETE, ROLE_GET, ROLE_TRUST_POLICY_MODIFY, ROLE_LIST, ROLE_POLICY_PUT, ROLE_POLICY_LIST, ROLE_POLICY_GET, ROLE_POLICY_DELETE, ROLE_UPDATE, RESHARD_ADD, RESHARD_LIST, RESHARD_STATUS, RESHARD_PROCESS, RESHARD_CANCEL, MFA_CREATE, MFA_REMOVE, MFA_GET, MFA_LIST, MFA_CHECK, MFA_RESYNC, RESHARD_STALE_INSTANCES_LIST, RESHARD_STALE_INSTANCES_DELETE, PUBSUB_TOPIC_LIST, PUBSUB_TOPIC_GET, PUBSUB_TOPIC_RM, PUBSUB_NOTIFICATION_LIST, PUBSUB_NOTIFICATION_GET, PUBSUB_NOTIFICATION_RM, PUBSUB_TOPIC_STATS, SCRIPT_PUT, SCRIPT_GET, SCRIPT_RM, SCRIPT_PACKAGE_ADD, SCRIPT_PACKAGE_RM, SCRIPT_PACKAGE_LIST }; } using namespace rgw_admin; static SimpleCmd::Commands all_cmds = { { "user create", OPT::USER_CREATE }, { "user info", OPT::USER_INFO }, { "user modify", OPT::USER_MODIFY }, { "user rename", OPT::USER_RENAME }, { "user rm", OPT::USER_RM }, { "user suspend", OPT::USER_SUSPEND }, { "user enable", OPT::USER_ENABLE }, { "user check", OPT::USER_CHECK }, { "user stats", OPT::USER_STATS }, { "user list", OPT::USER_LIST }, { "subuser create", OPT::SUBUSER_CREATE }, { "subuser modify", OPT::SUBUSER_MODIFY }, { "subuser rm", OPT::SUBUSER_RM }, { "key create", OPT::KEY_CREATE }, { "key rm", OPT::KEY_RM }, { "buckets list", OPT::BUCKETS_LIST }, { "bucket list", OPT::BUCKETS_LIST }, { "bucket limit check", OPT::BUCKET_LIMIT_CHECK }, { "bucket link", OPT::BUCKET_LINK }, { "bucket unlink", OPT::BUCKET_UNLINK }, { "bucket layout", OPT::BUCKET_LAYOUT }, { "bucket stats", OPT::BUCKET_STATS }, { "bucket check", OPT::BUCKET_CHECK }, { "bucket sync checkpoint", OPT::BUCKET_SYNC_CHECKPOINT }, { "bucket sync info", OPT::BUCKET_SYNC_INFO }, { "bucket sync status", OPT::BUCKET_SYNC_STATUS }, { "bucket sync markers", OPT::BUCKET_SYNC_MARKERS }, { "bucket sync init", OPT::BUCKET_SYNC_INIT }, { "bucket sync run", OPT::BUCKET_SYNC_RUN }, { "bucket sync disable", OPT::BUCKET_SYNC_DISABLE }, { "bucket sync enable", OPT::BUCKET_SYNC_ENABLE }, { "bucket rm", OPT::BUCKET_RM }, { "bucket rewrite", OPT::BUCKET_REWRITE }, { "bucket reshard", OPT::BUCKET_RESHARD }, { "bucket chown", OPT::BUCKET_CHOWN }, { "bucket radoslist", OPT::BUCKET_RADOS_LIST }, { "bucket rados list", OPT::BUCKET_RADOS_LIST }, { "bucket shard objects", OPT::BUCKET_SHARD_OBJECTS }, { "bucket shard object", OPT::BUCKET_SHARD_OBJECTS }, { "bucket object shard", OPT::BUCKET_OBJECT_SHARD }, { "policy", OPT::POLICY }, { "pool add", OPT::POOL_ADD }, { "pool rm", OPT::POOL_RM }, { "pool list", OPT::POOLS_LIST }, { "pools list", OPT::POOLS_LIST }, { "log list", OPT::LOG_LIST }, { "log show", OPT::LOG_SHOW }, { "log rm", OPT::LOG_RM }, { "usage show", OPT::USAGE_SHOW }, { "usage trim", OPT::USAGE_TRIM }, { "usage clear", OPT::USAGE_CLEAR }, { "object put", OPT::OBJECT_PUT }, { "object rm", OPT::OBJECT_RM }, { "object unlink", OPT::OBJECT_UNLINK }, { "object stat", OPT::OBJECT_STAT }, { "object rewrite", OPT::OBJECT_REWRITE }, { "object reindex", OPT::OBJECT_REINDEX }, { "objects expire", OPT::OBJECTS_EXPIRE }, { "objects expire-stale list", OPT::OBJECTS_EXPIRE_STALE_LIST }, { "objects expire-stale rm", OPT::OBJECTS_EXPIRE_STALE_RM }, { "bi get", OPT::BI_GET }, { "bi put", OPT::BI_PUT }, { "bi list", OPT::BI_LIST }, { "bi purge", OPT::BI_PURGE }, { "olh get", OPT::OLH_GET }, { "olh readlog", OPT::OLH_READLOG }, { "quota set", OPT::QUOTA_SET }, { "quota enable", OPT::QUOTA_ENABLE }, { "quota disable", OPT::QUOTA_DISABLE }, { "ratelimit get", OPT::RATELIMIT_GET }, { "ratelimit set", OPT::RATELIMIT_SET }, { "ratelimit enable", OPT::RATELIMIT_ENABLE }, { "ratelimit disable", OPT::RATELIMIT_DISABLE }, { "gc list", OPT::GC_LIST }, { "gc process", OPT::GC_PROCESS }, { "lc list", OPT::LC_LIST }, { "lc get", OPT::LC_GET }, { "lc process", OPT::LC_PROCESS }, { "lc reshard fix", OPT::LC_RESHARD_FIX }, { "orphans find", OPT::ORPHANS_FIND }, { "orphans finish", OPT::ORPHANS_FINISH }, { "orphans list jobs", OPT::ORPHANS_LIST_JOBS }, { "orphans list-jobs", OPT::ORPHANS_LIST_JOBS }, { "zonegroup add", OPT::ZONEGROUP_ADD }, { "zonegroup create", OPT::ZONEGROUP_CREATE }, { "zonegroup default", OPT::ZONEGROUP_DEFAULT }, { "zonegroup delete", OPT::ZONEGROUP_DELETE }, { "zonegroup get", OPT::ZONEGROUP_GET }, { "zonegroup modify", OPT::ZONEGROUP_MODIFY }, { "zonegroup set", OPT::ZONEGROUP_SET }, { "zonegroup list", OPT::ZONEGROUP_LIST }, { "zonegroups list", OPT::ZONEGROUP_LIST }, { "zonegroup remove", OPT::ZONEGROUP_REMOVE }, { "zonegroup remove zone", OPT::ZONEGROUP_REMOVE }, { "zonegroup rename", OPT::ZONEGROUP_RENAME }, { "zonegroup placement add", OPT::ZONEGROUP_PLACEMENT_ADD }, { "zonegroup placement modify", OPT::ZONEGROUP_PLACEMENT_MODIFY }, { "zonegroup placement rm", OPT::ZONEGROUP_PLACEMENT_RM }, { "zonegroup placement list", OPT::ZONEGROUP_PLACEMENT_LIST }, { "zonegroup placement get", OPT::ZONEGROUP_PLACEMENT_GET }, { "zonegroup placement default", OPT::ZONEGROUP_PLACEMENT_DEFAULT }, { "zone create", OPT::ZONE_CREATE }, { "zone delete", OPT::ZONE_DELETE }, { "zone get", OPT::ZONE_GET }, { "zone modify", OPT::ZONE_MODIFY }, { "zone set", OPT::ZONE_SET }, { "zone list", OPT::ZONE_LIST }, { "zones list", OPT::ZONE_LIST }, { "zone rename", OPT::ZONE_RENAME }, { "zone default", OPT::ZONE_DEFAULT }, { "zone placement add", OPT::ZONE_PLACEMENT_ADD }, { "zone placement modify", OPT::ZONE_PLACEMENT_MODIFY }, { "zone placement rm", OPT::ZONE_PLACEMENT_RM }, { "zone placement list", OPT::ZONE_PLACEMENT_LIST }, { "zone placement get", OPT::ZONE_PLACEMENT_GET }, { "caps add", OPT::CAPS_ADD }, { "caps rm", OPT::CAPS_RM }, { "metadata get [*]", OPT::METADATA_GET }, { "metadata put [*]", OPT::METADATA_PUT }, { "metadata rm [*]", OPT::METADATA_RM }, { "metadata list [*]", OPT::METADATA_LIST }, { "metadata sync status", OPT::METADATA_SYNC_STATUS }, { "metadata sync init", OPT::METADATA_SYNC_INIT }, { "metadata sync run", OPT::METADATA_SYNC_RUN }, { "mdlog list", OPT::MDLOG_LIST }, { "mdlog autotrim", OPT::MDLOG_AUTOTRIM }, { "mdlog trim", OPT::MDLOG_TRIM }, { "mdlog fetch", OPT::MDLOG_FETCH }, { "mdlog status", OPT::MDLOG_STATUS }, { "sync error list", OPT::SYNC_ERROR_LIST }, { "sync error trim", OPT::SYNC_ERROR_TRIM }, { "sync policy get", OPT::SYNC_POLICY_GET }, { "sync group create", OPT::SYNC_GROUP_CREATE }, { "sync group modify", OPT::SYNC_GROUP_MODIFY }, { "sync group get", OPT::SYNC_GROUP_GET }, { "sync group remove", OPT::SYNC_GROUP_REMOVE }, { "sync group flow create", OPT::SYNC_GROUP_FLOW_CREATE }, { "sync group flow remove", OPT::SYNC_GROUP_FLOW_REMOVE }, { "sync group pipe create", OPT::SYNC_GROUP_PIPE_CREATE }, { "sync group pipe modify", OPT::SYNC_GROUP_PIPE_MODIFY }, { "sync group pipe remove", OPT::SYNC_GROUP_PIPE_REMOVE }, { "bilog list", OPT::BILOG_LIST }, { "bilog trim", OPT::BILOG_TRIM }, { "bilog status", OPT::BILOG_STATUS }, { "bilog autotrim", OPT::BILOG_AUTOTRIM }, { "data sync status", OPT::DATA_SYNC_STATUS }, { "data sync init", OPT::DATA_SYNC_INIT }, { "data sync run", OPT::DATA_SYNC_RUN }, { "datalog list", OPT::DATALOG_LIST }, { "datalog status", OPT::DATALOG_STATUS }, { "datalog autotrim", OPT::DATALOG_AUTOTRIM }, { "datalog trim", OPT::DATALOG_TRIM }, { "datalog type", OPT::DATALOG_TYPE }, { "datalog prune", OPT::DATALOG_PRUNE }, { "realm create", OPT::REALM_CREATE }, { "realm rm", OPT::REALM_DELETE }, { "realm get", OPT::REALM_GET }, { "realm get default", OPT::REALM_GET_DEFAULT }, { "realm get-default", OPT::REALM_GET_DEFAULT }, { "realm list", OPT::REALM_LIST }, { "realm list periods", OPT::REALM_LIST_PERIODS }, { "realm list-periods", OPT::REALM_LIST_PERIODS }, { "realm rename", OPT::REALM_RENAME }, { "realm set", OPT::REALM_SET }, { "realm default", OPT::REALM_DEFAULT }, { "realm pull", OPT::REALM_PULL }, { "period delete", OPT::PERIOD_DELETE }, { "period get", OPT::PERIOD_GET }, { "period get-current", OPT::PERIOD_GET_CURRENT }, { "period get current", OPT::PERIOD_GET_CURRENT }, { "period pull", OPT::PERIOD_PULL }, { "period push", OPT::PERIOD_PUSH }, { "period list", OPT::PERIOD_LIST }, { "period update", OPT::PERIOD_UPDATE }, { "period commit", OPT::PERIOD_COMMIT }, { "global quota get", OPT::GLOBAL_QUOTA_GET }, { "global quota set", OPT::GLOBAL_QUOTA_SET }, { "global quota enable", OPT::GLOBAL_QUOTA_ENABLE }, { "global quota disable", OPT::GLOBAL_QUOTA_DISABLE }, { "global ratelimit get", OPT::GLOBAL_RATELIMIT_GET }, { "global ratelimit set", OPT::GLOBAL_RATELIMIT_SET }, { "global ratelimit enable", OPT::GLOBAL_RATELIMIT_ENABLE }, { "global ratelimit disable", OPT::GLOBAL_RATELIMIT_DISABLE }, { "sync info", OPT::SYNC_INFO }, { "sync status", OPT::SYNC_STATUS }, { "role create", OPT::ROLE_CREATE }, { "role delete", OPT::ROLE_DELETE }, { "role get", OPT::ROLE_GET }, { "role-trust-policy modify", OPT::ROLE_TRUST_POLICY_MODIFY }, { "role list", OPT::ROLE_LIST }, { "role policy put", OPT::ROLE_POLICY_PUT }, { "role-policy put", OPT::ROLE_POLICY_PUT }, { "role policy list", OPT::ROLE_POLICY_LIST }, { "role-policy list", OPT::ROLE_POLICY_LIST }, { "role policy get", OPT::ROLE_POLICY_GET }, { "role-policy get", OPT::ROLE_POLICY_GET }, { "role policy delete", OPT::ROLE_POLICY_DELETE }, { "role-policy delete", OPT::ROLE_POLICY_DELETE }, { "role update", OPT::ROLE_UPDATE }, { "reshard bucket", OPT::BUCKET_RESHARD }, { "reshard add", OPT::RESHARD_ADD }, { "reshard list", OPT::RESHARD_LIST }, { "reshard status", OPT::RESHARD_STATUS }, { "reshard process", OPT::RESHARD_PROCESS }, { "reshard cancel", OPT::RESHARD_CANCEL }, { "mfa create", OPT::MFA_CREATE }, { "mfa remove", OPT::MFA_REMOVE }, { "mfa get", OPT::MFA_GET }, { "mfa list", OPT::MFA_LIST }, { "mfa check", OPT::MFA_CHECK }, { "mfa resync", OPT::MFA_RESYNC }, { "reshard stale-instances list", OPT::RESHARD_STALE_INSTANCES_LIST }, { "reshard stale list", OPT::RESHARD_STALE_INSTANCES_LIST }, { "reshard stale-instances delete", OPT::RESHARD_STALE_INSTANCES_DELETE }, { "reshard stale delete", OPT::RESHARD_STALE_INSTANCES_DELETE }, { "topic list", OPT::PUBSUB_TOPIC_LIST }, { "topic get", OPT::PUBSUB_TOPIC_GET }, { "topic rm", OPT::PUBSUB_TOPIC_RM }, { "notification list", OPT::PUBSUB_NOTIFICATION_LIST }, { "notification get", OPT::PUBSUB_NOTIFICATION_GET }, { "notification rm", OPT::PUBSUB_NOTIFICATION_RM }, { "topic stats", OPT::PUBSUB_TOPIC_STATS }, { "script put", OPT::SCRIPT_PUT }, { "script get", OPT::SCRIPT_GET }, { "script rm", OPT::SCRIPT_RM }, { "script-package add", OPT::SCRIPT_PACKAGE_ADD }, { "script-package rm", OPT::SCRIPT_PACKAGE_RM }, { "script-package list", OPT::SCRIPT_PACKAGE_LIST }, }; static SimpleCmd::Aliases cmd_aliases = { { "delete", "del" }, { "remove", "rm" }, { "rename", "mv" }, }; BIIndexType get_bi_index_type(const string& type_str) { if (type_str == "plain") return BIIndexType::Plain; if (type_str == "instance") return BIIndexType::Instance; if (type_str == "olh") return BIIndexType::OLH; return BIIndexType::Invalid; } log_type get_log_type(const string& type_str) { if (strcasecmp(type_str.c_str(), "fifo") == 0) return log_type::fifo; if (strcasecmp(type_str.c_str(), "omap") == 0) return log_type::omap; return static_cast<log_type>(0xff); } static void show_user_info(RGWUserInfo& info, Formatter *formatter) { encode_json("user_info", info, formatter); formatter->flush(cout); cout << std::endl; } static void show_perm_policy(string perm_policy, Formatter* formatter) { formatter->open_object_section("role"); formatter->dump_string("Permission policy", perm_policy); formatter->close_section(); formatter->flush(cout); } static void show_policy_names(std::vector<string> policy_names, Formatter* formatter) { formatter->open_array_section("PolicyNames"); for (const auto& it : policy_names) { formatter->dump_string("policyname", it); } formatter->close_section(); formatter->flush(cout); } static void show_role_info(rgw::sal::RGWRole* role, Formatter* formatter) { formatter->open_object_section("role"); role->dump(formatter); formatter->close_section(); formatter->flush(cout); } static void show_roles_info(vector<std::unique_ptr<rgw::sal::RGWRole>>& roles, Formatter* formatter) { formatter->open_array_section("Roles"); for (const auto& it : roles) { formatter->open_object_section("role"); it->dump(formatter); formatter->close_section(); } formatter->close_section(); formatter->flush(cout); } static void show_reshard_status( const list<cls_rgw_bucket_instance_entry>& status, Formatter *formatter) { formatter->open_array_section("status"); for (const auto& entry : status) { formatter->open_object_section("entry"); formatter->dump_string("reshard_status", to_string(entry.reshard_status)); formatter->close_section(); } formatter->close_section(); formatter->flush(cout); } class StoreDestructor { rgw::sal::Driver* driver; public: explicit StoreDestructor(rgw::sal::Driver* _s) : driver(_s) {} ~StoreDestructor() { DriverManager::close_storage(driver); rgw_http_client_cleanup(); } }; static int init_bucket(rgw::sal::User* user, const rgw_bucket& b, std::unique_ptr<rgw::sal::Bucket>* bucket) { return driver->get_bucket(dpp(), user, b, bucket, null_yield); } static int init_bucket(rgw::sal::User* user, const string& tenant_name, const string& bucket_name, const string& bucket_id, std::unique_ptr<rgw::sal::Bucket>* bucket) { rgw_bucket b{tenant_name, bucket_name, bucket_id}; return init_bucket(user, b, bucket); } static int read_input(const string& infile, bufferlist& bl) { int fd = 0; if (infile.size()) { fd = open(infile.c_str(), O_RDONLY); if (fd < 0) { int err = -errno; cerr << "error reading input file " << infile << std::endl; return err; } } #define READ_CHUNK 8196 int r; int err; do { char buf[READ_CHUNK]; r = safe_read(fd, buf, READ_CHUNK); if (r < 0) { err = -errno; cerr << "error while reading input" << std::endl; goto out; } bl.append(buf, r); } while (r > 0); err = 0; out: if (infile.size()) { close(fd); } return err; } template <class T> static int read_decode_json(const string& infile, T& t) { bufferlist bl; int ret = read_input(infile, bl); if (ret < 0) { cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl; return ret; } JSONParser p; if (!p.parse(bl.c_str(), bl.length())) { cout << "failed to parse JSON" << std::endl; return -EINVAL; } try { decode_json_obj(t, &p); } catch (const JSONDecoder::err& e) { cout << "failed to decode JSON input: " << e.what() << std::endl; return -EINVAL; } return 0; } template <class T, class K> static int read_decode_json(const string& infile, T& t, K *k) { bufferlist bl; int ret = read_input(infile, bl); if (ret < 0) { cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl; return ret; } JSONParser p; if (!p.parse(bl.c_str(), bl.length())) { cout << "failed to parse JSON" << std::endl; return -EINVAL; } try { t.decode_json(&p, k); } catch (const JSONDecoder::err& e) { cout << "failed to decode JSON input: " << e.what() << std::endl; return -EINVAL; } return 0; } template <class T> static bool decode_dump(const char *field_name, bufferlist& bl, Formatter *f) { T t; auto iter = bl.cbegin(); try { decode(t, iter); } catch (buffer::error& err) { return false; } encode_json(field_name, t, f); return true; } static bool dump_string(const char *field_name, bufferlist& bl, Formatter *f) { string val = bl.to_str(); f->dump_string(field_name, val.c_str() /* hide encoded null termination chars */); return true; } bool set_ratelimit_info(RGWRateLimitInfo& ratelimit, OPT opt_cmd, int64_t max_read_ops, int64_t max_write_ops, int64_t max_read_bytes, int64_t max_write_bytes, bool have_max_read_ops, bool have_max_write_ops, bool have_max_read_bytes, bool have_max_write_bytes) { bool ratelimit_configured = true; switch (opt_cmd) { case OPT::RATELIMIT_ENABLE: case OPT::GLOBAL_RATELIMIT_ENABLE: ratelimit.enabled = true; break; case OPT::RATELIMIT_SET: case OPT::GLOBAL_RATELIMIT_SET: ratelimit_configured = false; if (have_max_read_ops) { if (max_read_ops >= 0) { ratelimit.max_read_ops = max_read_ops; ratelimit_configured = true; } } if (have_max_write_ops) { if (max_write_ops >= 0) { ratelimit.max_write_ops = max_write_ops; ratelimit_configured = true; } } if (have_max_read_bytes) { if (max_read_bytes >= 0) { ratelimit.max_read_bytes = max_read_bytes; ratelimit_configured = true; } } if (have_max_write_bytes) { if (max_write_bytes >= 0) { ratelimit.max_write_bytes = max_write_bytes; ratelimit_configured = true; } } break; case OPT::RATELIMIT_DISABLE: case OPT::GLOBAL_RATELIMIT_DISABLE: ratelimit.enabled = false; break; default: break; } return ratelimit_configured; } void set_quota_info(RGWQuotaInfo& quota, OPT opt_cmd, int64_t max_size, int64_t max_objects, bool have_max_size, bool have_max_objects) { switch (opt_cmd) { case OPT::QUOTA_ENABLE: case OPT::GLOBAL_QUOTA_ENABLE: quota.enabled = true; // falling through on purpose case OPT::QUOTA_SET: case OPT::GLOBAL_QUOTA_SET: if (have_max_objects) { if (max_objects < 0) { quota.max_objects = -1; } else { quota.max_objects = max_objects; } } if (have_max_size) { if (max_size < 0) { quota.max_size = -1; } else { quota.max_size = rgw_rounded_kb(max_size) * 1024; } } break; case OPT::QUOTA_DISABLE: case OPT::GLOBAL_QUOTA_DISABLE: quota.enabled = false; break; default: break; } } int set_bucket_quota(rgw::sal::Driver* driver, OPT opt_cmd, const string& tenant_name, const string& bucket_name, int64_t max_size, int64_t max_objects, bool have_max_size, bool have_max_objects) { std::unique_ptr<rgw::sal::Bucket> bucket; int r = driver->get_bucket(dpp(), nullptr, tenant_name, bucket_name, &bucket, null_yield); if (r < 0) { cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl; return -r; } set_quota_info(bucket->get_info().quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects); r = bucket->put_info(dpp(), false, real_time(), null_yield); if (r < 0) { cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl; return -r; } return 0; } int set_bucket_ratelimit(rgw::sal::Driver* driver, OPT opt_cmd, const string& tenant_name, const string& bucket_name, int64_t max_read_ops, int64_t max_write_ops, int64_t max_read_bytes, int64_t max_write_bytes, bool have_max_read_ops, bool have_max_write_ops, bool have_max_read_bytes, bool have_max_write_bytes) { std::unique_ptr<rgw::sal::Bucket> bucket; int r = driver->get_bucket(dpp(), nullptr, tenant_name, bucket_name, &bucket, null_yield); if (r < 0) { cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl; return -r; } RGWRateLimitInfo ratelimit_info; auto iter = bucket->get_attrs().find(RGW_ATTR_RATELIMIT); if(iter != bucket->get_attrs().end()) { try { bufferlist& bl = iter->second; auto biter = bl.cbegin(); decode(ratelimit_info, biter); } catch (buffer::error& err) { ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl; return -EIO; } } bool ratelimit_configured = set_ratelimit_info(ratelimit_info, opt_cmd, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); if (!ratelimit_configured) { ldpp_dout(dpp(), 0) << "ERROR: no rate limit values have been specified" << dendl; return -EINVAL; } bufferlist bl; ratelimit_info.encode(bl); rgw::sal::Attrs attr; attr[RGW_ATTR_RATELIMIT] = bl; r = bucket->merge_and_store_attrs(dpp(), attr, null_yield); if (r < 0) { cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl; return -r; } return 0; } int set_user_ratelimit(OPT opt_cmd, std::unique_ptr<rgw::sal::User>& user, int64_t max_read_ops, int64_t max_write_ops, int64_t max_read_bytes, int64_t max_write_bytes, bool have_max_read_ops, bool have_max_write_ops, bool have_max_read_bytes, bool have_max_write_bytes) { RGWRateLimitInfo ratelimit_info; user->load_user(dpp(), null_yield); auto iter = user->get_attrs().find(RGW_ATTR_RATELIMIT); if(iter != user->get_attrs().end()) { try { bufferlist& bl = iter->second; auto biter = bl.cbegin(); decode(ratelimit_info, biter); } catch (buffer::error& err) { ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl; return -EIO; } } bool ratelimit_configured = set_ratelimit_info(ratelimit_info, opt_cmd, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); if (!ratelimit_configured) { ldpp_dout(dpp(), 0) << "ERROR: no rate limit values have been specified" << dendl; return -EINVAL; } bufferlist bl; ratelimit_info.encode(bl); rgw::sal::Attrs attr; attr[RGW_ATTR_RATELIMIT] = bl; int r = user->merge_and_store_attrs(dpp(), attr, null_yield); if (r < 0) { cerr << "ERROR: failed writing user instance info: " << cpp_strerror(-r) << std::endl; return -r; } return 0; } int show_user_ratelimit(std::unique_ptr<rgw::sal::User>& user, Formatter *formatter) { RGWRateLimitInfo ratelimit_info; user->load_user(dpp(), null_yield); auto iter = user->get_attrs().find(RGW_ATTR_RATELIMIT); if(iter != user->get_attrs().end()) { try { bufferlist& bl = iter->second; auto biter = bl.cbegin(); decode(ratelimit_info, biter); } catch (buffer::error& err) { ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl; return -EIO; } } formatter->open_object_section("user_ratelimit"); encode_json("user_ratelimit", ratelimit_info, formatter); formatter->close_section(); formatter->flush(cout); cout << std::endl; return 0; } int show_bucket_ratelimit(rgw::sal::Driver* driver, const string& tenant_name, const string& bucket_name, Formatter *formatter) { std::unique_ptr<rgw::sal::Bucket> bucket; int r = driver->get_bucket(dpp(), nullptr, tenant_name, bucket_name, &bucket, null_yield); if (r < 0) { cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl; return -r; } RGWRateLimitInfo ratelimit_info; auto iter = bucket->get_attrs().find(RGW_ATTR_RATELIMIT); if (iter != bucket->get_attrs().end()) { try { bufferlist& bl = iter->second; auto biter = bl.cbegin(); decode(ratelimit_info, biter); } catch (buffer::error& err) { ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl; return -EIO; } } formatter->open_object_section("bucket_ratelimit"); encode_json("bucket_ratelimit", ratelimit_info, formatter); formatter->close_section(); formatter->flush(cout); cout << std::endl; return 0; } int set_user_bucket_quota(OPT opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects, bool have_max_size, bool have_max_objects) { RGWUserInfo& user_info = op_state.get_user_info(); set_quota_info(user_info.quota.bucket_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects); op_state.set_bucket_quota(user_info.quota.bucket_quota); string err; int r = user.modify(dpp(), op_state, null_yield, &err); if (r < 0) { cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl; return -r; } return 0; } int set_user_quota(OPT opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects, bool have_max_size, bool have_max_objects) { RGWUserInfo& user_info = op_state.get_user_info(); set_quota_info(user_info.quota.user_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects); op_state.set_user_quota(user_info.quota.user_quota); string err; int r = user.modify(dpp(), op_state, null_yield, &err); if (r < 0) { cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl; return -r; } return 0; } int check_min_obj_stripe_size(rgw::sal::Driver* driver, rgw::sal::Object* obj, uint64_t min_stripe_size, bool *need_rewrite) { int ret = obj->get_obj_attrs(null_yield, dpp()); if (ret < 0) { ldpp_dout(dpp(), -1) << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << dendl; return ret; } map<string, bufferlist>::iterator iter; iter = obj->get_attrs().find(RGW_ATTR_MANIFEST); if (iter == obj->get_attrs().end()) { *need_rewrite = (obj->get_obj_size() >= min_stripe_size); return 0; } RGWObjManifest manifest; try { bufferlist& bl = iter->second; auto biter = bl.cbegin(); decode(manifest, biter); } catch (buffer::error& err) { ldpp_dout(dpp(), 0) << "ERROR: failed to decode manifest" << dendl; return -EIO; } map<uint64_t, RGWObjManifestPart>& objs = manifest.get_explicit_objs(); map<uint64_t, RGWObjManifestPart>::iterator oiter; for (oiter = objs.begin(); oiter != objs.end(); ++oiter) { RGWObjManifestPart& part = oiter->second; if (part.size >= min_stripe_size) { *need_rewrite = true; return 0; } } *need_rewrite = false; return 0; } int check_obj_locator_underscore(rgw::sal::Object* obj, bool fix, bool remove_bad, Formatter *f) { f->open_object_section("object"); f->open_object_section("key"); f->dump_string("type", "head"); f->dump_string("name", obj->get_name()); f->dump_string("instance", obj->get_instance()); f->close_section(); string oid; string locator; get_obj_bucket_and_oid_loc(obj->get_obj(), oid, locator); f->dump_string("oid", oid); f->dump_string("locator", locator); std::unique_ptr<rgw::sal::Object::ReadOp> read_op = obj->get_read_op(); int ret = read_op->prepare(null_yield, dpp()); bool needs_fixing = (ret == -ENOENT); f->dump_bool("needs_fixing", needs_fixing); string status = (needs_fixing ? "needs_fixing" : "ok"); if ((needs_fixing || remove_bad) && fix) { ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->fix_head_obj_locator(dpp(), obj->get_bucket()->get_info(), needs_fixing, remove_bad, obj->get_key(), null_yield); if (ret < 0) { cerr << "ERROR: fix_head_object_locator() returned ret=" << ret << std::endl; goto done; } status = "fixed"; } done: f->dump_string("status", status); f->close_section(); return 0; } int check_obj_tail_locator_underscore(RGWBucketInfo& bucket_info, rgw_obj_key& key, bool fix, Formatter *f) { f->open_object_section("object"); f->open_object_section("key"); f->dump_string("type", "tail"); f->dump_string("name", key.name); f->dump_string("instance", key.instance); f->close_section(); bool needs_fixing; string status; int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->fix_tail_obj_locator(dpp(), bucket_info, key, fix, &needs_fixing, null_yield); if (ret < 0) { cerr << "ERROR: fix_tail_object_locator_underscore() returned ret=" << ret << std::endl; status = "failed"; } else { status = (needs_fixing && !fix ? "needs_fixing" : "ok"); } f->dump_bool("needs_fixing", needs_fixing); f->dump_string("status", status); f->close_section(); return 0; } int do_check_object_locator(const string& tenant_name, const string& bucket_name, bool fix, bool remove_bad, Formatter *f) { if (remove_bad && !fix) { cerr << "ERROR: can't have remove_bad specified without fix" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::Bucket> bucket; string bucket_id; f->open_object_section("bucket"); f->dump_string("bucket", bucket_name); int ret = init_bucket(nullptr, tenant_name, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return ret; } int count = 0; int max_entries = 1000; string prefix; string delim; string marker; vector<rgw_bucket_dir_entry> result; string ns; rgw::sal::Bucket::ListParams params; rgw::sal::Bucket::ListResults results; params.prefix = prefix; params.delim = delim; params.marker = rgw_obj_key(marker); params.ns = ns; params.enforce_ns = true; params.list_versions = true; f->open_array_section("check_objects"); do { ret = bucket->list(dpp(), params, max_entries - count, results, null_yield); if (ret < 0) { cerr << "ERROR: driver->list_objects(): " << cpp_strerror(-ret) << std::endl; return -ret; } count += results.objs.size(); for (vector<rgw_bucket_dir_entry>::iterator iter = results.objs.begin(); iter != results.objs.end(); ++iter) { std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(iter->key); if (obj->get_name()[0] == '_') { ret = check_obj_locator_underscore(obj.get(), fix, remove_bad, f); if (ret >= 0) { ret = check_obj_tail_locator_underscore(bucket->get_info(), obj->get_key(), fix, f); if (ret < 0) { cerr << "ERROR: check_obj_tail_locator_underscore(): " << cpp_strerror(-ret) << std::endl; return -ret; } } } } f->flush(cout); } while (results.is_truncated && count < max_entries); f->close_section(); f->close_section(); f->flush(cout); return 0; } /// search for a matching zone/zonegroup id and return a connection if found static boost::optional<RGWRESTConn> get_remote_conn(rgw::sal::RadosStore* driver, const RGWZoneGroup& zonegroup, const std::string& remote) { boost::optional<RGWRESTConn> conn; if (remote == zonegroup.get_id()) { conn.emplace(driver->ctx(), driver, remote, zonegroup.endpoints, zonegroup.api_name); } else { for (const auto& z : zonegroup.zones) { const auto& zone = z.second; if (remote == zone.id) { conn.emplace(driver->ctx(), driver, remote, zone.endpoints, zonegroup.api_name); break; } } } return conn; } /// search each zonegroup for a connection static boost::optional<RGWRESTConn> get_remote_conn(rgw::sal::RadosStore* driver, const RGWPeriodMap& period_map, const std::string& remote) { boost::optional<RGWRESTConn> conn; for (const auto& zg : period_map.zonegroups) { conn = get_remote_conn(driver, zg.second, remote); if (conn) { break; } } return conn; } // we expect a very small response static constexpr size_t MAX_REST_RESPONSE = 128 * 1024; static int send_to_remote_gateway(RGWRESTConn* conn, req_info& info, bufferlist& in_data, JSONParser& parser) { if (!conn) { return -EINVAL; } ceph::bufferlist response; rgw_user user; int ret = conn->forward(dpp(), user, info, nullptr, MAX_REST_RESPONSE, &in_data, &response, null_yield); int parse_ret = parser.parse(response.c_str(), response.length()); if (parse_ret < 0) { cerr << "failed to parse response" << std::endl; return parse_ret; } return ret; } static int send_to_url(const string& url, std::optional<string> opt_region, const string& access, const string& secret, req_info& info, bufferlist& in_data, JSONParser& parser) { if (access.empty() || secret.empty()) { cerr << "An --access-key and --secret must be provided with --url." << std::endl; return -EINVAL; } RGWAccessKey key; key.id = access; key.key = secret; param_vec_t params; RGWRESTSimpleRequest req(g_ceph_context, info.method, url, NULL, &params, opt_region); bufferlist response; int ret = req.forward_request(dpp(), key, info, MAX_REST_RESPONSE, &in_data, &response, null_yield); int parse_ret = parser.parse(response.c_str(), response.length()); if (parse_ret < 0) { cout << "failed to parse response" << std::endl; return parse_ret; } return ret; } static int send_to_remote_or_url(RGWRESTConn *conn, const string& url, std::optional<string> opt_region, const string& access, const string& secret, req_info& info, bufferlist& in_data, JSONParser& parser) { if (url.empty()) { return send_to_remote_gateway(conn, info, in_data, parser); } return send_to_url(url, opt_region, access, secret, info, in_data, parser); } static int commit_period(rgw::sal::ConfigStore* cfgstore, RGWRealm& realm, rgw::sal::RealmWriter& realm_writer, RGWPeriod& period, string remote, const string& url, std::optional<string> opt_region, const string& access, const string& secret, bool force) { auto& master_zone = period.get_master_zone().id; if (master_zone.empty()) { cerr << "cannot commit period: period does not have a master zone of a master zonegroup" << std::endl; return -EINVAL; } // are we the period's master zone? if (driver->get_zone()->get_id() == master_zone) { // read the current period RGWPeriod current_period; int ret = cfgstore->read_period(dpp(), null_yield, realm.current_period, std::nullopt, current_period); if (ret < 0) { cerr << "failed to load current period: " << cpp_strerror(ret) << std::endl; return ret; } // the master zone can commit locally ret = rgw::commit_period(dpp(), null_yield, cfgstore, driver, realm, realm_writer, current_period, period, cerr, force); if (ret < 0) { cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl; } return ret; } if (remote.empty() && url.empty()) { // use the new master zone's connection remote = master_zone; cerr << "Sending period to new master zone " << remote << std::endl; } boost::optional<RGWRESTConn> conn; RGWRESTConn *remote_conn = nullptr; if (!remote.empty()) { conn = get_remote_conn(static_cast<rgw::sal::RadosStore*>(driver), period.get_map(), remote); if (!conn) { cerr << "failed to find a zone or zonegroup for remote " << remote << std::endl; return -ENOENT; } remote_conn = &*conn; } // push period to the master with an empty period id period.set_id(string()); RGWEnv env; req_info info(g_ceph_context, &env); info.method = "POST"; info.request_uri = "/admin/realm/period"; // json format into a bufferlist JSONFormatter jf(false); encode_json("period", period, &jf); bufferlist bl; jf.flush(bl); JSONParser p; int ret = send_to_remote_or_url(remote_conn, url, opt_region, access, secret, info, bl, p); if (ret < 0) { cerr << "request failed: " << cpp_strerror(-ret) << std::endl; // did we parse an error message? auto message = p.find_obj("Message"); if (message) { cerr << "Reason: " << message->get_data() << std::endl; } return ret; } // decode the response and driver it back try { decode_json_obj(period, &p); } catch (const JSONDecoder::err& e) { cout << "failed to decode JSON input: " << e.what() << std::endl; return -EINVAL; } if (period.get_id().empty()) { cerr << "Period commit got back an empty period id" << std::endl; return -EINVAL; } // the master zone gave us back the period that it committed, so it's // safe to save it as our latest epoch constexpr bool exclusive = false; ret = cfgstore->create_period(dpp(), null_yield, exclusive, period); if (ret < 0) { cerr << "Error storing committed period " << period.get_id() << ": " << cpp_strerror(ret) << std::endl; return ret; } ret = rgw::reflect_period(dpp(), null_yield, cfgstore, period); if (ret < 0) { cerr << "Error updating local objects: " << cpp_strerror(ret) << std::endl; return ret; } (void) cfgstore->realm_notify_new_period(dpp(), null_yield, period); return ret; } static int update_period(rgw::sal::ConfigStore* cfgstore, const string& realm_id, const string& realm_name, const string& period_epoch, bool commit, const string& remote, const string& url, std::optional<string> opt_region, const string& access, const string& secret, Formatter *formatter, bool force) { RGWRealm realm; std::unique_ptr<rgw::sal::RealmWriter> realm_writer; int ret = rgw::read_realm(dpp(), null_yield, cfgstore, realm_id, realm_name, realm, &realm_writer); if (ret < 0) { cerr << "failed to load realm " << cpp_strerror(-ret) << std::endl; return ret; } std::optional<epoch_t> epoch; if (!period_epoch.empty()) { epoch = atoi(period_epoch.c_str()); } RGWPeriod period; ret = cfgstore->read_period(dpp(), null_yield, realm.current_period, epoch, period); if (ret < 0) { cerr << "failed to load current period: " << cpp_strerror(-ret) << std::endl; return ret; } // convert to the realm's staging period rgw::fork_period(dpp(), period); // update the staging period with all of the realm's zonegroups ret = rgw::update_period(dpp(), null_yield, cfgstore, period); if (ret < 0) { return ret; } constexpr bool exclusive = false; ret = cfgstore->create_period(dpp(), null_yield, exclusive, period); if (ret < 0) { cerr << "failed to driver period: " << cpp_strerror(-ret) << std::endl; return ret; } if (commit) { ret = commit_period(cfgstore, realm, *realm_writer, period, remote, url, opt_region, access, secret, force); if (ret < 0) { cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl; return ret; } } encode_json("period", period, formatter); formatter->flush(cout); return 0; } static int init_bucket_for_sync(rgw::sal::User* user, const string& tenant, const string& bucket_name, const string& bucket_id, std::unique_ptr<rgw::sal::Bucket>* bucket) { int ret = init_bucket(user, tenant, bucket_name, bucket_id, bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return ret; } return 0; } static int do_period_pull(rgw::sal::ConfigStore* cfgstore, RGWRESTConn *remote_conn, const string& url, std::optional<string> opt_region, const string& access_key, const string& secret_key, const string& realm_id, const string& realm_name, const string& period_id, const string& period_epoch, RGWPeriod *period) { RGWEnv env; req_info info(g_ceph_context, &env); info.method = "GET"; info.request_uri = "/admin/realm/period"; map<string, string> &params = info.args.get_params(); if (!realm_id.empty()) params["realm_id"] = realm_id; if (!realm_name.empty()) params["realm_name"] = realm_name; if (!period_id.empty()) params["period_id"] = period_id; if (!period_epoch.empty()) params["epoch"] = period_epoch; bufferlist bl; JSONParser p; int ret = send_to_remote_or_url(remote_conn, url, opt_region, access_key, secret_key, info, bl, p); if (ret < 0) { cerr << "request failed: " << cpp_strerror(-ret) << std::endl; return ret; } try { decode_json_obj(*period, &p); } catch (const JSONDecoder::err& e) { cout << "failed to decode JSON input: " << e.what() << std::endl; return -EINVAL; } constexpr bool exclusive = false; ret = cfgstore->create_period(dpp(), null_yield, exclusive, *period); if (ret < 0) { cerr << "Error storing period " << period->get_id() << ": " << cpp_strerror(ret) << std::endl; } return 0; } void flush_ss(stringstream& ss, list<string>& l) { if (!ss.str().empty()) { l.push_back(ss.str()); } ss.str(""); } stringstream& push_ss(stringstream& ss, list<string>& l, int tab = 0) { flush_ss(ss, l); if (tab > 0) { ss << setw(tab) << "" << setw(1); } return ss; } static void get_md_sync_status(list<string>& status) { RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor()); int ret = sync.init(dpp()); if (ret < 0) { status.push_back(string("failed to retrieve sync info: sync.init() failed: ") + cpp_strerror(-ret)); return; } rgw_meta_sync_status sync_status; ret = sync.read_sync_status(dpp(), &sync_status); if (ret < 0) { status.push_back(string("failed to read sync status: ") + cpp_strerror(-ret)); return; } string status_str; switch (sync_status.sync_info.state) { case rgw_meta_sync_info::StateInit: status_str = "init"; break; case rgw_meta_sync_info::StateBuildingFullSyncMaps: status_str = "preparing for full sync"; break; case rgw_meta_sync_info::StateSync: status_str = "syncing"; break; default: status_str = "unknown"; } status.push_back(status_str); uint64_t full_total = 0; uint64_t full_complete = 0; int num_full = 0; int num_inc = 0; int total_shards = 0; set<int> shards_behind_set; for (auto marker_iter : sync_status.sync_markers) { full_total += marker_iter.second.total_entries; total_shards++; if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) { num_full++; full_complete += marker_iter.second.pos; int shard_id = marker_iter.first; shards_behind_set.insert(shard_id); } else { full_complete += marker_iter.second.total_entries; } if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync) { num_inc++; } } stringstream ss; push_ss(ss, status) << "full sync: " << num_full << "/" << total_shards << " shards"; if (num_full > 0) { push_ss(ss, status) << "full sync: " << full_total - full_complete << " entries to sync"; } push_ss(ss, status) << "incremental sync: " << num_inc << "/" << total_shards << " shards"; map<int, RGWMetadataLogInfo> master_shards_info; string master_period = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_current_period_id(); ret = sync.read_master_log_shards_info(dpp(), master_period, &master_shards_info); if (ret < 0) { status.push_back(string("failed to fetch master sync status: ") + cpp_strerror(-ret)); return; } map<int, string> shards_behind; if (sync_status.sync_info.period != master_period) { status.push_back(string("master is on a different period: master_period=" + master_period + " local_period=" + sync_status.sync_info.period)); } else { for (auto local_iter : sync_status.sync_markers) { int shard_id = local_iter.first; auto iter = master_shards_info.find(shard_id); if (iter == master_shards_info.end()) { /* huh? */ derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl; continue; } auto master_marker = iter->second.marker; if (local_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync && master_marker > local_iter.second.marker) { shards_behind[shard_id] = local_iter.second.marker; shards_behind_set.insert(shard_id); } } } // fetch remote log entries to determine the oldest change std::optional<std::pair<int, ceph::real_time>> oldest; if (!shards_behind.empty()) { map<int, rgw_mdlog_shard_data> master_pos; ret = sync.read_master_log_shards_next(dpp(), sync_status.sync_info.period, shards_behind, &master_pos); if (ret < 0) { derr << "ERROR: failed to fetch master next positions (" << cpp_strerror(-ret) << ")" << dendl; } else { for (auto iter : master_pos) { rgw_mdlog_shard_data& shard_data = iter.second; if (shard_data.entries.empty()) { // there aren't any entries in this shard, so we're not really behind shards_behind.erase(iter.first); shards_behind_set.erase(iter.first); } else { rgw_mdlog_entry& entry = shard_data.entries.front(); if (!oldest) { oldest.emplace(iter.first, entry.timestamp); } else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest->second) { oldest.emplace(iter.first, entry.timestamp); } } } } } int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc); if (total_behind == 0) { push_ss(ss, status) << "metadata is caught up with master"; } else { push_ss(ss, status) << "metadata is behind on " << total_behind << " shards"; push_ss(ss, status) << "behind shards: " << "[" << shards_behind_set << "]"; if (oldest) { push_ss(ss, status) << "oldest incremental change not applied: " << oldest->second << " [" << oldest->first << ']'; } } flush_ss(ss, status); } static void get_data_sync_status(const rgw_zone_id& source_zone, list<string>& status, int tab) { stringstream ss; RGWZone *sz; if (!(sz = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->find_zone(source_zone))) { push_ss(ss, status, tab) << string("zone not found"); flush_ss(ss, status); return; } if (!static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->zone_syncs_from(static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone(), *sz)) { push_ss(ss, status, tab) << string("not syncing from zone"); flush_ss(ss, status); return; } RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr); int ret = sync.init(dpp()); if (ret < 0) { push_ss(ss, status, tab) << string("failed to retrieve sync info: ") + cpp_strerror(-ret); flush_ss(ss, status); return; } rgw_data_sync_status sync_status; ret = sync.read_sync_status(dpp(), &sync_status); if (ret < 0 && ret != -ENOENT) { push_ss(ss, status, tab) << string("failed read sync status: ") + cpp_strerror(-ret); return; } set<int> recovering_shards; ret = sync.read_recovering_shards(dpp(), sync_status.sync_info.num_shards, recovering_shards); if (ret < 0 && ret != ENOENT) { push_ss(ss, status, tab) << string("failed read recovering shards: ") + cpp_strerror(-ret); return; } string status_str; switch (sync_status.sync_info.state) { case rgw_data_sync_info::StateInit: status_str = "init"; break; case rgw_data_sync_info::StateBuildingFullSyncMaps: status_str = "preparing for full sync"; break; case rgw_data_sync_info::StateSync: status_str = "syncing"; break; default: status_str = "unknown"; } push_ss(ss, status, tab) << status_str; uint64_t full_total = 0; uint64_t full_complete = 0; int num_full = 0; int num_inc = 0; int total_shards = 0; set<int> shards_behind_set; for (auto marker_iter : sync_status.sync_markers) { full_total += marker_iter.second.total_entries; total_shards++; if (marker_iter.second.state == rgw_data_sync_marker::SyncState::FullSync) { num_full++; full_complete += marker_iter.second.pos; int shard_id = marker_iter.first; shards_behind_set.insert(shard_id); } else { full_complete += marker_iter.second.total_entries; } if (marker_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync) { num_inc++; } } push_ss(ss, status, tab) << "full sync: " << num_full << "/" << total_shards << " shards"; if (num_full > 0) { push_ss(ss, status, tab) << "full sync: " << full_total - full_complete << " buckets to sync"; } push_ss(ss, status, tab) << "incremental sync: " << num_inc << "/" << total_shards << " shards"; map<int, RGWDataChangesLogInfo> source_shards_info; ret = sync.read_source_log_shards_info(dpp(), &source_shards_info); if (ret < 0) { push_ss(ss, status, tab) << string("failed to fetch source sync status: ") + cpp_strerror(-ret); return; } map<int, string> shards_behind; for (auto local_iter : sync_status.sync_markers) { int shard_id = local_iter.first; auto iter = source_shards_info.find(shard_id); if (iter == source_shards_info.end()) { /* huh? */ derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl; continue; } auto master_marker = iter->second.marker; if (local_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync && master_marker > local_iter.second.marker) { shards_behind[shard_id] = local_iter.second.marker; shards_behind_set.insert(shard_id); } } std::optional<std::pair<int, ceph::real_time>> oldest; if (!shards_behind.empty()) { map<int, rgw_datalog_shard_data> master_pos; ret = sync.read_source_log_shards_next(dpp(), shards_behind, &master_pos); if (ret < 0) { derr << "ERROR: failed to fetch next positions (" << cpp_strerror(-ret) << ")" << dendl; } else { for (auto iter : master_pos) { rgw_datalog_shard_data& shard_data = iter.second; if (shard_data.entries.empty()) { // there aren't any entries in this shard, so we're not really behind shards_behind.erase(iter.first); shards_behind_set.erase(iter.first); } else { rgw_datalog_entry& entry = shard_data.entries.front(); if (!oldest) { oldest.emplace(iter.first, entry.timestamp); } else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest->second) { oldest.emplace(iter.first, entry.timestamp); } } } } } int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc); int total_recovering = recovering_shards.size(); if (total_behind == 0 && total_recovering == 0) { push_ss(ss, status, tab) << "data is caught up with source"; } else if (total_behind > 0) { push_ss(ss, status, tab) << "data is behind on " << total_behind << " shards"; push_ss(ss, status, tab) << "behind shards: " << "[" << shards_behind_set << "]" ; if (oldest) { push_ss(ss, status, tab) << "oldest incremental change not applied: " << oldest->second << " [" << oldest->first << ']'; } } if (total_recovering > 0) { push_ss(ss, status, tab) << total_recovering << " shards are recovering"; push_ss(ss, status, tab) << "recovering shards: " << "[" << recovering_shards << "]"; } flush_ss(ss, status); } static void tab_dump(const string& header, int width, const list<string>& entries) { string s = header; for (auto e : entries) { cout << std::setw(width) << s << std::setw(1) << " " << e << std::endl; s.clear(); } } // return features that are supported but not enabled static auto get_disabled_features(const rgw::zone_features::set& enabled) { auto features = rgw::zone_features::set{rgw::zone_features::supported.begin(), rgw::zone_features::supported.end()}; for (const auto& feature : enabled) { features.erase(feature); } return features; } static void sync_status(Formatter *formatter) { const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup(); rgw::sal::Zone* zone = driver->get_zone(); int width = 15; cout << std::setw(width) << "realm" << std::setw(1) << " " << zone->get_realm_id() << " (" << zone->get_realm_name() << ")" << std::endl; cout << std::setw(width) << "zonegroup" << std::setw(1) << " " << zonegroup.get_id() << " (" << zonegroup.get_name() << ")" << std::endl; cout << std::setw(width) << "zone" << std::setw(1) << " " << zone->get_id() << " (" << zone->get_name() << ")" << std::endl; cout << std::setw(width) << "current time" << std::setw(1) << " " << to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms) << std::endl; const auto& rzg = static_cast<const rgw::sal::RadosZoneGroup&>(zonegroup).get_group(); cout << std::setw(width) << "zonegroup features enabled: " << rzg.enabled_features << std::endl; if (auto d = get_disabled_features(rzg.enabled_features); !d.empty()) { cout << std::setw(width) << " disabled: " << d << std::endl; } list<string> md_status; if (driver->is_meta_master()) { md_status.push_back("no sync (zone is master)"); } else { get_md_sync_status(md_status); } tab_dump("metadata sync", width, md_status); list<string> data_status; auto& zone_conn_map = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_conn_map(); for (auto iter : zone_conn_map) { const rgw_zone_id& source_id = iter.first; string source_str = "source: "; string s = source_str + source_id.id; std::unique_ptr<rgw::sal::Zone> sz; if (driver->get_zone()->get_zonegroup().get_zone_by_id(source_id.id, &sz) == 0) { s += string(" (") + sz->get_name() + ")"; } data_status.push_back(s); get_data_sync_status(source_id, data_status, source_str.size()); } tab_dump("data sync", width, data_status); } struct indented { int w; // indent width std::string_view header; indented(int w, std::string_view header = "") : w(w), header(header) {} }; std::ostream& operator<<(std::ostream& out, const indented& h) { return out << std::setw(h.w) << h.header << std::setw(1) << ' '; } static int bucket_source_sync_status(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* driver, const RGWZone& zone, const RGWZone& source, RGWRESTConn *conn, const RGWBucketInfo& bucket_info, rgw_sync_bucket_pipe pipe, int width, std::ostream& out) { out << indented{width, "source zone"} << source.id << " (" << source.name << ")" << std::endl; // syncing from this zone? if (!driver->svc()->zone->zone_syncs_from(zone, source)) { out << indented{width} << "does not sync from zone\n"; return 0; } if (!pipe.source.bucket) { ldpp_dout(dpp, -1) << __func__ << "(): missing source bucket" << dendl; return -EINVAL; } std::unique_ptr<rgw::sal::Bucket> source_bucket; int r = init_bucket(nullptr, *pipe.source.bucket, &source_bucket); if (r < 0) { ldpp_dout(dpp, -1) << "failed to read source bucket info: " << cpp_strerror(r) << dendl; return r; } out << indented{width, "source bucket"} << source_bucket->get_key() << std::endl; pipe.source.bucket = source_bucket->get_key(); pipe.dest.bucket = bucket_info.bucket; uint64_t gen = 0; std::vector<rgw_bucket_shard_sync_info> shard_status; // check for full sync status rgw_bucket_sync_status full_status; r = rgw_read_bucket_full_sync_status(dpp, driver, pipe, &full_status, null_yield); if (r >= 0) { if (full_status.state == BucketSyncState::Init) { out << indented{width} << "init: bucket sync has not started\n"; return 0; } if (full_status.state == BucketSyncState::Stopped) { out << indented{width} << "stopped: bucket sync is disabled\n"; return 0; } if (full_status.state == BucketSyncState::Full) { out << indented{width} << "full sync: " << full_status.full.count << " objects completed\n"; return 0; } gen = full_status.incremental_gen; shard_status.resize(full_status.shards_done_with_gen.size()); } else if (r == -ENOENT) { // no full status, but there may be per-shard status from before upgrade const auto& logs = source_bucket->get_info().layout.logs; if (logs.empty()) { out << indented{width} << "init: bucket sync has not started\n"; return 0; } const auto& log = logs.front(); if (log.gen > 0) { // this isn't the backward-compatible case, so we just haven't started yet out << indented{width} << "init: bucket sync has not started\n"; return 0; } if (log.layout.type != rgw::BucketLogType::InIndex) { ldpp_dout(dpp, -1) << "unrecognized log layout type " << log.layout.type << dendl; return -EINVAL; } // use shard count from our log gen=0 shard_status.resize(rgw::num_shards(log.layout.in_index)); } else { lderr(driver->ctx()) << "failed to read bucket full sync status: " << cpp_strerror(r) << dendl; return r; } r = rgw_read_bucket_inc_sync_status(dpp, driver, pipe, gen, &shard_status); if (r < 0) { lderr(driver->ctx()) << "failed to read bucket incremental sync status: " << cpp_strerror(r) << dendl; return r; } const int total_shards = shard_status.size(); out << indented{width} << "incremental sync on " << total_shards << " shards\n"; rgw_bucket_index_marker_info remote_info; BucketIndexShardsManager remote_markers; r = rgw_read_remote_bilog_info(dpp, conn, source_bucket->get_key(), remote_info, remote_markers, null_yield); if (r < 0) { ldpp_dout(dpp, -1) << "failed to read remote log: " << cpp_strerror(r) << dendl; return r; } std::set<int> shards_behind; for (const auto& r : remote_markers.get()) { auto shard_id = r.first; if (r.second.empty()) { continue; // empty bucket index shard } if (shard_id >= total_shards) { // unexpected shard id. we don't have status for it, so we're behind shards_behind.insert(shard_id); continue; } auto& m = shard_status[shard_id]; const auto pos = BucketIndexShardsManager::get_shard_marker(m.inc_marker.position); if (pos < r.second) { shards_behind.insert(shard_id); } } if (!shards_behind.empty()) { out << indented{width} << "bucket is behind on " << shards_behind.size() << " shards\n"; out << indented{width} << "behind shards: [" << shards_behind << "]\n" ; } else { out << indented{width} << "bucket is caught up with source\n"; } return 0; } void encode_json(const char *name, const RGWBucketSyncFlowManager::pipe_set& pset, Formatter *f) { Formatter::ObjectSection top_section(*f, name); Formatter::ArraySection as(*f, "entries"); for (auto& pipe_handler : pset) { Formatter::ObjectSection hs(*f, "handler"); encode_json("source", pipe_handler.source, f); encode_json("dest", pipe_handler.dest, f); } } static std::vector<string> convert_bucket_set_to_str_vec(const std::set<rgw_bucket>& bs) { std::vector<string> result; result.reserve(bs.size()); for (auto& b : bs) { result.push_back(b.get_key()); } return result; } static void get_hint_entities(const std::set<rgw_zone_id>& zones, const std::set<rgw_bucket>& buckets, std::set<rgw_sync_bucket_entity> *hint_entities) { for (auto& zone_id : zones) { for (auto& b : buckets) { std::unique_ptr<rgw::sal::Bucket> hint_bucket; int ret = init_bucket(nullptr, b, &hint_bucket); if (ret < 0) { ldpp_dout(dpp(), 20) << "could not init bucket info for hint bucket=" << b << " ... skipping" << dendl; continue; } hint_entities->insert(rgw_sync_bucket_entity(zone_id, hint_bucket->get_key())); } } } static rgw_zone_id resolve_zone_id(const string& s) { std::unique_ptr<rgw::sal::Zone> zone; int ret = driver->get_zone()->get_zonegroup().get_zone_by_id(s, &zone); if (ret < 0) ret = driver->get_zone()->get_zonegroup().get_zone_by_name(s, &zone); if (ret < 0) return rgw_zone_id(s); return rgw_zone_id(zone->get_id()); } rgw_zone_id validate_zone_id(const rgw_zone_id& zone_id) { return resolve_zone_id(zone_id.id); } static int sync_info(std::optional<rgw_zone_id> opt_target_zone, std::optional<rgw_bucket> opt_bucket, Formatter *formatter) { rgw_zone_id zone_id = opt_target_zone.value_or(driver->get_zone()->get_id()); auto zone_policy_handler = driver->get_zone()->get_sync_policy_handler(); RGWBucketSyncPolicyHandlerRef bucket_handler; std::optional<rgw_bucket> eff_bucket = opt_bucket; auto handler = zone_policy_handler; if (eff_bucket) { std::unique_ptr<rgw::sal::Bucket> bucket; int ret = init_bucket(nullptr, *eff_bucket, &bucket); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: init_bucket failed: " << cpp_strerror(-ret) << std::endl; return ret; } if (ret >= 0) { rgw::sal::Attrs attrs = bucket->get_attrs(); bucket_handler.reset(handler->alloc_child(bucket->get_info(), std::move(attrs))); } else { cerr << "WARNING: bucket not found, simulating result" << std::endl; bucket_handler.reset(handler->alloc_child(*eff_bucket, nullopt)); } ret = bucket_handler->init(dpp(), null_yield); if (ret < 0) { cerr << "ERROR: failed to init bucket sync policy handler: " << cpp_strerror(-ret) << " (ret=" << ret << ")" << std::endl; return ret; } handler = bucket_handler; } std::set<rgw_sync_bucket_pipe> sources; std::set<rgw_sync_bucket_pipe> dests; handler->get_pipes(&sources, &dests, std::nullopt); auto source_hints_vec = convert_bucket_set_to_str_vec(handler->get_source_hints()); auto target_hints_vec = convert_bucket_set_to_str_vec(handler->get_target_hints()); std::set<rgw_sync_bucket_pipe> resolved_sources; std::set<rgw_sync_bucket_pipe> resolved_dests; rgw_sync_bucket_entity self_entity(zone_id, opt_bucket); set<rgw_zone_id> source_zones; set<rgw_zone_id> target_zones; zone_policy_handler->reflect(dpp(), nullptr, nullptr, nullptr, nullptr, &source_zones, &target_zones, false); /* relaxed: also get all zones that we allow to sync to/from */ std::set<rgw_sync_bucket_entity> hint_entities; get_hint_entities(source_zones, handler->get_source_hints(), &hint_entities); get_hint_entities(target_zones, handler->get_target_hints(), &hint_entities); for (auto& hint_entity : hint_entities) { if (!hint_entity.zone || !hint_entity.bucket) { continue; /* shouldn't really happen */ } auto zid = validate_zone_id(*hint_entity.zone); auto& hint_bucket = *hint_entity.bucket; RGWBucketSyncPolicyHandlerRef hint_bucket_handler; int r = driver->get_sync_policy_handler(dpp(), zid, hint_bucket, &hint_bucket_handler, null_yield); if (r < 0) { ldpp_dout(dpp(), 20) << "could not get bucket sync policy handler for hint bucket=" << hint_bucket << " ... skipping" << dendl; continue; } hint_bucket_handler->get_pipes(&resolved_dests, &resolved_sources, self_entity); /* flipping resolved dests and sources as these are relative to the remote entity */ } { Formatter::ObjectSection os(*formatter, "result"); encode_json("sources", sources, formatter); encode_json("dests", dests, formatter); { Formatter::ObjectSection hints_section(*formatter, "hints"); encode_json("sources", source_hints_vec, formatter); encode_json("dests", target_hints_vec, formatter); } { Formatter::ObjectSection resolved_hints_section(*formatter, "resolved-hints-1"); encode_json("sources", resolved_sources, formatter); encode_json("dests", resolved_dests, formatter); } { Formatter::ObjectSection resolved_hints_section(*formatter, "resolved-hints"); encode_json("sources", handler->get_resolved_source_hints(), formatter); encode_json("dests", handler->get_resolved_dest_hints(), formatter); } } formatter->flush(cout); return 0; } static int bucket_sync_info(rgw::sal::Driver* driver, const RGWBucketInfo& info, std::ostream& out) { const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup(); rgw::sal::Zone* zone = driver->get_zone(); constexpr int width = 15; out << indented{width, "realm"} << zone->get_realm_id() << " (" << zone->get_realm_name() << ")\n"; out << indented{width, "zonegroup"} << zonegroup.get_id() << " (" << zonegroup.get_name() << ")\n"; out << indented{width, "zone"} << zone->get_id() << " (" << zone->get_name() << ")\n"; out << indented{width, "bucket"} << info.bucket << "\n\n"; if (!static_cast<rgw::sal::RadosStore*>(driver)->ctl()->bucket->bucket_imports_data(info.bucket, null_yield, dpp())) { out << "Sync is disabled for bucket " << info.bucket.name << '\n'; return 0; } RGWBucketSyncPolicyHandlerRef handler; int r = driver->get_sync_policy_handler(dpp(), std::nullopt, info.bucket, &handler, null_yield); if (r < 0) { ldpp_dout(dpp(), -1) << "ERROR: failed to get policy handler for bucket (" << info.bucket << "): r=" << r << ": " << cpp_strerror(-r) << dendl; return r; } auto& sources = handler->get_sources(); for (auto& m : sources) { auto& zone = m.first; out << indented{width, "source zone"} << zone << std::endl; for (auto& pipe_handler : m.second) { out << indented{width, "bucket"} << *pipe_handler.source.bucket << std::endl; } } return 0; } static int bucket_sync_status(rgw::sal::Driver* driver, const RGWBucketInfo& info, const rgw_zone_id& source_zone_id, std::optional<rgw_bucket>& opt_source_bucket, std::ostream& out) { const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup(); rgw::sal::Zone* zone = driver->get_zone(); constexpr int width = 15; out << indented{width, "realm"} << zone->get_realm_id() << " (" << zone->get_realm_name() << ")\n"; out << indented{width, "zonegroup"} << zonegroup.get_id() << " (" << zonegroup.get_name() << ")\n"; out << indented{width, "zone"} << zone->get_id() << " (" << zone->get_name() << ")\n"; out << indented{width, "bucket"} << info.bucket << "\n"; out << indented{width, "current time"} << to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms) << "\n\n"; if (!static_cast<rgw::sal::RadosStore*>(driver)->ctl()->bucket->bucket_imports_data(info.bucket, null_yield, dpp())) { out << "Sync is disabled for bucket " << info.bucket.name << " or bucket has no sync sources" << std::endl; return 0; } RGWBucketSyncPolicyHandlerRef handler; int r = driver->get_sync_policy_handler(dpp(), std::nullopt, info.bucket, &handler, null_yield); if (r < 0) { ldpp_dout(dpp(), -1) << "ERROR: failed to get policy handler for bucket (" << info.bucket << "): r=" << r << ": " << cpp_strerror(-r) << dendl; return r; } auto sources = handler->get_all_sources(); auto& zone_conn_map = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_conn_map(); set<rgw_zone_id> zone_ids; if (!source_zone_id.empty()) { std::unique_ptr<rgw::sal::Zone> zone; int ret = driver->get_zone()->get_zonegroup().get_zone_by_id(source_zone_id.id, &zone); if (ret < 0) { ldpp_dout(dpp(), -1) << "Source zone not found in zonegroup " << zonegroup.get_name() << dendl; return -EINVAL; } auto c = zone_conn_map.find(source_zone_id); if (c == zone_conn_map.end()) { ldpp_dout(dpp(), -1) << "No connection to zone " << zone->get_name() << dendl; return -EINVAL; } zone_ids.insert(source_zone_id); } else { std::list<std::string> ids; int ret = driver->get_zone()->get_zonegroup().list_zones(ids); if (ret == 0) { for (const auto& entry : ids) { zone_ids.insert(entry); } } } for (auto& zone_id : zone_ids) { auto z = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zonegroup().zones.find(zone_id.id); if (z == static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zonegroup().zones.end()) { /* should't happen */ continue; } auto c = zone_conn_map.find(zone_id.id); if (c == zone_conn_map.end()) { /* should't happen */ continue; } for (auto& entry : sources) { auto& pipe = entry.second; if (opt_source_bucket && pipe.source.bucket != opt_source_bucket) { continue; } if (pipe.source.zone.value_or(rgw_zone_id()) == z->second.id) { bucket_source_sync_status(dpp(), static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone(), z->second, c->second, info, pipe, width, out); } } } return 0; } static void parse_tier_config_param(const string& s, map<string, string, ltstr_nocase>& out) { int level = 0; string cur_conf; list<string> confs; for (auto c : s) { if (c == ',') { if (level == 0) { confs.push_back(cur_conf); cur_conf.clear(); continue; } } if (c == '{') { ++level; } else if (c == '}') { --level; } cur_conf += c; } if (!cur_conf.empty()) { confs.push_back(cur_conf); } for (auto c : confs) { ssize_t pos = c.find("="); if (pos < 0) { out[c] = ""; } else { out[c.substr(0, pos)] = c.substr(pos + 1); } } } static int check_pool_support_omap(const rgw_pool& pool) { librados::IoCtx io_ctx; int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_rados_handle()->ioctx_create(pool.to_str().c_str(), io_ctx); if (ret < 0) { // the pool may not exist at this moment, we have no way to check if it supports omap. return 0; } ret = io_ctx.omap_clear("__omap_test_not_exist_oid__"); if (ret == -EOPNOTSUPP) { io_ctx.close(); return ret; } io_ctx.close(); return 0; } int check_reshard_bucket_params(rgw::sal::Driver* driver, const string& bucket_name, const string& tenant, const string& bucket_id, bool num_shards_specified, int num_shards, int yes_i_really_mean_it, std::unique_ptr<rgw::sal::Bucket>* bucket) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return -EINVAL; } if (!num_shards_specified) { cerr << "ERROR: --num-shards not specified" << std::endl; return -EINVAL; } if (num_shards > (int)static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_max_bucket_shards()) { cerr << "ERROR: num_shards too high, max value: " << static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_max_bucket_shards() << std::endl; return -EINVAL; } if (num_shards < 0) { cerr << "ERROR: num_shards must be non-negative integer" << std::endl; return -EINVAL; } int ret = init_bucket(nullptr, tenant, bucket_name, bucket_id, bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return ret; } int num_source_shards = rgw::current_num_shards((*bucket)->get_info().layout); if (num_shards <= num_source_shards && !yes_i_really_mean_it) { cerr << "num shards is less or equal to current shards count" << std::endl << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return -EINVAL; } return 0; } static int scan_totp(CephContext *cct, ceph::real_time& now, rados::cls::otp::otp_info_t& totp, vector<string>& pins, time_t *pofs) { #define MAX_TOTP_SKEW_HOURS (24 * 7) time_t start_time = ceph::real_clock::to_time_t(now); time_t time_ofs = 0, time_ofs_abs = 0; time_t step_size = totp.step_size; if (step_size == 0) { step_size = OATH_TOTP_DEFAULT_TIME_STEP_SIZE; } uint32_t count = 0; int sign = 1; uint32_t max_skew = MAX_TOTP_SKEW_HOURS * 3600; while (time_ofs_abs < max_skew) { int rc = oath_totp_validate2(totp.seed_bin.c_str(), totp.seed_bin.length(), start_time, step_size, time_ofs, 1, nullptr, pins[0].c_str()); if (rc != OATH_INVALID_OTP) { // oath_totp_validate2 is an external library function, cannot fix internally // Further, step_size is a small number and unlikely to overflow // coverity[store_truncates_time_t:SUPPRESS] rc = oath_totp_validate2(totp.seed_bin.c_str(), totp.seed_bin.length(), start_time, step_size, time_ofs - step_size, /* smaller time_ofs moves time forward */ 1, nullptr, pins[1].c_str()); if (rc != OATH_INVALID_OTP) { *pofs = time_ofs - step_size + step_size * totp.window / 2; ldpp_dout(dpp(), 20) << "found at time=" << start_time - time_ofs << " time_ofs=" << time_ofs << dendl; return 0; } } sign = -sign; time_ofs_abs = (++count) * step_size; time_ofs = sign * time_ofs_abs; } return -ENOENT; } static int trim_sync_error_log(int shard_id, const string& marker, int delay_ms) { auto oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX, shard_id); // call cls_log_trim() until it returns -ENODATA for (;;) { int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->timelog.trim(dpp(), oid, {}, {}, {}, marker, nullptr, null_yield); if (ret == -ENODATA) { return 0; } if (ret < 0) { return ret; } if (delay_ms) { std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); } } // unreachable } static bool symmetrical_flow_opt(const string& opt) { return (opt == "symmetrical" || opt == "symmetric"); } static bool directional_flow_opt(const string& opt) { return (opt == "directional" || opt == "direction"); } template <class T> static bool require_opt(std::optional<T> opt, bool extra_check = true) { if (!opt || !extra_check) { return false; } return true; } template <class T> static bool require_non_empty_opt(std::optional<T> opt, bool extra_check = true) { if (!opt || opt->empty() || !extra_check) { return false; } return true; } template <class T> static void show_result(T& obj, Formatter *formatter, ostream& os) { encode_json("obj", obj, formatter); formatter->flush(cout); } void init_optional_bucket(std::optional<rgw_bucket>& opt_bucket, std::optional<string>& opt_tenant, std::optional<string>& opt_bucket_name, std::optional<string>& opt_bucket_id) { if (opt_tenant || opt_bucket_name || opt_bucket_id) { opt_bucket.emplace(); if (opt_tenant) { opt_bucket->tenant = *opt_tenant; } if (opt_bucket_name) { opt_bucket->name = *opt_bucket_name; } if (opt_bucket_id) { opt_bucket->bucket_id = *opt_bucket_id; } } } class SyncPolicyContext { rgw::sal::ConfigStore* cfgstore; RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer; std::optional<rgw_bucket> b; std::unique_ptr<rgw::sal::Bucket> bucket; rgw_sync_policy_info *policy{nullptr}; std::optional<rgw_user> owner; public: SyncPolicyContext(rgw::sal::ConfigStore* cfgstore, std::optional<rgw_bucket> _bucket) : cfgstore(cfgstore), b(std::move(_bucket)) {} int init(const string& zonegroup_id, const string& zonegroup_name) { int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore, zonegroup_id, zonegroup_name, zonegroup, &zonegroup_writer); if (ret < 0) { cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl; return ret; } if (!b) { policy = &zonegroup.sync_policy; return 0; } ret = init_bucket(nullptr, *b, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return ret; } owner = bucket->get_info().owner; if (!bucket->get_info().sync_policy) { rgw_sync_policy_info new_policy; bucket->get_info().set_sync_policy(std::move(new_policy)); } policy = &(*bucket->get_info().sync_policy); return 0; } int write_policy() { if (!b) { int ret = zonegroup_writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } return 0; } int ret = bucket->put_info(dpp(), false, real_time(), null_yield); if (ret < 0) { cerr << "failed to driver bucket info: " << cpp_strerror(-ret) << std::endl; return -ret; } return 0; } rgw_sync_policy_info& get_policy() { return *policy; } std::optional<rgw_user>& get_owner() { return owner; } }; void resolve_zone_id_opt(std::optional<string>& zone_name, std::optional<rgw_zone_id>& zone_id) { if (!zone_name || zone_id) { return; } zone_id.emplace(); std::unique_ptr<rgw::sal::Zone> zone; int ret = driver->get_zone()->get_zonegroup().get_zone_by_name(*zone_name, &zone); if (ret < 0) { cerr << "WARNING: cannot find source zone id for name=" << *zone_name << std::endl; zone_id = rgw_zone_id(*zone_name); } else { zone_id->id = zone->get_id(); } } void resolve_zone_ids_opt(std::optional<vector<string> >& names, std::optional<vector<rgw_zone_id> >& ids) { if (!names || ids) { return; } ids.emplace(); for (auto& name : *names) { rgw_zone_id zid; std::unique_ptr<rgw::sal::Zone> zone; int ret = driver->get_zone()->get_zonegroup().get_zone_by_name(name, &zone); if (ret < 0) { cerr << "WARNING: cannot find source zone id for name=" << name << std::endl; zid = rgw_zone_id(name); } else { zid.id = zone->get_id(); } ids->push_back(zid); } } static vector<rgw_zone_id> zone_ids_from_str(const string& val) { vector<rgw_zone_id> result; vector<string> v; get_str_vec(val, v); for (auto& z : v) { result.push_back(rgw_zone_id(z)); } return result; } class JSONFormatter_PrettyZone : public JSONFormatter { class Handler : public JSONEncodeFilter::Handler<rgw_zone_id> { void encode_json(const char *name, const void *pval, ceph::Formatter *f) const override { auto zone_id = *(static_cast<const rgw_zone_id *>(pval)); string zone_name; std::unique_ptr<rgw::sal::Zone> zone; if (driver->get_zone()->get_zonegroup().get_zone_by_id(zone_id.id, &zone) == 0) { zone_name = zone->get_name(); } else { cerr << "WARNING: cannot find zone name for id=" << zone_id << std::endl; zone_name = zone_id.id; } ::encode_json(name, zone_name, f); } } zone_id_type_handler; JSONEncodeFilter encode_filter; public: JSONFormatter_PrettyZone(bool pretty_format) : JSONFormatter(pretty_format) { encode_filter.register_type(&zone_id_type_handler); } void *get_external_feature_handler(const std::string& feature) override { if (feature != "JSONEncodeFilter") { return nullptr; } return &encode_filter; } }; void init_realm_param(CephContext *cct, string& var, std::optional<string>& opt_var, const string& conf_name) { var = cct->_conf.get_val<string>(conf_name); if (!var.empty()) { opt_var = var; } } int main(int argc, const char **argv) { auto args = argv_to_vec(argc, argv); if (args.empty()) { cerr << argv[0] << ": -h or --help for usage" << std::endl; exit(1); } if (ceph_argparse_need_usage(args)) { usage(); exit(0); } auto cct = rgw_global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); // for region -> zonegroup conversion (must happen before common_init_finish()) if (!g_conf()->rgw_region.empty() && g_conf()->rgw_zonegroup.empty()) { g_conf().set_val_or_die("rgw_zonegroup", g_conf()->rgw_region.c_str()); } rgw_user user_id_arg; std::unique_ptr<rgw::sal::User> user; string tenant; string user_ns; rgw_user new_user_id; std::string access_key, secret_key, user_email, display_name; std::string bucket_name, pool_name, object; rgw_pool pool; std::string date, subuser, access, format; std::string start_date, end_date; std::string key_type_str; std::string period_id, period_epoch, remote, url; std::optional<string> opt_region; std::string master_zone; std::string realm_name, realm_id, realm_new_name; std::optional<string> opt_realm_name, opt_realm_id; std::string zone_name, zone_id, zone_new_name; std::optional<string> opt_zone_name, opt_zone_id; std::string zonegroup_name, zonegroup_id, zonegroup_new_name; std::optional<string> opt_zonegroup_name, opt_zonegroup_id; std::string api_name; std::string role_name, path, assume_role_doc, policy_name, perm_policy_doc, path_prefix, max_session_duration; std::string redirect_zone; bool redirect_zone_set = false; list<string> endpoints; int tmp_int; int sync_from_all_specified = false; bool sync_from_all = false; list<string> sync_from; list<string> sync_from_rm; int is_master_int; int set_default = 0; bool is_master = false; bool is_master_set = false; int read_only_int; bool read_only = false; int is_read_only_set = false; int commit = false; int staging = false; int key_type = KEY_TYPE_UNDEFINED; std::unique_ptr<rgw::sal::Bucket> bucket; uint32_t perm_mask = 0; RGWUserInfo info; OPT opt_cmd = OPT::NO_CMD; int gen_access_key = 0; int gen_secret_key = 0; bool set_perm = false; bool set_temp_url_key = false; map<int, string> temp_url_keys; string bucket_id; string new_bucket_name; std::unique_ptr<Formatter> formatter; std::unique_ptr<Formatter> zone_formatter; int purge_data = false; int pretty_format = false; int show_log_entries = true; int show_log_sum = true; int skip_zero_entries = false; // log show int purge_keys = false; int yes_i_really_mean_it = false; int delete_child_objects = false; int fix = false; int remove_bad = false; int check_head_obj_locator = false; int max_buckets = -1; bool max_buckets_specified = false; map<string, bool> categories; string caps; int check_objects = false; RGWBucketAdminOpState bucket_op; string infile; string metadata_key; RGWObjVersionTracker objv_tracker; string marker; string start_marker; string end_marker; int max_entries = -1; bool max_entries_specified = false; int admin = false; bool admin_specified = false; int system = false; bool system_specified = false; int shard_id = -1; bool specified_shard_id = false; string client_id; string op_id; string op_mask_str; string quota_scope; string ratelimit_scope; std::string objects_file; string object_version; string placement_id; std::optional<string> opt_storage_class; list<string> tags; list<string> tags_add; list<string> tags_rm; int placement_inline_data = true; bool placement_inline_data_specified = false; int64_t max_objects = -1; int64_t max_size = -1; int64_t max_read_ops = 0; int64_t max_write_ops = 0; int64_t max_read_bytes = 0; int64_t max_write_bytes = 0; bool have_max_objects = false; bool have_max_size = false; bool have_max_write_ops = false; bool have_max_read_ops = false; bool have_max_write_bytes = false; bool have_max_read_bytes = false; int include_all = false; int allow_unordered = false; int sync_stats = false; int reset_stats = false; int bypass_gc = false; int warnings_only = false; int inconsistent_index = false; int verbose = false; int extra_info = false; uint64_t min_rewrite_size = 4 * 1024 * 1024; uint64_t max_rewrite_size = ULLONG_MAX; uint64_t min_rewrite_stripe_size = 0; BIIndexType bi_index_type = BIIndexType::Plain; std::optional<log_type> opt_log_type; string job_id; int num_shards = 0; bool num_shards_specified = false; std::optional<int> bucket_index_max_shards; int max_concurrent_ios = 32; uint64_t orphan_stale_secs = (24 * 3600); int detail = false; std::string val; std::ostringstream errs; string err; string source_zone_name; rgw_zone_id source_zone; /* zone id */ string tier_type; bool tier_type_specified = false; map<string, string, ltstr_nocase> tier_config_add; map<string, string, ltstr_nocase> tier_config_rm; boost::optional<string> index_pool; boost::optional<string> data_pool; boost::optional<string> data_extra_pool; rgw::BucketIndexType placement_index_type = rgw::BucketIndexType::Normal; bool index_type_specified = false; boost::optional<std::string> compression_type; string totp_serial; string totp_seed; string totp_seed_type = "hex"; vector<string> totp_pin; int totp_seconds = 0; int totp_window = 0; int trim_delay_ms = 0; string topic_name; string notification_id; string sub_name; string event_id; std::optional<uint64_t> gen; std::optional<std::string> str_script_ctx; std::optional<std::string> script_package; int allow_compilation = false; std::optional<string> opt_group_id; std::optional<string> opt_status; std::optional<string> opt_flow_type; std::optional<vector<string> > opt_zone_names; std::optional<vector<rgw_zone_id> > opt_zone_ids; std::optional<string> opt_flow_id; std::optional<string> opt_source_zone_name; std::optional<rgw_zone_id> opt_source_zone_id; std::optional<string> opt_dest_zone_name; std::optional<rgw_zone_id> opt_dest_zone_id; std::optional<vector<string> > opt_source_zone_names; std::optional<vector<rgw_zone_id> > opt_source_zone_ids; std::optional<vector<string> > opt_dest_zone_names; std::optional<vector<rgw_zone_id> > opt_dest_zone_ids; std::optional<string> opt_pipe_id; std::optional<rgw_bucket> opt_bucket; std::optional<string> opt_tenant; std::optional<string> opt_bucket_name; std::optional<string> opt_bucket_id; std::optional<rgw_bucket> opt_source_bucket; std::optional<string> opt_source_tenant; std::optional<string> opt_source_bucket_name; std::optional<string> opt_source_bucket_id; std::optional<rgw_bucket> opt_dest_bucket; std::optional<string> opt_dest_tenant; std::optional<string> opt_dest_bucket_name; std::optional<string> opt_dest_bucket_id; std::optional<string> opt_effective_zone_name; std::optional<rgw_zone_id> opt_effective_zone_id; std::optional<string> opt_prefix; std::optional<string> opt_prefix_rm; std::optional<int> opt_priority; std::optional<string> opt_mode; std::optional<rgw_user> opt_dest_owner; ceph::timespan opt_retry_delay_ms = std::chrono::milliseconds(2000); ceph::timespan opt_timeout_sec = std::chrono::seconds(60); std::optional<std::string> inject_error_at; std::optional<int> inject_error_code; std::optional<std::string> inject_abort_at; rgw::zone_features::set enable_features; rgw::zone_features::set disable_features; SimpleCmd cmd(all_cmds, cmd_aliases); bool raw_storage_op = false; std::optional<std::string> rgw_obj_fs; // radoslist field separator init_realm_param(cct.get(), realm_id, opt_realm_id, "rgw_realm_id"); init_realm_param(cct.get(), zonegroup_id, opt_zonegroup_id, "rgw_zonegroup_id"); init_realm_param(cct.get(), zone_id, opt_zone_id, "rgw_zone_id"); for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) { if (ceph_argparse_double_dash(args, i)) { break; } else if (ceph_argparse_witharg(args, i, &val, "-i", "--uid", (char*)NULL)) { user_id_arg.from_str(val); if (user_id_arg.empty()) { cerr << "no value for uid" << std::endl; exit(1); } } else if (ceph_argparse_witharg(args, i, &val, "--new-uid", (char*)NULL)) { new_user_id.from_str(val); } else if (ceph_argparse_witharg(args, i, &val, "--tenant", (char*)NULL)) { tenant = val; opt_tenant = val; } else if (ceph_argparse_witharg(args, i, &val, "--user_ns", (char*)NULL)) { user_ns = val; } else if (ceph_argparse_witharg(args, i, &val, "--access-key", (char*)NULL)) { access_key = val; } else if (ceph_argparse_witharg(args, i, &val, "--subuser", (char*)NULL)) { subuser = val; } else if (ceph_argparse_witharg(args, i, &val, "--secret", "--secret-key", (char*)NULL)) { secret_key = val; } else if (ceph_argparse_witharg(args, i, &val, "-e", "--email", (char*)NULL)) { user_email = val; } else if (ceph_argparse_witharg(args, i, &val, "-n", "--display-name", (char*)NULL)) { display_name = val; } else if (ceph_argparse_witharg(args, i, &val, "-b", "--bucket", (char*)NULL)) { bucket_name = val; opt_bucket_name = val; } else if (ceph_argparse_witharg(args, i, &val, "-p", "--pool", (char*)NULL)) { pool_name = val; pool = rgw_pool(pool_name); } else if (ceph_argparse_witharg(args, i, &val, "-o", "--object", (char*)NULL)) { object = val; } else if (ceph_argparse_witharg(args, i, &val, "--objects-file", (char*)NULL)) { objects_file = val; } else if (ceph_argparse_witharg(args, i, &val, "--object-version", (char*)NULL)) { object_version = val; } else if (ceph_argparse_witharg(args, i, &val, "--client-id", (char*)NULL)) { client_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--op-id", (char*)NULL)) { op_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--op-mask", (char*)NULL)) { op_mask_str = val; } else if (ceph_argparse_witharg(args, i, &val, "--key-type", (char*)NULL)) { key_type_str = val; if (key_type_str.compare("swift") == 0) { key_type = KEY_TYPE_SWIFT; } else if (key_type_str.compare("s3") == 0) { key_type = KEY_TYPE_S3; } else { cerr << "bad key type: " << key_type_str << std::endl; exit(1); } } else if (ceph_argparse_witharg(args, i, &val, "--job-id", (char*)NULL)) { job_id = val; } else if (ceph_argparse_binary_flag(args, i, &gen_access_key, NULL, "--gen-access-key", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &gen_secret_key, NULL, "--gen-secret", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &show_log_entries, NULL, "--show-log-entries", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &show_log_sum, NULL, "--show-log-sum", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &skip_zero_entries, NULL, "--skip-zero-entries", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &admin, NULL, "--admin", (char*)NULL)) { admin_specified = true; } else if (ceph_argparse_binary_flag(args, i, &system, NULL, "--system", (char*)NULL)) { system_specified = true; } else if (ceph_argparse_binary_flag(args, i, &verbose, NULL, "--verbose", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &staging, NULL, "--staging", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &commit, NULL, "--commit", (char*)NULL)) { // do nothing } else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-size", (char*)NULL)) { min_rewrite_size = (uint64_t)atoll(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--max-rewrite-size", (char*)NULL)) { max_rewrite_size = (uint64_t)atoll(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-stripe-size", (char*)NULL)) { min_rewrite_stripe_size = (uint64_t)atoll(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--max-buckets", (char*)NULL)) { max_buckets = (int)strict_strtol(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max buckets: " << err << std::endl; return EINVAL; } max_buckets_specified = true; } else if (ceph_argparse_witharg(args, i, &val, "--max-entries", (char*)NULL)) { max_entries = (int)strict_strtol(val.c_str(), 10, &err); max_entries_specified = true; if (!err.empty()) { cerr << "ERROR: failed to parse max entries: " << err << std::endl; return EINVAL; } } else if (ceph_argparse_witharg(args, i, &val, "--max-size", (char*)NULL)) { max_size = strict_iec_cast<long long>(val, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max size: " << err << std::endl; return EINVAL; } have_max_size = true; } else if (ceph_argparse_witharg(args, i, &val, "--max-objects", (char*)NULL)) { max_objects = (int64_t)strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max objects: " << err << std::endl; return EINVAL; } have_max_objects = true; } else if (ceph_argparse_witharg(args, i, &val, "--max-read-ops", (char*)NULL)) { max_read_ops = (int64_t)strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max read requests: " << err << std::endl; return EINVAL; } have_max_read_ops = true; } else if (ceph_argparse_witharg(args, i, &val, "--max-write-ops", (char*)NULL)) { max_write_ops = (int64_t)strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max write requests: " << err << std::endl; return EINVAL; } have_max_write_ops = true; } else if (ceph_argparse_witharg(args, i, &val, "--max-read-bytes", (char*)NULL)) { max_read_bytes = (int64_t)strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max read bytes: " << err << std::endl; return EINVAL; } have_max_read_bytes = true; } else if (ceph_argparse_witharg(args, i, &val, "--max-write-bytes", (char*)NULL)) { max_write_bytes = (int64_t)strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max write bytes: " << err << std::endl; return EINVAL; } have_max_write_bytes = true; } else if (ceph_argparse_witharg(args, i, &val, "--date", "--time", (char*)NULL)) { date = val; if (end_date.empty()) end_date = date; } else if (ceph_argparse_witharg(args, i, &val, "--start-date", "--start-time", (char*)NULL)) { start_date = val; } else if (ceph_argparse_witharg(args, i, &val, "--end-date", "--end-time", (char*)NULL)) { end_date = val; } else if (ceph_argparse_witharg(args, i, &val, "--num-shards", (char*)NULL)) { num_shards = (int)strict_strtol(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse num shards: " << err << std::endl; return EINVAL; } num_shards_specified = true; } else if (ceph_argparse_witharg(args, i, &val, "--bucket-index-max-shards", (char*)NULL)) { bucket_index_max_shards = (int)strict_strtol(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse bucket-index-max-shards: " << err << std::endl; return EINVAL; } } else if (ceph_argparse_witharg(args, i, &val, "--max-concurrent-ios", (char*)NULL)) { max_concurrent_ios = (int)strict_strtol(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse max concurrent ios: " << err << std::endl; return EINVAL; } } else if (ceph_argparse_witharg(args, i, &val, "--orphan-stale-secs", (char*)NULL)) { orphan_stale_secs = (uint64_t)strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse orphan stale secs: " << err << std::endl; return EINVAL; } } else if (ceph_argparse_witharg(args, i, &val, "--shard-id", (char*)NULL)) { shard_id = (int)strict_strtol(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse shard id: " << err << std::endl; return EINVAL; } specified_shard_id = true; } else if (ceph_argparse_witharg(args, i, &val, "--gen", (char*)NULL)) { gen = strict_strtoll(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse gen id: " << err << std::endl; return EINVAL; } } else if (ceph_argparse_witharg(args, i, &val, "--access", (char*)NULL)) { access = val; perm_mask = rgw_str_to_perm(access.c_str()); set_perm = true; } else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key", (char*)NULL)) { temp_url_keys[0] = val; set_temp_url_key = true; } else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key2", "--temp-url-key-2", (char*)NULL)) { temp_url_keys[1] = val; set_temp_url_key = true; } else if (ceph_argparse_witharg(args, i, &val, "--bucket-id", (char*)NULL)) { bucket_id = val; opt_bucket_id = val; if (bucket_id.empty()) { cerr << "no value for bucket-id" << std::endl; exit(1); } } else if (ceph_argparse_witharg(args, i, &val, "--bucket-new-name", (char*)NULL)) { new_bucket_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--format", (char*)NULL)) { format = val; } else if (ceph_argparse_witharg(args, i, &val, "--categories", (char*)NULL)) { string cat_str = val; list<string> cat_list; list<string>::iterator iter; get_str_list(cat_str, cat_list); for (iter = cat_list.begin(); iter != cat_list.end(); ++iter) { categories[*iter] = true; } } else if (ceph_argparse_binary_flag(args, i, &delete_child_objects, NULL, "--purge-objects", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &pretty_format, NULL, "--pretty-format", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &purge_data, NULL, "--purge-data", (char*)NULL)) { delete_child_objects = purge_data; } else if (ceph_argparse_binary_flag(args, i, &purge_keys, NULL, "--purge-keys", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &yes_i_really_mean_it, NULL, "--yes-i-really-mean-it", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &fix, NULL, "--fix", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &remove_bad, NULL, "--remove-bad", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &check_head_obj_locator, NULL, "--check-head-obj-locator", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &check_objects, NULL, "--check-objects", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &sync_stats, NULL, "--sync-stats", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &reset_stats, NULL, "--reset-stats", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &include_all, NULL, "--include-all", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &allow_unordered, NULL, "--allow-unordered", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &extra_info, NULL, "--extra-info", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &bypass_gc, NULL, "--bypass-gc", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &warnings_only, NULL, "--warnings-only", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &inconsistent_index, NULL, "--inconsistent-index", (char*)NULL)) { // do nothing } else if (ceph_argparse_binary_flag(args, i, &placement_inline_data, NULL, "--placement-inline-data", (char*)NULL)) { placement_inline_data_specified = true; // do nothing } else if (ceph_argparse_witharg(args, i, &val, "--caps", (char*)NULL)) { caps = val; } else if (ceph_argparse_witharg(args, i, &val, "--infile", (char*)NULL)) { infile = val; } else if (ceph_argparse_witharg(args, i, &val, "--metadata-key", (char*)NULL)) { metadata_key = val; } else if (ceph_argparse_witharg(args, i, &val, "--marker", (char*)NULL)) { marker = val; } else if (ceph_argparse_witharg(args, i, &val, "--start-marker", (char*)NULL)) { start_marker = val; } else if (ceph_argparse_witharg(args, i, &val, "--end-marker", (char*)NULL)) { end_marker = val; } else if (ceph_argparse_witharg(args, i, &val, "--quota-scope", (char*)NULL)) { quota_scope = val; } else if (ceph_argparse_witharg(args, i, &val, "--ratelimit-scope", (char*)NULL)) { ratelimit_scope = val; } else if (ceph_argparse_witharg(args, i, &val, "--index-type", (char*)NULL)) { string index_type_str = val; bi_index_type = get_bi_index_type(index_type_str); if (bi_index_type == BIIndexType::Invalid) { cerr << "ERROR: invalid bucket index entry type" << std::endl; return EINVAL; } } else if (ceph_argparse_witharg(args, i, &val, "--log-type", (char*)NULL)) { string log_type_str = val; auto l = get_log_type(log_type_str); if (l == static_cast<log_type>(0xff)) { cerr << "ERROR: invalid log type" << std::endl; return EINVAL; } opt_log_type = l; } else if (ceph_argparse_binary_flag(args, i, &is_master_int, NULL, "--master", (char*)NULL)) { is_master = (bool)is_master_int; is_master_set = true; } else if (ceph_argparse_binary_flag(args, i, &set_default, NULL, "--default", (char*)NULL)) { /* do nothing */ } else if (ceph_argparse_witharg(args, i, &val, "--redirect-zone", (char*)NULL)) { redirect_zone = val; redirect_zone_set = true; } else if (ceph_argparse_binary_flag(args, i, &read_only_int, NULL, "--read-only", (char*)NULL)) { read_only = (bool)read_only_int; is_read_only_set = true; } else if (ceph_argparse_witharg(args, i, &val, "--master-zone", (char*)NULL)) { master_zone = val; } else if (ceph_argparse_witharg(args, i, &val, "--period", (char*)NULL)) { period_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--epoch", (char*)NULL)) { period_epoch = val; } else if (ceph_argparse_witharg(args, i, &val, "--remote", (char*)NULL)) { remote = val; } else if (ceph_argparse_witharg(args, i, &val, "--url", (char*)NULL)) { url = val; } else if (ceph_argparse_witharg(args, i, &val, "--region", (char*)NULL)) { opt_region = val; } else if (ceph_argparse_witharg(args, i, &val, "--realm-id", (char*)NULL)) { realm_id = val; opt_realm_id = val; g_conf().set_val("rgw_realm_id", val); } else if (ceph_argparse_witharg(args, i, &val, "--realm-new-name", (char*)NULL)) { realm_new_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-id", (char*)NULL)) { zonegroup_id = val; opt_zonegroup_id = val; g_conf().set_val("rgw_zonegroup_id", val); } else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-new-name", (char*)NULL)) { zonegroup_new_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--placement-id", (char*)NULL)) { placement_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--storage-class", (char*)NULL)) { opt_storage_class = val; } else if (ceph_argparse_witharg(args, i, &val, "--tags", (char*)NULL)) { get_str_list(val, ",", tags); } else if (ceph_argparse_witharg(args, i, &val, "--tags-add", (char*)NULL)) { get_str_list(val, ",", tags_add); } else if (ceph_argparse_witharg(args, i, &val, "--tags-rm", (char*)NULL)) { get_str_list(val, ",", tags_rm); } else if (ceph_argparse_witharg(args, i, &val, "--api-name", (char*)NULL)) { api_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--zone-id", (char*)NULL)) { zone_id = val; opt_zone_id = val; g_conf().set_val("rgw_zone_id", val); } else if (ceph_argparse_witharg(args, i, &val, "--zone-new-name", (char*)NULL)) { zone_new_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--endpoints", (char*)NULL)) { get_str_list(val, endpoints); } else if (ceph_argparse_witharg(args, i, &val, "--sync-from", (char*)NULL)) { get_str_list(val, sync_from); } else if (ceph_argparse_witharg(args, i, &val, "--sync-from-rm", (char*)NULL)) { get_str_list(val, sync_from_rm); } else if (ceph_argparse_binary_flag(args, i, &tmp_int, NULL, "--sync-from-all", (char*)NULL)) { sync_from_all = (bool)tmp_int; sync_from_all_specified = true; } else if (ceph_argparse_witharg(args, i, &val, "--source-zone", (char*)NULL)) { source_zone_name = val; opt_source_zone_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--source-zone-id", (char*)NULL)) { opt_source_zone_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--dest-zone", (char*)NULL)) { opt_dest_zone_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--dest-zone-id", (char*)NULL)) { opt_dest_zone_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--tier-type", (char*)NULL)) { tier_type = val; tier_type_specified = true; } else if (ceph_argparse_witharg(args, i, &val, "--tier-config", (char*)NULL)) { parse_tier_config_param(val, tier_config_add); } else if (ceph_argparse_witharg(args, i, &val, "--tier-config-rm", (char*)NULL)) { parse_tier_config_param(val, tier_config_rm); } else if (ceph_argparse_witharg(args, i, &val, "--index-pool", (char*)NULL)) { index_pool = val; } else if (ceph_argparse_witharg(args, i, &val, "--data-pool", (char*)NULL)) { data_pool = val; } else if (ceph_argparse_witharg(args, i, &val, "--data-extra-pool", (char*)NULL)) { data_extra_pool = val; } else if (ceph_argparse_witharg(args, i, &val, "--placement-index-type", (char*)NULL)) { if (val == "normal") { placement_index_type = rgw::BucketIndexType::Normal; } else if (val == "indexless") { placement_index_type = rgw::BucketIndexType::Indexless; } else { placement_index_type = (rgw::BucketIndexType)strict_strtol(val.c_str(), 10, &err); if (!err.empty()) { cerr << "ERROR: failed to parse index type index: " << err << std::endl; return EINVAL; } } index_type_specified = true; } else if (ceph_argparse_witharg(args, i, &val, "--compression", (char*)NULL)) { compression_type = val; } else if (ceph_argparse_witharg(args, i, &val, "--role-name", (char*)NULL)) { role_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--path", (char*)NULL)) { path = val; } else if (ceph_argparse_witharg(args, i, &val, "--assume-role-policy-doc", (char*)NULL)) { assume_role_doc = val; } else if (ceph_argparse_witharg(args, i, &val, "--policy-name", (char*)NULL)) { policy_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--policy-doc", (char*)NULL)) { perm_policy_doc = val; } else if (ceph_argparse_witharg(args, i, &val, "--path-prefix", (char*)NULL)) { path_prefix = val; } else if (ceph_argparse_witharg(args, i, &val, "--max-session-duration", (char*)NULL)) { max_session_duration = val; } else if (ceph_argparse_witharg(args, i, &val, "--totp-serial", (char*)NULL)) { totp_serial = val; } else if (ceph_argparse_witharg(args, i, &val, "--totp-pin", (char*)NULL)) { totp_pin.push_back(val); } else if (ceph_argparse_witharg(args, i, &val, "--totp-seed", (char*)NULL)) { totp_seed = val; } else if (ceph_argparse_witharg(args, i, &val, "--totp-seed-type", (char*)NULL)) { totp_seed_type = val; } else if (ceph_argparse_witharg(args, i, &val, "--totp-seconds", (char*)NULL)) { totp_seconds = atoi(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--totp-window", (char*)NULL)) { totp_window = atoi(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--trim-delay-ms", (char*)NULL)) { trim_delay_ms = atoi(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--topic", (char*)NULL)) { topic_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--notification-id", (char*)NULL)) { notification_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--subscription", (char*)NULL)) { sub_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--event-id", (char*)NULL)) { event_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--group-id", (char*)NULL)) { opt_group_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--status", (char*)NULL)) { opt_status = val; } else if (ceph_argparse_witharg(args, i, &val, "--flow-type", (char*)NULL)) { opt_flow_type = val; } else if (ceph_argparse_witharg(args, i, &val, "--zones", "--zone-names", (char*)NULL)) { vector<string> v; get_str_vec(val, v); opt_zone_names = std::move(v); } else if (ceph_argparse_witharg(args, i, &val, "--zone-ids", (char*)NULL)) { opt_zone_ids = zone_ids_from_str(val); } else if (ceph_argparse_witharg(args, i, &val, "--source-zones", "--source-zone-names", (char*)NULL)) { vector<string> v; get_str_vec(val, v); opt_source_zone_names = std::move(v); } else if (ceph_argparse_witharg(args, i, &val, "--source-zone-ids", (char*)NULL)) { opt_source_zone_ids = zone_ids_from_str(val); } else if (ceph_argparse_witharg(args, i, &val, "--dest-zones", "--dest-zone-names", (char*)NULL)) { vector<string> v; get_str_vec(val, v); opt_dest_zone_names = std::move(v); } else if (ceph_argparse_witharg(args, i, &val, "--dest-zone-ids", (char*)NULL)) { opt_dest_zone_ids = zone_ids_from_str(val); } else if (ceph_argparse_witharg(args, i, &val, "--flow-id", (char*)NULL)) { opt_flow_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--pipe-id", (char*)NULL)) { opt_pipe_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--source-tenant", (char*)NULL)) { opt_source_tenant = val; } else if (ceph_argparse_witharg(args, i, &val, "--source-bucket", (char*)NULL)) { opt_source_bucket_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--source-bucket-id", (char*)NULL)) { opt_source_bucket_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--dest-tenant", (char*)NULL)) { opt_dest_tenant = val; } else if (ceph_argparse_witharg(args, i, &val, "--dest-bucket", (char*)NULL)) { opt_dest_bucket_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--dest-bucket-id", (char*)NULL)) { opt_dest_bucket_id = val; } else if (ceph_argparse_witharg(args, i, &val, "--effective-zone-name", "--effective-zone", (char*)NULL)) { opt_effective_zone_name = val; } else if (ceph_argparse_witharg(args, i, &val, "--effective-zone-id", (char*)NULL)) { opt_effective_zone_id = rgw_zone_id(val); } else if (ceph_argparse_witharg(args, i, &val, "--prefix", (char*)NULL)) { opt_prefix = val; } else if (ceph_argparse_witharg(args, i, &val, "--prefix-rm", (char*)NULL)) { opt_prefix_rm = val; } else if (ceph_argparse_witharg(args, i, &val, "--priority", (char*)NULL)) { opt_priority = atoi(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--mode", (char*)NULL)) { opt_mode = val; } else if (ceph_argparse_witharg(args, i, &val, "--dest-owner", (char*)NULL)) { opt_dest_owner.emplace(val); opt_dest_owner = val; } else if (ceph_argparse_witharg(args, i, &val, "--retry-delay-ms", (char*)NULL)) { opt_retry_delay_ms = std::chrono::milliseconds(atoi(val.c_str())); } else if (ceph_argparse_witharg(args, i, &val, "--timeout-sec", (char*)NULL)) { opt_timeout_sec = std::chrono::seconds(atoi(val.c_str())); } else if (ceph_argparse_witharg(args, i, &val, "--inject-error-at", (char*)NULL)) { inject_error_at = val; } else if (ceph_argparse_witharg(args, i, &val, "--inject-error-code", (char*)NULL)) { inject_error_code = atoi(val.c_str()); } else if (ceph_argparse_witharg(args, i, &val, "--inject-abort-at", (char*)NULL)) { inject_abort_at = val; } else if (ceph_argparse_binary_flag(args, i, &detail, NULL, "--detail", (char*)NULL)) { // do nothing } else if (ceph_argparse_witharg(args, i, &val, "--context", (char*)NULL)) { str_script_ctx = val; } else if (ceph_argparse_witharg(args, i, &val, "--package", (char*)NULL)) { script_package = val; } else if (ceph_argparse_binary_flag(args, i, &allow_compilation, NULL, "--allow-compilation", (char*)NULL)) { // do nothing } else if (ceph_argparse_witharg(args, i, &val, "--rgw-obj-fs", (char*)NULL)) { rgw_obj_fs = val; } else if (ceph_argparse_witharg(args, i, &val, "--enable-feature", (char*)NULL)) { if (!rgw::zone_features::supports(val)) { std::cerr << "ERROR: Cannot enable unrecognized zone feature \"" << val << "\"" << std::endl; return EINVAL; } enable_features.insert(val); } else if (ceph_argparse_witharg(args, i, &val, "--disable-feature", (char*)NULL)) { disable_features.insert(val); } else if (strncmp(*i, "-", 1) == 0) { cerr << "ERROR: invalid flag " << *i << std::endl; return EINVAL; } else { ++i; } } /* common_init_finish needs to be called after g_conf().set_val() */ common_init_finish(g_ceph_context); std::unique_ptr<rgw::sal::ConfigStore> cfgstore; if (args.empty()) { usage(); exit(1); } else { std::vector<string> extra_args; std::vector<string> expected; std::any _opt_cmd; if (!cmd.find_command(args, &_opt_cmd, &extra_args, &err, &expected)) { if (!expected.empty()) { cerr << err << std::endl; cerr << "Expected one of the following:" << std::endl; for (auto& exp : expected) { if (exp == "*" || exp == "[*]") { continue; } cerr << " " << exp << std::endl; } } else { cerr << "Command not found:"; for (auto& arg : args) { cerr << " " << arg; } cerr << std::endl; } exit(1); } opt_cmd = std::any_cast<OPT>(_opt_cmd); /* some commands may have an optional extra param */ if (!extra_args.empty()) { switch (opt_cmd) { case OPT::METADATA_GET: case OPT::METADATA_PUT: case OPT::METADATA_RM: case OPT::METADATA_LIST: metadata_key = extra_args[0]; break; default: break; } } // not a raw op if 'period update' needs to commit to master bool raw_period_update = opt_cmd == OPT::PERIOD_UPDATE && !commit; // not a raw op if 'period pull' needs to read zone/period configuration bool raw_period_pull = opt_cmd == OPT::PERIOD_PULL && !url.empty(); std::set<OPT> raw_storage_ops_list = {OPT::ZONEGROUP_ADD, OPT::ZONEGROUP_CREATE, OPT::ZONEGROUP_DELETE, OPT::ZONEGROUP_GET, OPT::ZONEGROUP_LIST, OPT::ZONEGROUP_SET, OPT::ZONEGROUP_DEFAULT, OPT::ZONEGROUP_RENAME, OPT::ZONEGROUP_MODIFY, OPT::ZONEGROUP_REMOVE, OPT::ZONEGROUP_PLACEMENT_ADD, OPT::ZONEGROUP_PLACEMENT_RM, OPT::ZONEGROUP_PLACEMENT_MODIFY, OPT::ZONEGROUP_PLACEMENT_LIST, OPT::ZONEGROUP_PLACEMENT_GET, OPT::ZONEGROUP_PLACEMENT_DEFAULT, OPT::ZONE_CREATE, OPT::ZONE_DELETE, OPT::ZONE_GET, OPT::ZONE_SET, OPT::ZONE_RENAME, OPT::ZONE_LIST, OPT::ZONE_MODIFY, OPT::ZONE_DEFAULT, OPT::ZONE_PLACEMENT_ADD, OPT::ZONE_PLACEMENT_RM, OPT::ZONE_PLACEMENT_MODIFY, OPT::ZONE_PLACEMENT_LIST, OPT::ZONE_PLACEMENT_GET, OPT::REALM_CREATE, OPT::PERIOD_DELETE, OPT::PERIOD_GET, OPT::PERIOD_GET_CURRENT, OPT::PERIOD_LIST, OPT::GLOBAL_QUOTA_GET, OPT::GLOBAL_QUOTA_SET, OPT::GLOBAL_QUOTA_ENABLE, OPT::GLOBAL_QUOTA_DISABLE, OPT::GLOBAL_RATELIMIT_GET, OPT::GLOBAL_RATELIMIT_SET, OPT::GLOBAL_RATELIMIT_ENABLE, OPT::GLOBAL_RATELIMIT_DISABLE, OPT::REALM_DELETE, OPT::REALM_GET, OPT::REALM_LIST, OPT::REALM_LIST_PERIODS, OPT::REALM_GET_DEFAULT, OPT::REALM_RENAME, OPT::REALM_SET, OPT::REALM_DEFAULT, OPT::REALM_PULL}; std::set<OPT> readonly_ops_list = { OPT::USER_INFO, OPT::USER_STATS, OPT::BUCKETS_LIST, OPT::BUCKET_LIMIT_CHECK, OPT::BUCKET_LAYOUT, OPT::BUCKET_STATS, OPT::BUCKET_SYNC_CHECKPOINT, OPT::BUCKET_SYNC_INFO, OPT::BUCKET_SYNC_STATUS, OPT::BUCKET_SYNC_MARKERS, OPT::BUCKET_SHARD_OBJECTS, OPT::BUCKET_OBJECT_SHARD, OPT::LOG_LIST, OPT::LOG_SHOW, OPT::USAGE_SHOW, OPT::OBJECT_STAT, OPT::BI_GET, OPT::BI_LIST, OPT::OLH_GET, OPT::OLH_READLOG, OPT::GC_LIST, OPT::LC_LIST, OPT::ORPHANS_LIST_JOBS, OPT::ZONEGROUP_GET, OPT::ZONEGROUP_LIST, OPT::ZONEGROUP_PLACEMENT_LIST, OPT::ZONEGROUP_PLACEMENT_GET, OPT::ZONE_GET, OPT::ZONE_LIST, OPT::ZONE_PLACEMENT_LIST, OPT::ZONE_PLACEMENT_GET, OPT::METADATA_GET, OPT::METADATA_LIST, OPT::METADATA_SYNC_STATUS, OPT::MDLOG_LIST, OPT::MDLOG_STATUS, OPT::SYNC_ERROR_LIST, OPT::SYNC_GROUP_GET, OPT::SYNC_POLICY_GET, OPT::BILOG_LIST, OPT::BILOG_STATUS, OPT::DATA_SYNC_STATUS, OPT::DATALOG_LIST, OPT::DATALOG_STATUS, OPT::REALM_GET, OPT::REALM_GET_DEFAULT, OPT::REALM_LIST, OPT::REALM_LIST_PERIODS, OPT::PERIOD_GET, OPT::PERIOD_GET_CURRENT, OPT::PERIOD_LIST, OPT::GLOBAL_QUOTA_GET, OPT::GLOBAL_RATELIMIT_GET, OPT::SYNC_INFO, OPT::SYNC_STATUS, OPT::ROLE_GET, OPT::ROLE_LIST, OPT::ROLE_POLICY_LIST, OPT::ROLE_POLICY_GET, OPT::RESHARD_LIST, OPT::RESHARD_STATUS, OPT::PUBSUB_TOPIC_LIST, OPT::PUBSUB_NOTIFICATION_LIST, OPT::PUBSUB_TOPIC_GET, OPT::PUBSUB_NOTIFICATION_GET, OPT::PUBSUB_TOPIC_STATS , OPT::SCRIPT_GET, }; std::set<OPT> gc_ops_list = { OPT::GC_LIST, OPT::GC_PROCESS, OPT::OBJECT_RM, OPT::BUCKET_RM, // --purge-objects OPT::USER_RM, // --purge-data OPT::OBJECTS_EXPIRE, OPT::OBJECTS_EXPIRE_STALE_RM, OPT::LC_PROCESS, OPT::BUCKET_SYNC_RUN, OPT::DATA_SYNC_RUN, OPT::BUCKET_REWRITE, OPT::OBJECT_REWRITE }; raw_storage_op = (raw_storage_ops_list.find(opt_cmd) != raw_storage_ops_list.end() || raw_period_update || raw_period_pull); bool need_cache = readonly_ops_list.find(opt_cmd) == readonly_ops_list.end(); bool need_gc = (gc_ops_list.find(opt_cmd) != gc_ops_list.end()) && !bypass_gc; DriverManager::Config cfg = DriverManager::get_config(true, g_ceph_context); auto config_store_type = g_conf().get_val<std::string>("rgw_config_store"); cfgstore = DriverManager::create_config_store(dpp(), config_store_type); if (!cfgstore) { cerr << "couldn't init config storage provider" << std::endl; return EIO; } if (raw_storage_op) { driver = DriverManager::get_raw_storage(dpp(), g_ceph_context, cfg); } else { driver = DriverManager::get_storage(dpp(), g_ceph_context, cfg, false, false, false, false, false, false, null_yield, need_cache && g_conf()->rgw_cache_enabled, need_gc); } if (!driver) { cerr << "couldn't init storage provider" << std::endl; return EIO; } /* Needs to be after the driver is initialized. Note, user could be empty here. */ user = driver->get_user(user_id_arg); init_optional_bucket(opt_bucket, opt_tenant, opt_bucket_name, opt_bucket_id); init_optional_bucket(opt_source_bucket, opt_source_tenant, opt_source_bucket_name, opt_source_bucket_id); init_optional_bucket(opt_dest_bucket, opt_dest_tenant, opt_dest_bucket_name, opt_dest_bucket_id); if (tenant.empty()) { tenant = user->get_tenant(); } else { if (rgw::sal::User::empty(user) && opt_cmd != OPT::ROLE_CREATE && opt_cmd != OPT::ROLE_DELETE && opt_cmd != OPT::ROLE_GET && opt_cmd != OPT::ROLE_TRUST_POLICY_MODIFY && opt_cmd != OPT::ROLE_LIST && opt_cmd != OPT::ROLE_POLICY_PUT && opt_cmd != OPT::ROLE_POLICY_LIST && opt_cmd != OPT::ROLE_POLICY_GET && opt_cmd != OPT::ROLE_POLICY_DELETE && opt_cmd != OPT::ROLE_UPDATE && opt_cmd != OPT::RESHARD_ADD && opt_cmd != OPT::RESHARD_CANCEL && opt_cmd != OPT::RESHARD_STATUS && opt_cmd != OPT::PUBSUB_TOPIC_LIST && opt_cmd != OPT::PUBSUB_NOTIFICATION_LIST && opt_cmd != OPT::PUBSUB_TOPIC_GET && opt_cmd != OPT::PUBSUB_NOTIFICATION_GET && opt_cmd != OPT::PUBSUB_TOPIC_RM && opt_cmd != OPT::PUBSUB_NOTIFICATION_RM && opt_cmd != OPT::PUBSUB_TOPIC_STATS ) { cerr << "ERROR: --tenant is set, but there's no user ID" << std::endl; return EINVAL; } user->set_tenant(tenant); } if (user_ns.empty()) { user_ns = user->get_id().ns; } else { user->set_ns(user_ns); } if (!new_user_id.empty() && !tenant.empty()) { new_user_id.tenant = tenant; } /* check key parameter conflict */ if ((!access_key.empty()) && gen_access_key) { cerr << "ERROR: key parameter conflict, --access-key & --gen-access-key" << std::endl; return EINVAL; } if ((!secret_key.empty()) && gen_secret_key) { cerr << "ERROR: key parameter conflict, --secret & --gen-secret" << std::endl; return EINVAL; } } // default to pretty json if (format.empty()) { format = "json"; pretty_format = true; } if (format == "xml") formatter = make_unique<XMLFormatter>(pretty_format); else if (format == "json") formatter = make_unique<JSONFormatter>(pretty_format); else { cerr << "unrecognized format: " << format << std::endl; exit(1); } zone_formatter = std::make_unique<JSONFormatter_PrettyZone>(pretty_format); realm_name = g_conf()->rgw_realm; zone_name = g_conf()->rgw_zone; zonegroup_name = g_conf()->rgw_zonegroup; if (!realm_name.empty()) { opt_realm_name = realm_name; } if (!zone_name.empty()) { opt_zone_name = zone_name; } if (!zonegroup_name.empty()) { opt_zonegroup_name = zonegroup_name; } RGWStreamFlusher stream_flusher(formatter.get(), cout); RGWUserAdminOpState user_op(driver); if (!user_email.empty()) { user_op.user_email_specified=true; } if (!source_zone_name.empty()) { std::unique_ptr<rgw::sal::Zone> zone; if (driver->get_zone()->get_zonegroup().get_zone_by_name(source_zone_name, &zone) < 0) { cerr << "WARNING: cannot find source zone id for name=" << source_zone_name << std::endl; source_zone = source_zone_name; } else { source_zone.id = zone->get_id(); } } rgw_http_client_init(g_ceph_context); struct rgw_curl_setup { rgw_curl_setup() { rgw::curl::setup_curl(boost::none); } ~rgw_curl_setup() { rgw::curl::cleanup_curl(); } } curl_cleanup; oath_init(); StoreDestructor store_destructor(driver); if (raw_storage_op) { switch (opt_cmd) { case OPT::PERIOD_DELETE: { if (period_id.empty()) { cerr << "missing period id" << std::endl; return EINVAL; } int ret = cfgstore->delete_period(dpp(), null_yield, period_id); if (ret < 0) { cerr << "ERROR: couldn't delete period: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::PERIOD_GET: { std::optional<epoch_t> epoch; if (!period_epoch.empty()) { epoch = atoi(period_epoch.c_str()); } if (staging) { RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 ) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } realm_id = realm.get_id(); realm_name = realm.get_name(); period_id = RGWPeriod::get_staging_id(realm_id); epoch = 1; } if (period_id.empty()) { // use realm's current period RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 ) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } period_id = realm.current_period; } RGWPeriod period; int ret = cfgstore->read_period(dpp(), null_yield, period_id, epoch, period); if (ret < 0) { cerr << "failed to load period: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("period", period, formatter.get()); formatter->flush(cout); } break; case OPT::PERIOD_GET_CURRENT: { RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0) { std::cerr << "failed to load realm: " << cpp_strerror(ret) << std::endl; return -ret; } formatter->open_object_section("period_get_current"); encode_json("current_period", realm.current_period, formatter.get()); formatter->close_section(); formatter->flush(cout); } break; case OPT::PERIOD_LIST: { Formatter::ObjectSection periods_list{*formatter, "periods_list"}; Formatter::ArraySection periods{*formatter, "periods"}; rgw::sal::ListResult<std::string> listing; std::array<std::string, 1000> period_ids; // list in pages of 1000 do { int ret = cfgstore->list_period_ids(dpp(), null_yield, listing.next, period_ids, listing); if (ret < 0) { std::cerr << "failed to list periods: " << cpp_strerror(-ret) << std::endl; return -ret; } for (const auto& id : listing.entries) { encode_json("id", id, formatter.get()); } } while (!listing.next.empty()); } // close sections periods and periods_list formatter->flush(cout); break; case OPT::PERIOD_UPDATE: { int ret = update_period(cfgstore.get(), realm_id, realm_name, period_epoch, commit, remote, url, opt_region, access_key, secret_key, formatter.get(), yes_i_really_mean_it); if (ret < 0) { return -ret; } } break; case OPT::PERIOD_PULL: { boost::optional<RGWRESTConn> conn; RGWRESTConn *remote_conn = nullptr; if (url.empty()) { // load current period for endpoints RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 ) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } period_id = realm.current_period; RGWPeriod current_period; ret = cfgstore->read_period(dpp(), null_yield, period_id, std::nullopt, current_period); if (ret < 0) { cerr << "failed to load current period: " << cpp_strerror(-ret) << std::endl; return -ret; } if (remote.empty()) { // use realm master zone as remote remote = current_period.get_master_zone().id; } conn = get_remote_conn(static_cast<rgw::sal::RadosStore*>(driver), current_period.get_map(), remote); if (!conn) { cerr << "failed to find a zone or zonegroup for remote " << remote << std::endl; return -ENOENT; } remote_conn = &*conn; } RGWPeriod period; int ret = do_period_pull(cfgstore.get(), remote_conn, url, opt_region, access_key, secret_key, realm_id, realm_name, period_id, period_epoch, &period); if (ret < 0) { cerr << "period pull failed: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("period", period, formatter.get()); formatter->flush(cout); } break; case OPT::GLOBAL_RATELIMIT_GET: case OPT::GLOBAL_RATELIMIT_SET: case OPT::GLOBAL_RATELIMIT_ENABLE: case OPT::GLOBAL_RATELIMIT_DISABLE: { if (realm_id.empty()) { if (!realm_name.empty()) { // look up realm_id for the given realm_name int ret = cfgstore->read_realm_id(dpp(), null_yield, realm_name, realm_id); if (ret < 0) { cerr << "ERROR: failed to read realm for " << realm_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } } else { // use default realm_id when none is given int ret = cfgstore->read_default_realm_id(dpp(), null_yield, realm_id); if (ret < 0 && ret != -ENOENT) { // on ENOENT, use empty realm_id cerr << "ERROR: failed to read default realm: " << cpp_strerror(-ret) << std::endl; return -ret; } } } RGWPeriodConfig period_config; int ret = cfgstore->read_period_config(dpp(), null_yield, realm_id, period_config); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: failed to read period config: " << cpp_strerror(-ret) << std::endl; return -ret; } bool ratelimit_configured = true; formatter->open_object_section("period_config"); if (ratelimit_scope == "bucket") { ratelimit_configured = set_ratelimit_info(period_config.bucket_ratelimit, opt_cmd, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); encode_json("bucket_ratelimit", period_config.bucket_ratelimit, formatter.get()); } else if (ratelimit_scope == "user") { ratelimit_configured = set_ratelimit_info(period_config.user_ratelimit, opt_cmd, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); encode_json("user_ratelimit", period_config.user_ratelimit, formatter.get()); } else if (ratelimit_scope == "anonymous") { ratelimit_configured = set_ratelimit_info(period_config.anon_ratelimit, opt_cmd, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); encode_json("anonymous_ratelimit", period_config.anon_ratelimit, formatter.get()); } else if (ratelimit_scope.empty() && opt_cmd == OPT::GLOBAL_RATELIMIT_GET) { // if no scope is given for GET, print both encode_json("bucket_ratelimit", period_config.bucket_ratelimit, formatter.get()); encode_json("user_ratelimit", period_config.user_ratelimit, formatter.get()); encode_json("anonymous_ratelimit", period_config.anon_ratelimit, formatter.get()); } else { cerr << "ERROR: invalid rate limit scope specification. Please specify " "either --ratelimit-scope=bucket, or --ratelimit-scope=user or --ratelimit-scope=anonymous" << std::endl; return EINVAL; } if (!ratelimit_configured) { cerr << "ERROR: no rate limit values have been specified" << std::endl; return EINVAL; } formatter->close_section(); if (opt_cmd != OPT::GLOBAL_RATELIMIT_GET) { // write the modified period config constexpr bool exclusive = false; ret = cfgstore->write_period_config(dpp(), null_yield, exclusive, realm_id, period_config); if (ret < 0) { cerr << "ERROR: failed to write period config: " << cpp_strerror(-ret) << std::endl; return -ret; } if (!realm_id.empty()) { cout << "Global ratelimit changes saved. Use 'period update' to apply " "them to the staging period, and 'period commit' to commit the " "new period." << std::endl; } else { cout << "Global ratelimit changes saved. They will take effect as " "the gateways are restarted." << std::endl; } } formatter->flush(cout); } break; case OPT::GLOBAL_QUOTA_GET: case OPT::GLOBAL_QUOTA_SET: case OPT::GLOBAL_QUOTA_ENABLE: case OPT::GLOBAL_QUOTA_DISABLE: { if (realm_id.empty()) { if (!realm_name.empty()) { // look up realm_id for the given realm_name int ret = cfgstore->read_realm_id(dpp(), null_yield, realm_name, realm_id); if (ret < 0) { cerr << "ERROR: failed to read realm for " << realm_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } } else { // use default realm_id when none is given int ret = cfgstore->read_default_realm_id(dpp(), null_yield, realm_id); if (ret < 0 && ret != -ENOENT) { // on ENOENT, use empty realm_id cerr << "ERROR: failed to read default realm: " << cpp_strerror(-ret) << std::endl; return -ret; } } } RGWPeriodConfig period_config; int ret = cfgstore->read_period_config(dpp(), null_yield, realm_id, period_config); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: failed to read period config: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->open_object_section("period_config"); if (quota_scope == "bucket") { set_quota_info(period_config.quota.bucket_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects); encode_json("bucket quota", period_config.quota.bucket_quota, formatter.get()); } else if (quota_scope == "user") { set_quota_info(period_config.quota.user_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects); encode_json("user quota", period_config.quota.user_quota, formatter.get()); } else if (quota_scope.empty() && opt_cmd == OPT::GLOBAL_QUOTA_GET) { // if no scope is given for GET, print both encode_json("bucket quota", period_config.quota.bucket_quota, formatter.get()); encode_json("user quota", period_config.quota.user_quota, formatter.get()); } else { cerr << "ERROR: invalid quota scope specification. Please specify " "either --quota-scope=bucket, or --quota-scope=user" << std::endl; return EINVAL; } formatter->close_section(); if (opt_cmd != OPT::GLOBAL_QUOTA_GET) { // write the modified period config constexpr bool exclusive = false; ret = cfgstore->write_period_config(dpp(), null_yield, exclusive, realm_id, period_config); if (ret < 0) { cerr << "ERROR: failed to write period config: " << cpp_strerror(-ret) << std::endl; return -ret; } if (!realm_id.empty()) { cout << "Global quota changes saved. Use 'period update' to apply " "them to the staging period, and 'period commit' to commit the " "new period." << std::endl; } else { cout << "Global quota changes saved. They will take effect as " "the gateways are restarted." << std::endl; } } formatter->flush(cout); } break; case OPT::REALM_CREATE: { if (realm_name.empty()) { cerr << "missing realm name" << std::endl; return EINVAL; } RGWRealm realm; realm.name = realm_name; constexpr bool exclusive = true; int ret = rgw::create_realm(dpp(), null_yield, cfgstore.get(), exclusive, realm); if (ret < 0) { cerr << "ERROR: couldn't create realm " << realm_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } if (set_default) { ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm); if (ret < 0) { cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("realm", realm, formatter.get()); formatter->flush(cout); } break; case OPT::REALM_DELETE: { if (realm_id.empty() && realm_name.empty()) { cerr << "missing realm name or id" << std::endl; return EINVAL; } RGWRealm realm; std::unique_ptr<rgw::sal::RealmWriter> writer; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm, &writer); if (ret < 0) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = writer->remove(dpp(), null_yield); if (ret < 0) { cerr << "failed to remove realm: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::REALM_GET: { RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0) { if (ret == -ENOENT && realm_name.empty() && realm_id.empty()) { cerr << "missing realm name or id, or default realm not found" << std::endl; } else { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; } return -ret; } encode_json("realm", realm, formatter.get()); formatter->flush(cout); } break; case OPT::REALM_GET_DEFAULT: { string default_id; int ret = cfgstore->read_default_realm_id(dpp(), null_yield, default_id); if (ret == -ENOENT) { cout << "No default realm is set" << std::endl; return -ret; } else if (ret < 0) { cerr << "Error reading default realm: " << cpp_strerror(-ret) << std::endl; return -ret; } cout << "default realm: " << default_id << std::endl; } break; case OPT::REALM_LIST: { std::string default_id; int ret = cfgstore->read_default_realm_id(dpp(), null_yield, default_id); if (ret < 0 && ret != -ENOENT) { cerr << "could not determine default realm: " << cpp_strerror(-ret) << std::endl; } Formatter::ObjectSection realms_list{*formatter, "realms_list"}; encode_json("default_info", default_id, formatter.get()); Formatter::ArraySection realms{*formatter, "realms"}; rgw::sal::ListResult<std::string> listing; std::array<std::string, 1000> names; // list in pages of 1000 do { ret = cfgstore->list_realm_names(dpp(), null_yield, listing.next, names, listing); if (ret < 0) { std::cerr << "failed to list realms: " << cpp_strerror(-ret) << std::endl; return -ret; } for (const auto& name : listing.entries) { encode_json("name", name, formatter.get()); } } while (!listing.next.empty()); } // close sections realms and realms_list formatter->flush(cout); break; case OPT::REALM_LIST_PERIODS: { // use realm's current period RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } period_id = realm.current_period; Formatter::ObjectSection periods_list{*formatter, "realm_periods_list"}; encode_json("current_period", period_id, formatter.get()); Formatter::ArraySection periods{*formatter, "periods"}; while (!period_id.empty()) { RGWPeriod period; ret = cfgstore->read_period(dpp(), null_yield, period_id, std::nullopt, period); if (ret < 0) { cerr << "failed to load period id " << period_id << ": " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("id", period_id, formatter.get()); period_id = period.predecessor_uuid; } } // close sections periods and realm_periods_list formatter->flush(cout); break; case OPT::REALM_RENAME: { if (realm_new_name.empty()) { cerr << "missing realm new name" << std::endl; return EINVAL; } if (realm_name.empty() && realm_id.empty()) { cerr << "missing realm name or id" << std::endl; return EINVAL; } RGWRealm realm; std::unique_ptr<rgw::sal::RealmWriter> writer; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm, &writer); if (ret < 0) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = writer->rename(dpp(), null_yield, realm, realm_new_name); if (ret < 0) { cerr << "rename failed: " << cpp_strerror(-ret) << std::endl; return -ret; } cout << "Realm name updated. Note that this change only applies to " "the current cluster, so this command must be run separately " "on each of the realm's other clusters." << std::endl; } break; case OPT::REALM_SET: { if (realm_id.empty() && realm_name.empty()) { cerr << "no realm name or id provided" << std::endl; return EINVAL; } bool new_realm = false; RGWRealm realm; std::unique_ptr<rgw::sal::RealmWriter> writer; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm, &writer); if (ret < 0 && ret != -ENOENT) { cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl; return -ret; } else if (ret == -ENOENT) { new_realm = true; } ret = read_decode_json(infile, realm); if (ret < 0) { return 1; } if (!realm_name.empty() && realm.get_name() != realm_name) { cerr << "mismatch between --rgw-realm " << realm_name << " and json input file name " << realm.get_name() << std::endl; return EINVAL; } /* new realm */ if (new_realm) { cout << "clearing period and epoch for new realm" << std::endl; realm.clear_current_period_and_epoch(); constexpr bool exclusive = true; ret = rgw::create_realm(dpp(), null_yield, cfgstore.get(), exclusive, realm); if (ret < 0) { cerr << "ERROR: couldn't create new realm: " << cpp_strerror(-ret) << std::endl; return 1; } } else { ret = writer->write(dpp(), null_yield, realm); if (ret < 0) { cerr << "ERROR: couldn't driver realm info: " << cpp_strerror(-ret) << std::endl; return 1; } } if (set_default) { ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm); if (ret < 0) { cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("realm", realm, formatter.get()); formatter->flush(cout); } break; case OPT::REALM_DEFAULT: { RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm); if (ret < 0) { cerr << "failed to set realm as default: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::REALM_PULL: { if (url.empty()) { cerr << "A --url must be provided." << std::endl; return EINVAL; } RGWEnv env; req_info info(g_ceph_context, &env); info.method = "GET"; info.request_uri = "/admin/realm"; map<string, string> &params = info.args.get_params(); if (!realm_id.empty()) params["id"] = realm_id; if (!realm_name.empty()) params["name"] = realm_name; bufferlist bl; JSONParser p; int ret = send_to_url(url, opt_region, access_key, secret_key, info, bl, p); if (ret < 0) { cerr << "request failed: " << cpp_strerror(-ret) << std::endl; if (ret == -EACCES) { cerr << "If the realm has been changed on the master zone, the " "master zone's gateway may need to be restarted to recognize " "this user." << std::endl; } return -ret; } RGWRealm realm; try { decode_json_obj(realm, &p); } catch (const JSONDecoder::err& e) { cerr << "failed to decode JSON response: " << e.what() << std::endl; return EINVAL; } RGWPeriod period; auto& current_period = realm.get_current_period(); if (!current_period.empty()) { // pull the latest epoch of the realm's current period ret = do_period_pull(cfgstore.get(), nullptr, url, opt_region, access_key, secret_key, realm_id, realm_name, current_period, "", &period); if (ret < 0) { cerr << "could not fetch period " << current_period << std::endl; return -ret; } } constexpr bool exclusive = false; ret = rgw::create_realm(dpp(), null_yield, cfgstore.get(), exclusive, realm); if (ret < 0) { cerr << "Error storing realm " << realm.get_id() << ": " << cpp_strerror(ret) << std::endl; return -ret; } if (set_default) { ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm); if (ret < 0) { cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("realm", realm, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_ADD: { if (zonegroup_id.empty() && zonegroup_name.empty()) { cerr << "no zonegroup name or id provided" << std::endl; return EINVAL; } // load the zonegroup and zone params RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &zonegroup_writer); if (ret < 0) { cerr << "failed to load zonegroup " << zonegroup_name << " id " << zonegroup_id << ": " << cpp_strerror(-ret) << std::endl; return -ret; } RGWZoneParams zone_params; std::unique_ptr<rgw::sal::ZoneWriter> zone_writer; ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone_params, &zone_writer); if (ret < 0) { cerr << "unable to load zone: " << cpp_strerror(-ret) << std::endl; return -ret; } // update zone_params if necessary bool need_zone_update = false; if (zone_params.realm_id != zonegroup.realm_id) { if (!zone_params.realm_id.empty()) { cerr << "WARNING: overwriting zone realm_id=" << zone_params.realm_id << " to match zonegroup realm_id=" << zonegroup.realm_id << std::endl; } zone_params.realm_id = zonegroup.realm_id; need_zone_update = true; } for (auto a : tier_config_add) { ret = zone_params.tier_config.set(a.first, a.second); if (ret < 0) { cerr << "ERROR: failed to set configurable: " << a << std::endl; return EINVAL; } need_zone_update = true; } if (need_zone_update) { ret = zone_writer->write(dpp(), null_yield, zone_params); if (ret < 0) { cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl; return -ret; } } const bool *pis_master = (is_master_set ? &is_master : nullptr); const bool *pread_only = (is_read_only_set ? &read_only : nullptr); const bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr); const string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr); // validate --tier-type if specified const string *ptier_type = (tier_type_specified ? &tier_type : nullptr); if (ptier_type) { auto sync_mgr = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager(); if (!sync_mgr->get_module(*ptier_type, nullptr)) { ldpp_dout(dpp(), -1) << "ERROR: could not find sync module: " << *ptier_type << ", valid sync modules: " << sync_mgr->get_registered_module_names() << dendl; return EINVAL; } } if (enable_features.empty()) { // enable all features by default enable_features.insert(rgw::zone_features::supported.begin(), rgw::zone_features::supported.end()); } // add/update the public zone information stored in the zonegroup ret = rgw::add_zone_to_group(dpp(), zonegroup, zone_params, pis_master, pread_only, endpoints, ptier_type, psync_from_all, sync_from, sync_from_rm, predirect_zone, bucket_index_max_shards, enable_features, disable_features); if (ret < 0) { return -ret; } // write the updated zonegroup ret = zonegroup_writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to write updated zonegroup " << zonegroup.get_name() << ": " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("zonegroup", zonegroup, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_CREATE: { if (zonegroup_name.empty()) { cerr << "Missing zonegroup name" << std::endl; return EINVAL; } RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0) { cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWZoneGroup zonegroup; zonegroup.name = zonegroup_name; zonegroup.is_master = is_master; zonegroup.realm_id = realm.get_id(); zonegroup.endpoints = endpoints; zonegroup.api_name = (api_name.empty() ? zonegroup_name : api_name); zonegroup.enabled_features = enable_features; if (zonegroup.enabled_features.empty()) { // enable features by default zonegroup.enabled_features.insert(rgw::zone_features::enabled.begin(), rgw::zone_features::enabled.end()); } for (const auto& feature : disable_features) { auto i = zonegroup.enabled_features.find(feature); if (i == zonegroup.enabled_features.end()) { ldout(cct, 1) << "WARNING: zone feature \"" << feature << "\" was not enabled in zonegroup " << zonegroup_name << dendl; continue; } zonegroup.enabled_features.erase(i); } constexpr bool exclusive = true; ret = rgw::create_zonegroup(dpp(), null_yield, cfgstore.get(), exclusive, zonegroup); if (ret < 0) { cerr << "failed to create zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } if (set_default) { ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup); if (ret < 0) { cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("zonegroup", zonegroup, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_DEFAULT: { if (zonegroup_id.empty() && zonegroup_name.empty()) { cerr << "no zonegroup name or id provided" << std::endl; return EINVAL; } RGWZoneGroup zonegroup; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup); if (ret < 0) { cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup); if (ret < 0) { cerr << "failed to set zonegroup as default: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::ZONEGROUP_DELETE: { if (zonegroup_id.empty() && zonegroup_name.empty()) { cerr << "no zonegroup name or id provided" << std::endl; return EINVAL; } RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> writer; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &writer); if (ret < 0) { cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = writer->remove(dpp(), null_yield); if (ret < 0) { cerr << "ERROR: couldn't delete zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::ZONEGROUP_GET: { RGWZoneGroup zonegroup; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup); if (ret < 0) { cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("zonegroup", zonegroup, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_LIST: { RGWZoneGroup default_zonegroup; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), {}, {}, default_zonegroup); if (ret < 0 && ret != -ENOENT) { cerr << "could not determine default zonegroup: " << cpp_strerror(-ret) << std::endl; } Formatter::ObjectSection zonegroups_list{*formatter, "zonegroups_list"}; encode_json("default_info", default_zonegroup.id, formatter.get()); Formatter::ArraySection zonegroups{*formatter, "zonegroups"}; rgw::sal::ListResult<std::string> listing; std::array<std::string, 1000> names; // list in pages of 1000 do { ret = cfgstore->list_zonegroup_names(dpp(), null_yield, listing.next, names, listing); if (ret < 0) { std::cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl; return -ret; } for (const auto& name : listing.entries) { encode_json("name", name, formatter.get()); } } while (!listing.next.empty()); } // close sections zonegroups and zonegroups_list formatter->flush(cout); break; case OPT::ZONEGROUP_MODIFY: { RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> writer; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &writer); if (ret < 0) { cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } bool need_update = false; if (!master_zone.empty()) { zonegroup.master_zone = master_zone; need_update = true; } if (is_master_set) { zonegroup.is_master = is_master; need_update = true; } if (!endpoints.empty()) { zonegroup.endpoints = endpoints; need_update = true; } if (!api_name.empty()) { zonegroup.api_name = api_name; need_update = true; } if (!realm_id.empty()) { zonegroup.realm_id = realm_id; need_update = true; } else if (!realm_name.empty()) { // get realm id from name ret = cfgstore->read_realm_id(dpp(), null_yield, realm_name, zonegroup.realm_id); if (ret < 0) { cerr << "failed to find realm by name " << realm_name << std::endl; return -ret; } need_update = true; } if (bucket_index_max_shards) { for (auto& [name, zone] : zonegroup.zones) { zone.bucket_index_max_shards = *bucket_index_max_shards; } need_update = true; } for (const auto& feature : enable_features) { zonegroup.enabled_features.insert(feature); need_update = true; } for (const auto& feature : disable_features) { auto i = zonegroup.enabled_features.find(feature); if (i == zonegroup.enabled_features.end()) { ldout(cct, 1) << "WARNING: zone feature \"" << feature << "\" was not enabled in zonegroup " << zonegroup.get_name() << dendl; continue; } zonegroup.enabled_features.erase(i); need_update = true; } if (need_update) { ret = writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (set_default) { ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup); if (ret < 0) { cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("zonegroup", zonegroup, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_SET: { RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); bool default_realm_not_exist = (ret == -ENOENT && realm_id.empty() && realm_name.empty()); if (ret < 0 && !default_realm_not_exist) { cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWZoneGroup zonegroup; ret = read_decode_json(infile, zonegroup); if (ret < 0) { return 1; } if (zonegroup.realm_id.empty() && !default_realm_not_exist) { zonegroup.realm_id = realm.get_id(); } // validate zonegroup features for (const auto& feature : zonegroup.enabled_features) { if (!rgw::zone_features::supports(feature)) { std::cerr << "ERROR: Unrecognized zonegroup feature \"" << feature << "\"" << std::endl; return EINVAL; } } for (const auto& [name, zone] : zonegroup.zones) { // validate zone features for (const auto& feature : zone.supported_features) { if (!rgw::zone_features::supports(feature)) { std::cerr << "ERROR: Unrecognized zone feature \"" << feature << "\" in zone " << zone.name << std::endl; return EINVAL; } } // zone must support everything zonegroup does for (const auto& feature : zonegroup.enabled_features) { if (!zone.supports(feature)) { std::cerr << "ERROR: Zone " << name << " does not support feature \"" << feature << "\" required by zonegroup" << std::endl; return EINVAL; } } } // create/overwrite the zonegroup info constexpr bool exclusive = false; ret = rgw::create_zonegroup(dpp(), null_yield, cfgstore.get(), exclusive, zonegroup); if (ret < 0) { cerr << "ERROR: couldn't create zonegroup info: " << cpp_strerror(-ret) << std::endl; return 1; } if (set_default) { ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup); if (ret < 0) { cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("zonegroup", zonegroup, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_REMOVE: { RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> writer; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &writer); if (ret < 0) { cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } if (zone_id.empty()) { if (zone_name.empty()) { cerr << "no --zone-id or --rgw-zone name provided" << std::endl; return EINVAL; } // look up zone id by name for (auto& z : zonegroup.zones) { if (zone_name == z.second.name) { zone_id = z.second.id; break; } } if (zone_id.empty()) { cerr << "zone name " << zone_name << " not found in zonegroup " << zonegroup.get_name() << std::endl; return ENOENT; } } ret = rgw::remove_zone_from_group(dpp(), zonegroup, zone_id); if (ret < 0) { cerr << "failed to remove zone: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to write zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("zonegroup", zonegroup, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_RENAME: { if (zonegroup_new_name.empty()) { cerr << " missing zonegroup new name" << std::endl; return EINVAL; } if (zonegroup_id.empty() && zonegroup_name.empty()) { cerr << "no zonegroup name or id provided" << std::endl; return EINVAL; } RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> writer; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &writer); if (ret < 0) { cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = writer->rename(dpp(), null_yield, zonegroup, zonegroup_new_name); if (ret < 0) { cerr << "failed to rename zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::ZONEGROUP_PLACEMENT_LIST: { RGWZoneGroup zonegroup; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup); if (ret < 0) { cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("placement_targets", zonegroup.placement_targets, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_PLACEMENT_GET: { if (placement_id.empty()) { cerr << "ERROR: --placement-id not specified" << std::endl; return EINVAL; } RGWZoneGroup zonegroup; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup); if (ret < 0) { cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } auto p = zonegroup.placement_targets.find(placement_id); if (p == zonegroup.placement_targets.end()) { cerr << "failed to find a zonegroup placement target named '" << placement_id << "'" << std::endl; return -ENOENT; } encode_json("placement_targets", p->second, formatter.get()); formatter->flush(cout); } break; case OPT::ZONEGROUP_PLACEMENT_ADD: case OPT::ZONEGROUP_PLACEMENT_MODIFY: case OPT::ZONEGROUP_PLACEMENT_RM: case OPT::ZONEGROUP_PLACEMENT_DEFAULT: { if (placement_id.empty()) { cerr << "ERROR: --placement-id not specified" << std::endl; return EINVAL; } rgw_placement_rule rule; rule.from_str(placement_id); if (!rule.storage_class.empty() && opt_storage_class && rule.storage_class != *opt_storage_class) { cerr << "ERROR: provided contradicting storage class configuration" << std::endl; return EINVAL; } else if (rule.storage_class.empty()) { rule.storage_class = opt_storage_class.value_or(string()); } RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> writer; int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &writer); if (ret < 0) { cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_ADD || opt_cmd == OPT::ZONEGROUP_PLACEMENT_MODIFY) { RGWZoneGroupPlacementTarget& target = zonegroup.placement_targets[placement_id]; if (!tags.empty()) { target.tags.clear(); for (auto& t : tags) { target.tags.insert(t); } } target.name = placement_id; for (auto& t : tags_rm) { target.tags.erase(t); } for (auto& t : tags_add) { target.tags.insert(t); } target.storage_classes.insert(rule.get_storage_class()); /* Tier options */ bool tier_class = false; std::string storage_class = rule.get_storage_class(); RGWZoneGroupPlacementTier t{storage_class}; RGWZoneGroupPlacementTier *pt = &t; auto ptiter = target.tier_targets.find(storage_class); if (ptiter != target.tier_targets.end()) { pt = &ptiter->second; tier_class = true; } else if (tier_type_specified) { if (tier_type == "cloud-s3") { /* we support only cloud-s3 tier-type for now. * Once set cant be reset. */ tier_class = true; pt->tier_type = tier_type; pt->storage_class = storage_class; } else { cerr << "ERROR: Invalid tier-type specified" << std::endl; return EINVAL; } } if (tier_class) { if (tier_config_add.size() > 0) { JSONFormattable tconfig; for (auto add : tier_config_add) { int r = tconfig.set(add.first, add.second); if (r < 0) { cerr << "ERROR: failed to set configurable: " << add << std::endl; return EINVAL; } } int r = pt->update_params(tconfig); if (r < 0) { cerr << "ERROR: failed to update tier_config options"<< std::endl; } } if (tier_config_rm.size() > 0) { JSONFormattable tconfig; for (auto add : tier_config_rm) { int r = tconfig.set(add.first, add.second); if (r < 0) { cerr << "ERROR: failed to set configurable: " << add << std::endl; return EINVAL; } } int r = pt->clear_params(tconfig); if (r < 0) { cerr << "ERROR: failed to update tier_config options"<< std::endl; } } target.tier_targets.emplace(std::make_pair(storage_class, *pt)); } if (zonegroup.default_placement.empty()) { zonegroup.default_placement.init(rule.name, RGW_STORAGE_CLASS_STANDARD); } } else if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_RM) { if (!opt_storage_class || opt_storage_class->empty()) { zonegroup.placement_targets.erase(placement_id); if (zonegroup.default_placement.name == placement_id) { // clear default placement zonegroup.default_placement.clear(); } } else { auto iter = zonegroup.placement_targets.find(placement_id); if (iter != zonegroup.placement_targets.end()) { RGWZoneGroupPlacementTarget& info = zonegroup.placement_targets[placement_id]; info.storage_classes.erase(*opt_storage_class); if (zonegroup.default_placement == rule) { // clear default storage class zonegroup.default_placement.storage_class.clear(); } auto ptiter = info.tier_targets.find(*opt_storage_class); if (ptiter != info.tier_targets.end()) { info.tier_targets.erase(ptiter); } } } } else if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_DEFAULT) { if (!zonegroup.placement_targets.count(placement_id)) { cerr << "failed to find a zonegroup placement target named '" << placement_id << "'" << std::endl; return -ENOENT; } zonegroup.default_placement = rule; } ret = writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("placement_targets", zonegroup.placement_targets, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_CREATE: { if (zone_name.empty()) { cerr << "zone name not provided" << std::endl; return EINVAL; } RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer; /* if the user didn't provide zonegroup info , create stand alone zone */ if (!zonegroup_id.empty() || !zonegroup_name.empty()) { int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &zonegroup_writer); if (ret < 0) { cerr << "failed to load zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } if (realm_id.empty() && realm_name.empty()) { realm_id = zonegroup.realm_id; } } // create the local zone params RGWZoneParams zone_params; zone_params.id = zone_id; zone_params.name = zone_name; zone_params.system_key.id = access_key; zone_params.system_key.key = secret_key; zone_params.realm_id = realm_id; for (const auto& a : tier_config_add) { int r = zone_params.tier_config.set(a.first, a.second); if (r < 0) { cerr << "ERROR: failed to set configurable: " << a << std::endl; return EINVAL; } } if (zone_params.realm_id.empty()) { RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 && ret != -ENOENT) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } zone_params.realm_id = realm.id; cerr << "NOTICE: set zone's realm_id=" << realm.id << std::endl; } constexpr bool exclusive = true; int ret = rgw::create_zone(dpp(), null_yield, cfgstore.get(), exclusive, zone_params); if (ret < 0) { cerr << "failed to create zone " << zone_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } if (zonegroup_writer) { const bool *pis_master = (is_master_set ? &is_master : nullptr); const bool *pread_only = (is_read_only_set ? &read_only : nullptr); const bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr); const string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr); // validate --tier-type if specified const string *ptier_type = (tier_type_specified ? &tier_type : nullptr); if (ptier_type) { auto sync_mgr = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager(); if (!sync_mgr->get_module(*ptier_type, nullptr)) { ldpp_dout(dpp(), -1) << "ERROR: could not find sync module: " << *ptier_type << ", valid sync modules: " << sync_mgr->get_registered_module_names() << dendl; return EINVAL; } } if (enable_features.empty()) { // enable all features by default enable_features.insert(rgw::zone_features::supported.begin(), rgw::zone_features::supported.end()); } // add/update the public zone information stored in the zonegroup ret = rgw::add_zone_to_group(dpp(), zonegroup, zone_params, pis_master, pread_only, endpoints, ptier_type, psync_from_all, sync_from, sync_from_rm, predirect_zone, bucket_index_max_shards, enable_features, disable_features); if (ret < 0) { return -ret; } // write the updated zonegroup ret = zonegroup_writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to add zone " << zone_name << " to zonegroup " << zonegroup.get_name() << ": " << cpp_strerror(-ret) << std::endl; return -ret; } } if (set_default) { ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(), zone_params); if (ret < 0) { cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("zone", zone_params, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_DEFAULT: { if (zone_id.empty() && zone_name.empty()) { cerr << "no zone name or id provided" << std::endl; return EINVAL; } RGWZoneParams zone_params; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone_params); if (ret < 0) { cerr << "unable to load zone: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(), zone_params); if (ret < 0) { cerr << "failed to set zone as default: " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::ZONE_DELETE: { if (zone_id.empty() && zone_name.empty()) { cerr << "no zone name or id provided" << std::endl; return EINVAL; } RGWZoneParams zone_params; std::unique_ptr<rgw::sal::ZoneWriter> writer; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone_params, &writer); if (ret < 0) { cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = rgw::delete_zone(dpp(), null_yield, cfgstore.get(), zone_params, *writer); if (ret < 0) { cerr << "failed to delete zone " << zone_params.get_name() << ": " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::ZONE_GET: { RGWZoneParams zone_params; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone_params); if (ret < 0) { cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("zone", zone_params, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_SET: { RGWZoneParams zone; std::unique_ptr<rgw::sal::ZoneWriter> writer; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone, &writer); if (ret < 0 && ret != -ENOENT) { cerr << "failed to load zone: " << cpp_strerror(ret) << std::endl; return -ret; } string orig_id = zone.get_id(); ret = read_decode_json(infile, zone); if (ret < 0) { return 1; } if (zone.realm_id.empty()) { RGWRealm realm; ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 && ret != -ENOENT) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } zone.realm_id = realm.get_id(); cerr << "NOTICE: set zone's realm_id=" << zone.realm_id << std::endl; } if (!zone_name.empty() && !zone.get_name().empty() && zone.get_name() != zone_name) { cerr << "Error: zone name " << zone_name << " is different than the zone name " << zone.get_name() << " in the provided json " << std::endl; return EINVAL; } if (zone.get_name().empty()) { zone.set_name(zone_name); if (zone.get_name().empty()) { cerr << "no zone name specified" << std::endl; return EINVAL; } } zone_name = zone.get_name(); if (zone.get_id().empty()) { zone.set_id(orig_id); } constexpr bool exclusive = false; ret = rgw::create_zone(dpp(), null_yield, cfgstore.get(), exclusive, zone); if (ret < 0) { cerr << "ERROR: couldn't create zone: " << cpp_strerror(-ret) << std::endl; return -ret; } if (set_default) { ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(), zone); if (ret < 0) { cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("zone", zone, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_LIST: { RGWZoneParams default_zone_params; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), {}, {}, default_zone_params); if (ret < 0 && ret != -ENOENT) { cerr << "could not determine default zone: " << cpp_strerror(-ret) << std::endl; } Formatter::ObjectSection zones_list{*formatter, "zones_list"}; encode_json("default_info", default_zone_params.id, formatter.get()); Formatter::ArraySection zones{*formatter, "zones"}; rgw::sal::ListResult<std::string> listing; std::array<std::string, 1000> names; // list in pages of 1000 do { ret = cfgstore->list_zone_names(dpp(), null_yield, listing.next, names, listing); if (ret < 0) { std::cerr << "failed to list zones: " << cpp_strerror(-ret) << std::endl; return -ret; } for (const auto& name : listing.entries) { encode_json("name", name, formatter.get()); } } while (!listing.next.empty()); } // close sections zones and zones_list formatter->flush(cout); break; case OPT::ZONE_MODIFY: { RGWZoneParams zone_params; std::unique_ptr<rgw::sal::ZoneWriter> zone_writer; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone_params, &zone_writer); if (ret < 0) { cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl; return -ret; } bool need_zone_update = false; if (!access_key.empty()) { zone_params.system_key.id = access_key; need_zone_update = true; } if (!secret_key.empty()) { zone_params.system_key.key = secret_key; need_zone_update = true; } if (!realm_id.empty()) { zone_params.realm_id = realm_id; need_zone_update = true; } else if (!realm_name.empty()) { // get realm id from name ret = cfgstore->read_realm_id(dpp(), null_yield, realm_name, zone_params.realm_id); if (ret < 0) { cerr << "failed to find realm by name " << realm_name << std::endl; return -ret; } need_zone_update = true; } for (const auto& add : tier_config_add) { ret = zone_params.tier_config.set(add.first, add.second); if (ret < 0) { cerr << "ERROR: failed to set configurable: " << add << std::endl; return EINVAL; } need_zone_update = true; } for (const auto& rm : tier_config_rm) { if (!rm.first.empty()) { /* otherwise will remove the entire config */ zone_params.tier_config.erase(rm.first); need_zone_update = true; } } if (need_zone_update) { ret = zone_writer->write(dpp(), null_yield, zone_params); if (ret < 0) { cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl; return -ret; } } RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer; ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &zonegroup_writer); if (ret < 0) { cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } const bool *pis_master = (is_master_set ? &is_master : nullptr); const bool *pread_only = (is_read_only_set ? &read_only : nullptr); const bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr); const string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr); // validate --tier-type if specified const string *ptier_type = (tier_type_specified ? &tier_type : nullptr); if (ptier_type) { auto sync_mgr = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager(); if (!sync_mgr->get_module(*ptier_type, nullptr)) { ldpp_dout(dpp(), -1) << "ERROR: could not find sync module: " << *ptier_type << ", valid sync modules: " << sync_mgr->get_registered_module_names() << dendl; return EINVAL; } } if (enable_features.empty()) { // enable all features by default enable_features.insert(rgw::zone_features::supported.begin(), rgw::zone_features::supported.end()); } // add/update the public zone information stored in the zonegroup ret = rgw::add_zone_to_group(dpp(), zonegroup, zone_params, pis_master, pread_only, endpoints, ptier_type, psync_from_all, sync_from, sync_from_rm, predirect_zone, bucket_index_max_shards, enable_features, disable_features); if (ret < 0) { return -ret; } // write the updated zonegroup ret = zonegroup_writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } if (set_default) { ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(), zone_params); if (ret < 0) { cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl; } } encode_json("zone", zone_params, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_RENAME: { if (zone_new_name.empty()) { cerr << " missing zone new name" << std::endl; return EINVAL; } if (zone_id.empty() && zone_name.empty()) { cerr << "no zone name or id provided" << std::endl; return EINVAL; } RGWZoneParams zone_params; std::unique_ptr<rgw::sal::ZoneWriter> zone_writer; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone_params, &zone_writer); if (ret < 0) { cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = zone_writer->rename(dpp(), null_yield, zone_params, zone_new_name); if (ret < 0) { cerr << "failed to rename zone " << zone_name << " to " << zone_new_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } RGWZoneGroup zonegroup; std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer; ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup, &zonegroup_writer); if (ret < 0) { cerr << "WARNING: failed to load zonegroup " << zonegroup_name << std::endl; return EXIT_SUCCESS; } auto z = zonegroup.zones.find(zone_params.id); if (z == zonegroup.zones.end()) { return EXIT_SUCCESS; } z->second.name = zone_params.name; ret = zonegroup_writer->write(dpp(), null_yield, zonegroup); if (ret < 0) { cerr << "Error in zonegroup rename for " << zone_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } } break; case OPT::ZONE_PLACEMENT_ADD: case OPT::ZONE_PLACEMENT_MODIFY: case OPT::ZONE_PLACEMENT_RM: { if (placement_id.empty()) { cerr << "ERROR: --placement-id not specified" << std::endl; return EINVAL; } // validate compression type if (compression_type && *compression_type != "random" && !Compressor::get_comp_alg_type(*compression_type)) { std::cerr << "Unrecognized compression type" << std::endl; return EINVAL; } RGWZoneParams zone; std::unique_ptr<rgw::sal::ZoneWriter> writer; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone, &writer); if (ret < 0) { cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl; return -ret; } if (opt_cmd == OPT::ZONE_PLACEMENT_ADD || opt_cmd == OPT::ZONE_PLACEMENT_MODIFY) { RGWZoneGroup zonegroup; ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(), zonegroup_id, zonegroup_name, zonegroup); if (ret < 0) { cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl; return -ret; } auto ptiter = zonegroup.placement_targets.find(placement_id); if (ptiter == zonegroup.placement_targets.end()) { cerr << "ERROR: placement id '" << placement_id << "' is not configured in zonegroup placement targets" << std::endl; return EINVAL; } string storage_class = rgw_placement_rule::get_canonical_storage_class(opt_storage_class.value_or(string())); if (ptiter->second.storage_classes.find(storage_class) == ptiter->second.storage_classes.end()) { cerr << "ERROR: storage class '" << storage_class << "' is not defined in zonegroup '" << placement_id << "' placement target" << std::endl; return EINVAL; } if (ptiter->second.tier_targets.find(storage_class) != ptiter->second.tier_targets.end()) { cerr << "ERROR: storage class '" << storage_class << "' is of tier type in zonegroup '" << placement_id << "' placement target" << std::endl; return EINVAL; } RGWZonePlacementInfo& info = zone.placement_pools[placement_id]; string opt_index_pool = index_pool.value_or(string()); string opt_data_pool = data_pool.value_or(string()); if (!opt_index_pool.empty()) { info.index_pool = opt_index_pool; } if (info.index_pool.empty()) { cerr << "ERROR: index pool not configured, need to specify --index-pool" << std::endl; return EINVAL; } if (opt_data_pool.empty()) { const RGWZoneStorageClass *porig_sc{nullptr}; if (info.storage_classes.find(storage_class, &porig_sc)) { if (porig_sc->data_pool) { opt_data_pool = porig_sc->data_pool->to_str(); } } if (opt_data_pool.empty()) { cerr << "ERROR: data pool not configured, need to specify --data-pool" << std::endl; return EINVAL; } } rgw_pool dp = opt_data_pool; info.storage_classes.set_storage_class(storage_class, &dp, compression_type.get_ptr()); if (data_extra_pool) { info.data_extra_pool = *data_extra_pool; } if (index_type_specified) { info.index_type = placement_index_type; } if (placement_inline_data_specified) { info.inline_data = placement_inline_data; } ret = check_pool_support_omap(info.get_data_extra_pool()); if (ret < 0) { cerr << "ERROR: the data extra (non-ec) pool '" << info.get_data_extra_pool() << "' does not support omap" << std::endl; return ret; } } else if (opt_cmd == OPT::ZONE_PLACEMENT_RM) { if (!opt_storage_class || opt_storage_class->empty()) { zone.placement_pools.erase(placement_id); } else { auto iter = zone.placement_pools.find(placement_id); if (iter != zone.placement_pools.end()) { RGWZonePlacementInfo& info = zone.placement_pools[placement_id]; info.storage_classes.remove_storage_class(*opt_storage_class); } } } ret = writer->write(dpp(), null_yield, zone); if (ret < 0) { cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("zone", zone, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_PLACEMENT_LIST: { RGWZoneParams zone; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone); if (ret < 0) { cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("placement_pools", zone.placement_pools, formatter.get()); formatter->flush(cout); } break; case OPT::ZONE_PLACEMENT_GET: { if (placement_id.empty()) { cerr << "ERROR: --placement-id not specified" << std::endl; return EINVAL; } RGWZoneParams zone; int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(), zone_id, zone_name, zone); if (ret < 0) { cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl; return -ret; } auto p = zone.placement_pools.find(placement_id); if (p == zone.placement_pools.end()) { cerr << "ERROR: zone placement target '" << placement_id << "' not found" << std::endl; return ENOENT; } encode_json("placement_pools", p->second, formatter.get()); formatter->flush(cout); } default: break; } return 0; } resolve_zone_id_opt(opt_effective_zone_name, opt_effective_zone_id); resolve_zone_id_opt(opt_source_zone_name, opt_source_zone_id); resolve_zone_id_opt(opt_dest_zone_name, opt_dest_zone_id); resolve_zone_ids_opt(opt_zone_names, opt_zone_ids); resolve_zone_ids_opt(opt_source_zone_names, opt_source_zone_ids); resolve_zone_ids_opt(opt_dest_zone_names, opt_dest_zone_ids); bool non_master_cmd = (!driver->is_meta_master() && !yes_i_really_mean_it); std::set<OPT> non_master_ops_list = {OPT::USER_CREATE, OPT::USER_RM, OPT::USER_MODIFY, OPT::USER_ENABLE, OPT::USER_SUSPEND, OPT::SUBUSER_CREATE, OPT::SUBUSER_MODIFY, OPT::SUBUSER_RM, OPT::BUCKET_LINK, OPT::BUCKET_UNLINK, OPT::BUCKET_RM, OPT::BUCKET_CHOWN, OPT::METADATA_PUT, OPT::METADATA_RM, OPT::MFA_CREATE, OPT::MFA_REMOVE, OPT::MFA_RESYNC, OPT::CAPS_ADD, OPT::CAPS_RM, OPT::ROLE_CREATE, OPT::ROLE_DELETE, OPT::ROLE_POLICY_PUT, OPT::ROLE_POLICY_DELETE}; bool print_warning_message = (non_master_ops_list.find(opt_cmd) != non_master_ops_list.end() && non_master_cmd); if (print_warning_message) { cerr << "Please run the command on master zone. Performing this operation on non-master zone leads to inconsistent metadata between zones" << std::endl; cerr << "Are you sure you want to go ahead? (requires --yes-i-really-mean-it)" << std::endl; return EINVAL; } if (!rgw::sal::User::empty(user)) { user_op.set_user_id(user->get_id()); bucket_op.set_user_id(user->get_id()); } if (!display_name.empty()) user_op.set_display_name(display_name); if (!user_email.empty()) user_op.set_user_email(user_email); if (!rgw::sal::User::empty(user)) { user_op.set_new_user_id(new_user_id); } if (!access_key.empty()) user_op.set_access_key(access_key); if (!secret_key.empty()) user_op.set_secret_key(secret_key); if (!subuser.empty()) user_op.set_subuser(subuser); if (!caps.empty()) user_op.set_caps(caps); user_op.set_purge_data(purge_data); if (purge_keys) user_op.set_purge_keys(); if (gen_access_key) user_op.set_generate_key(); if (gen_secret_key) user_op.set_gen_secret(); // assume that a key pair should be created if (max_buckets_specified) user_op.set_max_buckets(max_buckets); if (admin_specified) user_op.set_admin(admin); if (system_specified) user_op.set_system(system); if (set_perm) user_op.set_perm(perm_mask); if (set_temp_url_key) { map<int, string>::iterator iter = temp_url_keys.begin(); for (; iter != temp_url_keys.end(); ++iter) { user_op.set_temp_url_key(iter->second, iter->first); } } if (!op_mask_str.empty()) { uint32_t op_mask; int ret = rgw_parse_op_type_list(op_mask_str, &op_mask); if (ret < 0) { cerr << "failed to parse op_mask: " << cpp_strerror(-ret) << std::endl; return -ret; } user_op.set_op_mask(op_mask); } if (key_type != KEY_TYPE_UNDEFINED) user_op.set_key_type(key_type); // set suspension operation parameters if (opt_cmd == OPT::USER_ENABLE) user_op.set_suspension(false); else if (opt_cmd == OPT::USER_SUSPEND) user_op.set_suspension(true); if (!placement_id.empty()) { rgw_placement_rule target_rule; target_rule.name = placement_id; target_rule.storage_class = opt_storage_class.value_or(""); if (!driver->valid_placement(target_rule)) { cerr << "NOTICE: invalid dest placement: " << target_rule.to_str() << std::endl; return EINVAL; } user_op.set_default_placement(target_rule); } if (!tags.empty()) { user_op.set_placement_tags(tags); } // RGWUser to use for user operations RGWUser ruser; int ret = 0; if (!(rgw::sal::User::empty(user) && access_key.empty()) || !subuser.empty()) { ret = ruser.init(dpp(), driver, user_op, null_yield); if (ret < 0) { cerr << "user.init failed: " << cpp_strerror(-ret) << std::endl; return -ret; } } /* populate bucket operation */ bucket_op.set_bucket_name(bucket_name); bucket_op.set_object(object); bucket_op.set_check_objects(check_objects); bucket_op.set_delete_children(delete_child_objects); bucket_op.set_fix_index(fix); bucket_op.set_max_aio(max_concurrent_ios); // required to gather errors from operations std::string err_msg; bool output_user_info = true; switch (opt_cmd) { case OPT::USER_INFO: if (rgw::sal::User::empty(user) && access_key.empty()) { cerr << "ERROR: --uid or --access-key required" << std::endl; return EINVAL; } break; case OPT::USER_CREATE: if (!user_op.has_existing_user()) { user_op.set_generate_key(); // generate a new key by default } ret = ruser.add(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not create user: " << err_msg << std::endl; if (ret == -ERR_INVALID_TENANT_NAME) ret = -EINVAL; return -ret; } if (!subuser.empty()) { ret = ruser.subusers.add(dpp(),user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not create subuser: " << err_msg << std::endl; return -ret; } } break; case OPT::USER_RM: ret = ruser.remove(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not remove user: " << err_msg << std::endl; return -ret; } output_user_info = false; break; case OPT::USER_RENAME: if (yes_i_really_mean_it) { user_op.set_overwrite_new_user(true); } ret = ruser.rename(user_op, null_yield, dpp(), &err_msg); if (ret < 0) { if (ret == -EEXIST) { err_msg += ". to overwrite this user, add --yes-i-really-mean-it"; } cerr << "could not rename user: " << err_msg << std::endl; return -ret; } break; case OPT::USER_ENABLE: case OPT::USER_SUSPEND: case OPT::USER_MODIFY: ret = ruser.modify(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not modify user: " << err_msg << std::endl; return -ret; } break; case OPT::SUBUSER_CREATE: ret = ruser.subusers.add(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not create subuser: " << err_msg << std::endl; return -ret; } break; case OPT::SUBUSER_MODIFY: ret = ruser.subusers.modify(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not modify subuser: " << err_msg << std::endl; return -ret; } break; case OPT::SUBUSER_RM: ret = ruser.subusers.remove(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not remove subuser: " << err_msg << std::endl; return -ret; } break; case OPT::CAPS_ADD: ret = ruser.caps.add(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not add caps: " << err_msg << std::endl; return -ret; } break; case OPT::CAPS_RM: ret = ruser.caps.remove(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not remove caps: " << err_msg << std::endl; return -ret; } break; case OPT::KEY_CREATE: ret = ruser.keys.add(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not create key: " << err_msg << std::endl; return -ret; } break; case OPT::KEY_RM: ret = ruser.keys.remove(dpp(), user_op, null_yield, &err_msg); if (ret < 0) { cerr << "could not remove key: " << err_msg << std::endl; return -ret; } break; case OPT::PERIOD_PUSH: { RGWEnv env; req_info info(g_ceph_context, &env); info.method = "POST"; info.request_uri = "/admin/realm/period"; map<string, string> &params = info.args.get_params(); if (!realm_id.empty()) params["realm_id"] = realm_id; if (!realm_name.empty()) params["realm_name"] = realm_name; if (!period_id.empty()) params["period_id"] = period_id; if (!period_epoch.empty()) params["epoch"] = period_epoch; // load the period RGWPeriod period; int ret = cfgstore->read_period(dpp(), null_yield, period_id, std::nullopt, period); if (ret < 0) { cerr << "failed to load period: " << cpp_strerror(-ret) << std::endl; return -ret; } // json format into a bufferlist JSONFormatter jf(false); encode_json("period", period, &jf); bufferlist bl; jf.flush(bl); JSONParser p; ret = send_to_remote_or_url(nullptr, url, opt_region, access_key, secret_key, info, bl, p); if (ret < 0) { cerr << "request failed: " << cpp_strerror(-ret) << std::endl; return -ret; } } return 0; case OPT::PERIOD_UPDATE: { int ret = update_period(cfgstore.get(), realm_id, realm_name, period_epoch, commit, remote, url, opt_region, access_key, secret_key, formatter.get(), yes_i_really_mean_it); if (ret < 0) { return -ret; } } return 0; case OPT::PERIOD_COMMIT: { // read realm and staging period RGWRealm realm; std::unique_ptr<rgw::sal::RealmWriter> realm_writer; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm, &realm_writer); if (ret < 0) { cerr << "Error initializing realm: " << cpp_strerror(-ret) << std::endl; return -ret; } period_id = rgw::get_staging_period_id(realm.id); epoch_t epoch = 1; RGWPeriod period; ret = cfgstore->read_period(dpp(), null_yield, period_id, epoch, period); if (ret < 0) { cerr << "failed to load period: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = commit_period(cfgstore.get(), realm, *realm_writer, period, remote, url, opt_region, access_key, secret_key, yes_i_really_mean_it); if (ret < 0) { cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("period", period, formatter.get()); formatter->flush(cout); } return 0; case OPT::ROLE_CREATE: { if (role_name.empty()) { cerr << "ERROR: role name is empty" << std::endl; return -EINVAL; } if (assume_role_doc.empty()) { cerr << "ERROR: assume role policy document is empty" << std::endl; return -EINVAL; } bufferlist bl = bufferlist::static_from_string(assume_role_doc); try { const rgw::IAM::Policy p( g_ceph_context, tenant, bl, g_ceph_context->_conf.get_val<bool>( "rgw_policy_reject_invalid_principals")); } catch (rgw::IAM::PolicyParseException& e) { cerr << "failed to parse policy: " << e.what() << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant, path, assume_role_doc); ret = role->create(dpp(), true, "", null_yield); if (ret < 0) { return -ret; } show_role_info(role.get(), formatter.get()); return 0; } case OPT::ROLE_DELETE: { if (role_name.empty()) { cerr << "ERROR: empty role name" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->delete_obj(dpp(), null_yield); if (ret < 0) { return -ret; } cout << "role: " << role_name << " successfully deleted" << std::endl; return 0; } case OPT::ROLE_GET: { if (role_name.empty()) { cerr << "ERROR: empty role name" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } show_role_info(role.get(), formatter.get()); return 0; } case OPT::ROLE_TRUST_POLICY_MODIFY: { if (role_name.empty()) { cerr << "ERROR: role name is empty" << std::endl; return -EINVAL; } if (assume_role_doc.empty()) { cerr << "ERROR: assume role policy document is empty" << std::endl; return -EINVAL; } bufferlist bl = bufferlist::static_from_string(assume_role_doc); try { const rgw::IAM::Policy p(g_ceph_context, tenant, bl, g_ceph_context->_conf.get_val<bool>( "rgw_policy_reject_invalid_principals")); } catch (rgw::IAM::PolicyParseException& e) { cerr << "failed to parse policy: " << e.what() << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } role->update_trust_policy(assume_role_doc); ret = role->update(dpp(), null_yield); if (ret < 0) { return -ret; } cout << "Assume role policy document updated successfully for role: " << role_name << std::endl; return 0; } case OPT::ROLE_LIST: { vector<std::unique_ptr<rgw::sal::RGWRole>> result; ret = driver->get_roles(dpp(), null_yield, path_prefix, tenant, result); if (ret < 0) { return -ret; } show_roles_info(result, formatter.get()); return 0; } case OPT::ROLE_POLICY_PUT: { if (role_name.empty()) { cerr << "role name is empty" << std::endl; return -EINVAL; } if (policy_name.empty()) { cerr << "policy name is empty" << std::endl; return -EINVAL; } if (perm_policy_doc.empty() && infile.empty()) { cerr << "permission policy document is empty" << std::endl; return -EINVAL; } bufferlist bl; if (!infile.empty()) { int ret = read_input(infile, bl); if (ret < 0) { cerr << "ERROR: failed to read input policy document: " << cpp_strerror(-ret) << std::endl; return -ret; } perm_policy_doc = bl.to_str(); } else { bl = bufferlist::static_from_string(perm_policy_doc); } try { const rgw::IAM::Policy p(g_ceph_context, tenant, bl, g_ceph_context->_conf.get_val<bool>( "rgw_policy_reject_invalid_principals")); } catch (rgw::IAM::PolicyParseException& e) { cerr << "failed to parse perm policy: " << e.what() << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } role->set_perm_policy(policy_name, perm_policy_doc); ret = role->update(dpp(), null_yield); if (ret < 0) { return -ret; } cout << "Permission policy attached successfully" << std::endl; return 0; } case OPT::ROLE_POLICY_LIST: { if (role_name.empty()) { cerr << "ERROR: Role name is empty" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } std::vector<string> policy_names = role->get_role_policy_names(); show_policy_names(policy_names, formatter.get()); return 0; } case OPT::ROLE_POLICY_GET: { if (role_name.empty()) { cerr << "ERROR: role name is empty" << std::endl; return -EINVAL; } if (policy_name.empty()) { cerr << "ERROR: policy name is empty" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); int ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } string perm_policy; ret = role->get_role_policy(dpp(), policy_name, perm_policy); if (ret < 0) { return -ret; } show_perm_policy(perm_policy, formatter.get()); return 0; } case OPT::ROLE_POLICY_DELETE: { if (role_name.empty()) { cerr << "ERROR: role name is empty" << std::endl; return -EINVAL; } if (policy_name.empty()) { cerr << "ERROR: policy name is empty" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } ret = role->delete_policy(dpp(), policy_name); if (ret < 0) { return -ret; } ret = role->update(dpp(), null_yield); if (ret < 0) { return -ret; } cout << "Policy: " << policy_name << " successfully deleted for role: " << role_name << std::endl; return 0; } case OPT::ROLE_UPDATE: { if (role_name.empty()) { cerr << "ERROR: role name is empty" << std::endl; return -EINVAL; } std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant); ret = role->get(dpp(), null_yield); if (ret < 0) { return -ret; } if (!role->validate_max_session_duration(dpp())) { ret = -EINVAL; return ret; } role->update_max_session_duration(max_session_duration); ret = role->update(dpp(), null_yield); if (ret < 0) { return -ret; } cout << "Max session duration updated successfully for role: " << role_name << std::endl; return 0; } default: output_user_info = false; } // output the result of a user operation if (output_user_info) { ret = ruser.info(info, &err_msg); if (ret < 0) { cerr << "could not fetch user info: " << err_msg << std::endl; return -ret; } show_user_info(info, formatter.get()); } if (opt_cmd == OPT::POLICY) { if (format == "xml") { int ret = RGWBucketAdminOp::dump_s3_policy(driver, bucket_op, cout, dpp(), null_yield); if (ret < 0) { cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl; return -ret; } } else { int ret = RGWBucketAdminOp::get_policy(driver, bucket_op, stream_flusher, dpp(), null_yield); if (ret < 0) { cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl; return -ret; } } } if (opt_cmd == OPT::BUCKET_LIMIT_CHECK) { void *handle; std::list<std::string> user_ids; metadata_key = "user"; int max = 1000; bool truncated; if (!rgw::sal::User::empty(user)) { user_ids.push_back(user->get_id().id); ret = RGWBucketAdminOp::limit_check(driver, bucket_op, user_ids, stream_flusher, null_yield, dpp(), warnings_only); } else { /* list users in groups of max-keys, then perform user-bucket * limit-check on each group */ ret = driver->meta_list_keys_init(dpp(), metadata_key, string(), &handle); if (ret < 0) { cerr << "ERROR: buckets limit check can't get user metadata_key: " << cpp_strerror(-ret) << std::endl; return -ret; } do { ret = driver->meta_list_keys_next(dpp(), handle, max, user_ids, &truncated); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: buckets limit check lists_keys_next(): " << cpp_strerror(-ret) << std::endl; break; } else { /* ok, do the limit checks for this group */ ret = RGWBucketAdminOp::limit_check(driver, bucket_op, user_ids, stream_flusher, null_yield, dpp(), warnings_only); if (ret < 0) break; } user_ids.clear(); } while (truncated); driver->meta_list_keys_complete(handle); } return -ret; } /* OPT::BUCKET_LIMIT_CHECK */ if (opt_cmd == OPT::BUCKETS_LIST) { if (bucket_name.empty()) { if (!rgw::sal::User::empty(user)) { if (!user_op.has_existing_user()) { cerr << "ERROR: could not find user: " << user << std::endl; return -ENOENT; } } RGWBucketAdminOp::info(driver, bucket_op, stream_flusher, null_yield, dpp()); } else { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->open_array_section("entries"); int count = 0; static constexpr int MAX_PAGINATE_SIZE = 10000; static constexpr int DEFAULT_MAX_ENTRIES = 1000; if (max_entries < 0) { max_entries = DEFAULT_MAX_ENTRIES; } const int paginate_size = std::min(max_entries, MAX_PAGINATE_SIZE); string prefix; string delim; string ns; rgw::sal::Bucket::ListParams params; rgw::sal::Bucket::ListResults results; params.prefix = prefix; params.delim = delim; params.marker = rgw_obj_key(marker); params.ns = ns; params.enforce_ns = false; params.list_versions = true; params.allow_unordered = bool(allow_unordered); do { const int remaining = max_entries - count; ret = bucket->list(dpp(), params, std::min(remaining, paginate_size), results, null_yield); if (ret < 0) { cerr << "ERROR: driver->list_objects(): " << cpp_strerror(-ret) << std::endl; return -ret; } ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": list() returned without error; results.objs.sizie()=" << results.objs.size() << "results.is_truncated=" << results.is_truncated << ", marker=" << params.marker << dendl; count += results.objs.size(); for (const auto& entry : results.objs) { encode_json("entry", entry, formatter.get()); } formatter->flush(cout); } while (results.is_truncated && count < max_entries); ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": done" << dendl; formatter->close_section(); formatter->flush(cout); } /* have bucket_name */ } /* OPT::BUCKETS_LIST */ if (opt_cmd == OPT::BUCKET_RADOS_LIST) { RGWRadosList lister(static_cast<rgw::sal::RadosStore*>(driver), max_concurrent_ios, orphan_stale_secs, tenant); if (rgw_obj_fs) { lister.set_field_separator(*rgw_obj_fs); } if (bucket_name.empty()) { // yes_i_really_mean_it means continue with listing even if // there are indexless buckets ret = lister.run(dpp(), yes_i_really_mean_it); } else { ret = lister.run(dpp(), bucket_name); } if (ret < 0) { std::cerr << "ERROR: bucket radoslist failed to finish before " << "encountering error: " << cpp_strerror(-ret) << std::endl; std::cerr << "************************************" "************************************" << std::endl; std::cerr << "WARNING: THE RESULTS ARE NOT RELIABLE AND SHOULD NOT " << "BE USED IN DELETING ORPHANS" << std::endl; std::cerr << "************************************" "************************************" << std::endl; return -ret; } } if (opt_cmd == OPT::BUCKET_LAYOUT) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } const auto& bucket_info = bucket->get_info(); formatter->open_object_section("layout"); encode_json("layout", bucket_info.layout, formatter.get()); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BUCKET_STATS) { if (bucket_name.empty() && !bucket_id.empty()) { rgw_bucket bucket; if (!rgw_find_bucket_by_id(dpp(), driver->ctx(), driver, marker, bucket_id, &bucket)) { cerr << "failure: no such bucket id" << std::endl; return -ENOENT; } bucket_op.set_tenant(bucket.tenant); bucket_op.set_bucket_name(bucket.name); } bucket_op.set_fetch_stats(true); int r = RGWBucketAdminOp::info(driver, bucket_op, stream_flusher, null_yield, dpp()); if (r < 0) { cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl; return posix_errortrans(-r); } } if (opt_cmd == OPT::BUCKET_LINK) { bucket_op.set_bucket_id(bucket_id); bucket_op.set_new_bucket_name(new_bucket_name); string err; int r = RGWBucketAdminOp::link(driver, bucket_op, dpp(), null_yield, &err); if (r < 0) { cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl; return -r; } } if (opt_cmd == OPT::BUCKET_UNLINK) { int r = RGWBucketAdminOp::unlink(driver, bucket_op, dpp(), null_yield); if (r < 0) { cerr << "failure: " << cpp_strerror(-r) << std::endl; return -r; } } if (opt_cmd == OPT::BUCKET_SHARD_OBJECTS) { const auto prefix = opt_prefix ? *opt_prefix : "obj"s; if (!num_shards_specified) { cerr << "ERROR: num-shards must be specified." << std::endl; return EINVAL; } if (specified_shard_id) { if (shard_id >= num_shards) { cerr << "ERROR: shard-id must be less than num-shards." << std::endl; return EINVAL; } std::string obj; uint64_t ctr = 0; int shard; do { obj = fmt::format("{}{:0>20}", prefix, ctr); shard = RGWSI_BucketIndex_RADOS::bucket_shard_index(obj, num_shards); ++ctr; } while (shard != shard_id); formatter->open_object_section("shard_obj"); encode_json("obj", obj, formatter.get()); formatter->close_section(); formatter->flush(cout); } else { std::vector<std::string> objs(num_shards); for (uint64_t ctr = 0, shardsleft = num_shards; shardsleft > 0; ++ctr) { auto key = fmt::format("{}{:0>20}", prefix, ctr); auto shard = RGWSI_BucketIndex_RADOS::bucket_shard_index(key, num_shards); if (objs[shard].empty()) { objs[shard] = std::move(key); --shardsleft; } } formatter->open_object_section("shard_objs"); encode_json("objs", objs, formatter.get()); formatter->close_section(); formatter->flush(cout); } } if (opt_cmd == OPT::BUCKET_OBJECT_SHARD) { if (!num_shards_specified || object.empty()) { cerr << "ERROR: num-shards and object must be specified." << std::endl; return EINVAL; } auto shard = RGWSI_BucketIndex_RADOS::bucket_shard_index(object, num_shards); formatter->open_object_section("obj_shard"); encode_json("shard", shard, formatter.get()); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BUCKET_CHOWN) { if (bucket_name.empty()) { cerr << "ERROR: bucket name not specified" << std::endl; return EINVAL; } bucket_op.set_bucket_name(bucket_name); bucket_op.set_new_bucket_name(new_bucket_name); string err; int r = RGWBucketAdminOp::chown(driver, bucket_op, marker, dpp(), null_yield, &err); if (r < 0) { cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl; return -r; } } if (opt_cmd == OPT::LOG_LIST) { // filter by date? if (date.size() && date.size() != 10) { cerr << "bad date format for '" << date << "', expect YYYY-MM-DD" << std::endl; return EINVAL; } formatter->reset(); formatter->open_array_section("logs"); RGWAccessHandle h; int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_list_init(dpp(), date, &h); if (r == -ENOENT) { // no logs. } else { if (r < 0) { cerr << "log list: error " << r << std::endl; return -r; } while (true) { string name; int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_list_next(h, &name); if (r == -ENOENT) break; if (r < 0) { cerr << "log list: error " << r << std::endl; return -r; } formatter->dump_string("object", name); } } formatter->close_section(); formatter->flush(cout); cout << std::endl; } if (opt_cmd == OPT::LOG_SHOW || opt_cmd == OPT::LOG_RM) { if (object.empty() && (date.empty() || bucket_name.empty() || bucket_id.empty())) { cerr << "specify an object or a date, bucket and bucket-id" << std::endl; exit(1); } string oid; if (!object.empty()) { oid = object; } else { oid = date; oid += "-"; oid += bucket_id; oid += "-"; oid += bucket_name; } if (opt_cmd == OPT::LOG_SHOW) { RGWAccessHandle h; int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_show_init(dpp(), oid, &h); if (r < 0) { cerr << "error opening log " << oid << ": " << cpp_strerror(-r) << std::endl; return -r; } formatter->reset(); formatter->open_object_section("log"); struct rgw_log_entry entry; // peek at first entry to get bucket metadata r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_show_next(dpp(), h, &entry); if (r < 0) { cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl; return -r; } formatter->dump_string("bucket_id", entry.bucket_id); formatter->dump_string("bucket_owner", entry.bucket_owner.to_str()); formatter->dump_string("bucket", entry.bucket); uint64_t agg_time = 0; uint64_t agg_bytes_sent = 0; uint64_t agg_bytes_received = 0; uint64_t total_entries = 0; if (show_log_entries) formatter->open_array_section("log_entries"); do { using namespace std::chrono; uint64_t total_time = duration_cast<milliseconds>(entry.total_time).count(); agg_time += total_time; agg_bytes_sent += entry.bytes_sent; agg_bytes_received += entry.bytes_received; total_entries++; if (skip_zero_entries && entry.bytes_sent == 0 && entry.bytes_received == 0) goto next; if (show_log_entries) { rgw_format_ops_log_entry(entry, formatter.get()); formatter->flush(cout); } next: r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_show_next(dpp(), h, &entry); } while (r > 0); if (r < 0) { cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl; return -r; } if (show_log_entries) formatter->close_section(); if (show_log_sum) { formatter->open_object_section("log_sum"); formatter->dump_int("bytes_sent", agg_bytes_sent); formatter->dump_int("bytes_received", agg_bytes_received); formatter->dump_int("total_time", agg_time); formatter->dump_int("total_entries", total_entries); formatter->close_section(); } formatter->close_section(); formatter->flush(cout); cout << std::endl; } if (opt_cmd == OPT::LOG_RM) { int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_remove(dpp(), oid); if (r < 0) { cerr << "error removing log " << oid << ": " << cpp_strerror(-r) << std::endl; return -r; } } } if (opt_cmd == OPT::POOL_ADD) { if (pool_name.empty()) { cerr << "need to specify pool to add!" << std::endl; exit(1); } int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->add_bucket_placement(dpp(), pool, null_yield); if (ret < 0) cerr << "failed to add bucket placement: " << cpp_strerror(-ret) << std::endl; } if (opt_cmd == OPT::POOL_RM) { if (pool_name.empty()) { cerr << "need to specify pool to remove!" << std::endl; exit(1); } int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->remove_bucket_placement(dpp(), pool, null_yield); if (ret < 0) cerr << "failed to remove bucket placement: " << cpp_strerror(-ret) << std::endl; } if (opt_cmd == OPT::POOLS_LIST) { set<rgw_pool> pools; int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->list_placement_set(dpp(), pools, null_yield); if (ret < 0) { cerr << "could not list placement set: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->reset(); formatter->open_array_section("pools"); for (auto siter = pools.begin(); siter != pools.end(); ++siter) { formatter->open_object_section("pool"); formatter->dump_string("name", siter->to_str()); formatter->close_section(); } formatter->close_section(); formatter->flush(cout); cout << std::endl; } if (opt_cmd == OPT::USAGE_SHOW) { uint64_t start_epoch = 0; uint64_t end_epoch = (uint64_t)-1; int ret; if (!start_date.empty()) { ret = utime_t::parse_date(start_date, &start_epoch, NULL); if (ret < 0) { cerr << "ERROR: failed to parse start date" << std::endl; return 1; } } if (!end_date.empty()) { ret = utime_t::parse_date(end_date, &end_epoch, NULL); if (ret < 0) { cerr << "ERROR: failed to parse end date" << std::endl; return 1; } } if (!bucket_name.empty()) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } } ret = RGWUsage::show(dpp(), driver, user.get(), bucket.get(), start_epoch, end_epoch, show_log_entries, show_log_sum, &categories, stream_flusher); if (ret < 0) { cerr << "ERROR: failed to show usage" << std::endl; return 1; } } if (opt_cmd == OPT::USAGE_TRIM) { if (rgw::sal::User::empty(user) && bucket_name.empty() && start_date.empty() && end_date.empty() && !yes_i_really_mean_it) { cerr << "usage trim without user/date/bucket specified will remove *all* users data" << std::endl; cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return 1; } int ret; uint64_t start_epoch = 0; uint64_t end_epoch = (uint64_t)-1; if (!start_date.empty()) { ret = utime_t::parse_date(start_date, &start_epoch, NULL); if (ret < 0) { cerr << "ERROR: failed to parse start date" << std::endl; return 1; } } if (!end_date.empty()) { ret = utime_t::parse_date(end_date, &end_epoch, NULL); if (ret < 0) { cerr << "ERROR: failed to parse end date" << std::endl; return 1; } } if (!bucket_name.empty()) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } } ret = RGWUsage::trim(dpp(), driver, user.get(), bucket.get(), start_epoch, end_epoch, null_yield); if (ret < 0) { cerr << "ERROR: read_usage() returned ret=" << ret << std::endl; return 1; } } if (opt_cmd == OPT::USAGE_CLEAR) { if (!yes_i_really_mean_it) { cerr << "usage clear would remove *all* users usage data for all time" << std::endl; cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return 1; } ret = RGWUsage::clear(dpp(), driver, null_yield); if (ret < 0) { return ret; } } if (opt_cmd == OPT::OLH_GET || opt_cmd == OPT::OLH_READLOG) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } if (object.empty()) { cerr << "ERROR: object not specified" << std::endl; return EINVAL; } } if (opt_cmd == OPT::OLH_GET) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWOLHInfo olh; rgw_obj obj(bucket->get_key(), object); ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_olh(dpp(), bucket->get_info(), obj, &olh, null_yield); if (ret < 0) { cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("olh", olh, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::OLH_READLOG) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } map<uint64_t, vector<rgw_bucket_olh_log_entry> > log; bool is_truncated; std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object); RGWObjState *state; ret = obj->get_obj_state(dpp(), &state, null_yield); if (ret < 0) { return -ret; } ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bucket_index_read_olh_log(dpp(), bucket->get_info(), *state, obj->get_obj(), 0, &log, &is_truncated, null_yield); if (ret < 0) { cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->open_object_section("result"); encode_json("is_truncated", is_truncated, formatter.get()); encode_json("log", log, formatter.get()); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BI_GET) { if (bucket_name.empty()) { cerr << "ERROR: bucket name not specified" << std::endl; return EINVAL; } if (object.empty()) { cerr << "ERROR: object not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } rgw_obj obj(bucket->get_key(), object); if (!object_version.empty()) { obj.key.set_instance(object_version); } rgw_cls_bi_entry entry; ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_get(dpp(), bucket->get_info(), obj, bi_index_type, &entry, null_yield); if (ret < 0) { cerr << "ERROR: bi_get(): " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("entry", entry, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::BI_PUT) { if (bucket_name.empty()) { cerr << "ERROR: bucket name not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } rgw_cls_bi_entry entry; cls_rgw_obj_key key; ret = read_decode_json(infile, entry, &key); if (ret < 0) { return 1; } rgw_obj obj(bucket->get_key(), key); ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_put(dpp(), bucket->get_key(), obj, entry, null_yield); if (ret < 0) { cerr << "ERROR: bi_put(): " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::BI_LIST) { if (bucket_name.empty()) { cerr << "ERROR: bucket name not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } std::list<rgw_cls_bi_entry> entries; bool is_truncated; const auto& index = bucket->get_info().layout.current_index; const int max_shards = rgw::num_shards(index); if (max_entries < 0) { max_entries = 1000; } ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": max_entries=" << max_entries << ", index=" << index << ", max_shards=" << max_shards << dendl; formatter->open_array_section("entries"); int i = (specified_shard_id ? shard_id : 0); for (; i < max_shards; i++) { ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": starting shard=" << i << dendl; RGWRados::BucketShard bs(static_cast<rgw::sal::RadosStore*>(driver)->getRados()); int ret = bs.init(dpp(), bucket->get_info(), index, i, null_yield); marker.clear(); if (ret < 0) { cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << i << "): " << cpp_strerror(-ret) << std::endl; return -ret; } do { entries.clear(); // if object is specified, we use that as a filter to only retrieve some some entries ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_list(bs, object, marker, max_entries, &entries, &is_truncated, null_yield); if (ret < 0) { cerr << "ERROR: bi_list(): " << cpp_strerror(-ret) << std::endl; return -ret; } ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": bi_list() returned without error; entries.size()=" << entries.size() << ", is_truncated=" << is_truncated << ", marker=" << marker << dendl; for (const auto& entry : entries) { encode_json("entry", entry, formatter.get()); marker = entry.idx; } formatter->flush(cout); } while (is_truncated); formatter->flush(cout); if (specified_shard_id) { break; } } ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": done" << dendl; formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BI_PURGE) { if (bucket_name.empty()) { cerr << "ERROR: bucket name not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } std::unique_ptr<rgw::sal::Bucket> cur_bucket; ret = init_bucket(user.get(), tenant, bucket_name, string(), &cur_bucket); if (ret == -ENOENT) { // no bucket entrypoint } else if (ret < 0) { cerr << "ERROR: could not init current bucket info for bucket_name=" << bucket_name << ": " << cpp_strerror(-ret) << std::endl; return -ret; } else if (cur_bucket->get_bucket_id() == bucket->get_bucket_id() && !yes_i_really_mean_it) { cerr << "specified bucket instance points to a current bucket instance" << std::endl; cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return EINVAL; } const auto& index = bucket->get_info().layout.current_index; if (index.layout.type == rgw::BucketIndexType::Indexless) { cerr << "ERROR: indexless bucket has no index to purge" << std::endl; return EINVAL; } const int max_shards = rgw::num_shards(index); for (int i = 0; i < max_shards; i++) { RGWRados::BucketShard bs(static_cast<rgw::sal::RadosStore*>(driver)->getRados()); int ret = bs.init(dpp(), bucket->get_info(), index, i, null_yield); if (ret < 0) { cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << i << "): " << cpp_strerror(-ret) << std::endl; return -ret; } ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_remove(dpp(), bs); if (ret < 0) { cerr << "ERROR: failed to remove bucket index object: " << cpp_strerror(-ret) << std::endl; return -ret; } } } if (opt_cmd == OPT::OBJECT_PUT) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } if (object.empty()) { cerr << "ERROR: object not specified" << std::endl; return EINVAL; } RGWDataAccess data_access(driver); rgw_obj_key key(object, object_version); RGWDataAccess::BucketRef b; RGWDataAccess::ObjectRef obj; int ret = data_access.get_bucket(dpp(), tenant, bucket_name, bucket_id, &b, null_yield); if (ret < 0) { cerr << "ERROR: failed to init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = b->get_object(key, &obj); if (ret < 0) { cerr << "ERROR: failed to get object: " << cpp_strerror(-ret) << std::endl; return -ret; } bufferlist bl; ret = read_input(infile, bl); if (ret < 0) { cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl; } map<string, bufferlist> attrs; ret = obj->put(bl, attrs, dpp(), null_yield); if (ret < 0) { cerr << "ERROR: put object returned error: " << cpp_strerror(-ret) << std::endl; } } if (opt_cmd == OPT::OBJECT_RM) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } rgw_obj_key key(object, object_version); ret = rgw_remove_object(dpp(), driver, bucket.get(), key, null_yield); if (ret < 0) { cerr << "ERROR: object remove returned: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::OBJECT_REWRITE) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } if (object.empty()) { cerr << "ERROR: object not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object); obj->set_instance(object_version); bool need_rewrite = true; if (min_rewrite_stripe_size > 0) { ret = check_min_obj_stripe_size(driver, obj.get(), min_rewrite_stripe_size, &need_rewrite); if (ret < 0) { ldpp_dout(dpp(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << ret << dendl; } } if (need_rewrite) { RGWRados* store = static_cast<rgw::sal::RadosStore*>(driver)->getRados(); ret = store->rewrite_obj(bucket->get_info(), obj->get_obj(), dpp(), null_yield); if (ret < 0) { cerr << "ERROR: object rewrite returned: " << cpp_strerror(-ret) << std::endl; return -ret; } } else { ldpp_dout(dpp(), 20) << "skipped object" << dendl; } } // OPT::OBJECT_REWRITE if (opt_cmd == OPT::OBJECT_REINDEX) { if (bucket_name.empty()) { cerr << "ERROR: --bucket not specified." << std::endl; return EINVAL; } if (object.empty() && objects_file.empty()) { cerr << "ERROR: neither --object nor --objects-file specified." << std::endl; return EINVAL; } else if (!object.empty() && !objects_file.empty()) { cerr << "ERROR: both --object and --objects-file specified and only one is allowed." << std::endl; return EINVAL; } else if (!objects_file.empty() && !object_version.empty()) { cerr << "ERROR: cannot specify --object_version when --objects-file specified." << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << "." << std::endl; return -ret; } rgw::sal::RadosStore* rados_store = dynamic_cast<rgw::sal::RadosStore*>(driver); if (!rados_store) { cerr << "ERROR: this command can only work when the cluster has a RADOS backing store." << std::endl; return EPERM; } RGWRados* store = rados_store->getRados(); auto process = [&](const std::string& p_object, const std::string& p_object_version) -> int { std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(p_object); obj->set_instance(p_object_version); ret = store->reindex_obj(bucket->get_info(), obj->get_obj(), dpp(), null_yield); if (ret < 0) { return ret; } return 0; }; if (!object.empty()) { ret = process(object, object_version); if (ret < 0) { return -ret; } } else { std::ifstream file; file.open(objects_file); if (!file.is_open()) { std::cerr << "ERROR: unable to open objects-file \"" << objects_file << "\"." << std::endl; return ENOENT; } std::string obj_name; const std::string empty_version; while (std::getline(file, obj_name)) { ret = process(obj_name, empty_version); if (ret < 0) { std::cerr << "ERROR: while processing \"" << obj_name << "\", received " << cpp_strerror(-ret) << "." << std::endl; if (!yes_i_really_mean_it) { std::cerr << "NOTE: with *caution* you can use --yes-i-really-mean-it to push through errors and continue processing." << std::endl; return -ret; } } } // while } } // OPT::OBJECT_REINDEX if (opt_cmd == OPT::OBJECTS_EXPIRE) { if (!static_cast<rgw::sal::RadosStore*>(driver)->getRados()->process_expire_objects(dpp(), null_yield)) { cerr << "ERROR: process_expire_objects() processing returned error." << std::endl; return 1; } } if (opt_cmd == OPT::OBJECTS_EXPIRE_STALE_LIST) { ret = RGWBucketAdminOp::fix_obj_expiry(driver, bucket_op, stream_flusher, dpp(), null_yield, true); if (ret < 0) { cerr << "ERROR: listing returned " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::OBJECTS_EXPIRE_STALE_RM) { ret = RGWBucketAdminOp::fix_obj_expiry(driver, bucket_op, stream_flusher, dpp(), null_yield, false); if (ret < 0) { cerr << "ERROR: removing returned " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::BUCKET_REWRITE) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } uint64_t start_epoch = 0; uint64_t end_epoch = 0; if (!end_date.empty()) { int ret = utime_t::parse_date(end_date, &end_epoch, NULL); if (ret < 0) { cerr << "ERROR: failed to parse end date" << std::endl; return EINVAL; } } if (!start_date.empty()) { int ret = utime_t::parse_date(start_date, &start_epoch, NULL); if (ret < 0) { cerr << "ERROR: failed to parse start date" << std::endl; return EINVAL; } } bool is_truncated = true; bool cls_filtered = true; rgw_obj_index_key marker; string empty_prefix; string empty_delimiter; formatter->open_object_section("result"); formatter->dump_string("bucket", bucket_name); formatter->open_array_section("objects"); constexpr uint32_t NUM_ENTRIES = 1000; uint16_t expansion_factor = 1; while (is_truncated) { RGWRados::ent_map_t result; result.reserve(NUM_ENTRIES); const auto& current_index = bucket->get_info().layout.current_index; int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->cls_bucket_list_ordered( dpp(), bucket->get_info(), current_index, RGW_NO_SHARD, marker, empty_prefix, empty_delimiter, NUM_ENTRIES, true, expansion_factor, result, &is_truncated, &cls_filtered, &marker, null_yield, rgw_bucket_object_check_filter); if (r < 0 && r != -ENOENT) { cerr << "ERROR: failed operation r=" << r << std::endl; } else if (r == -ENOENT) { break; } if (result.size() < NUM_ENTRIES / 8) { ++expansion_factor; } else if (result.size() > NUM_ENTRIES * 7 / 8 && expansion_factor > 1) { --expansion_factor; } for (auto iter = result.begin(); iter != result.end(); ++iter) { rgw_obj_key key = iter->second.key; rgw_bucket_dir_entry& entry = iter->second; formatter->open_object_section("object"); formatter->dump_string("name", key.name); formatter->dump_string("instance", key.instance); formatter->dump_int("size", entry.meta.size); utime_t ut(entry.meta.mtime); ut.gmtime(formatter->dump_stream("mtime")); if ((entry.meta.size < min_rewrite_size) || (entry.meta.size > max_rewrite_size) || (start_epoch > 0 && start_epoch > (uint64_t)ut.sec()) || (end_epoch > 0 && end_epoch < (uint64_t)ut.sec())) { formatter->dump_string("status", "Skipped"); } else { std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(key); bool need_rewrite = true; if (min_rewrite_stripe_size > 0) { r = check_min_obj_stripe_size(driver, obj.get(), min_rewrite_stripe_size, &need_rewrite); if (r < 0) { ldpp_dout(dpp(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << r << dendl; } } if (!need_rewrite) { formatter->dump_string("status", "Skipped"); } else { RGWRados* store = static_cast<rgw::sal::RadosStore*>(driver)->getRados(); r = store->rewrite_obj(bucket->get_info(), obj->get_obj(), dpp(), null_yield); if (r == 0) { formatter->dump_string("status", "Success"); } else { formatter->dump_string("status", cpp_strerror(-r)); } } } formatter->dump_int("flags", entry.flags); formatter->close_section(); formatter->flush(cout); } } formatter->close_section(); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BUCKET_RESHARD) { int ret = check_reshard_bucket_params(driver, bucket_name, tenant, bucket_id, num_shards_specified, num_shards, yes_i_really_mean_it, &bucket); if (ret < 0) { return ret; } auto zone_svc = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone; if (!zone_svc->can_reshard()) { const auto& zonegroup = zone_svc->get_zonegroup(); std::cerr << "The zonegroup '" << zonegroup.get_name() << "' does not " "have the resharding feature enabled." << std::endl; return ENOTSUP; } if (!RGWBucketReshard::can_reshard(bucket->get_info(), zone_svc) && !yes_i_really_mean_it) { std::cerr << "Bucket '" << bucket->get_name() << "' already has too many " "log generations (" << bucket->get_info().layout.logs.size() << ") " "from previous reshards that peer zones haven't finished syncing. " "Resharding is not recommended until the old generations sync, but " "you can force a reshard with --yes-i-really-mean-it." << std::endl; return EINVAL; } RGWBucketReshard br(static_cast<rgw::sal::RadosStore*>(driver), bucket->get_info(), bucket->get_attrs(), nullptr /* no callback */); #define DEFAULT_RESHARD_MAX_ENTRIES 1000 if (max_entries < 1) { max_entries = DEFAULT_RESHARD_MAX_ENTRIES; } ReshardFaultInjector fault; if (inject_error_at) { const int code = -inject_error_code.value_or(EIO); fault.inject(*inject_error_at, InjectError{code, dpp()}); } else if (inject_abort_at) { fault.inject(*inject_abort_at, InjectAbort{}); } ret = br.execute(num_shards, fault, max_entries, dpp(), null_yield, verbose, &cout, formatter.get()); return -ret; } if (opt_cmd == OPT::RESHARD_ADD) { int ret = check_reshard_bucket_params(driver, bucket_name, tenant, bucket_id, num_shards_specified, num_shards, yes_i_really_mean_it, &bucket); if (ret < 0) { return ret; } int num_source_shards = rgw::current_num_shards(bucket->get_info().layout); RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), dpp()); cls_rgw_reshard_entry entry; entry.time = real_clock::now(); entry.tenant = tenant; entry.bucket_name = bucket_name; entry.bucket_id = bucket->get_info().bucket.bucket_id; entry.old_num_shards = num_source_shards; entry.new_num_shards = num_shards; return reshard.add(dpp(), entry, null_yield); } if (opt_cmd == OPT::RESHARD_LIST) { int ret; int count = 0; if (max_entries < 0) { max_entries = 1000; } int num_logshards = driver->ctx()->_conf.get_val<uint64_t>("rgw_reshard_num_logs"); RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), dpp()); formatter->open_array_section("reshard"); for (int i = 0; i < num_logshards; i++) { bool is_truncated = true; std::string marker; do { std::list<cls_rgw_reshard_entry> entries; ret = reshard.list(dpp(), i, marker, max_entries - count, entries, &is_truncated); if (ret < 0) { cerr << "Error listing resharding buckets: " << cpp_strerror(-ret) << std::endl; return ret; } for (const auto& entry : entries) { encode_json("entry", entry, formatter.get()); } if (is_truncated) { entries.crbegin()->get_key(&marker); // last entry's key becomes marker } count += entries.size(); formatter->flush(cout); } while (is_truncated && count < max_entries); if (count >= max_entries) { break; } } formatter->close_section(); formatter->flush(cout); return 0; } if (opt_cmd == OPT::RESHARD_STATUS) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWBucketReshard br(static_cast<rgw::sal::RadosStore*>(driver), bucket->get_info(), bucket->get_attrs(), nullptr /* no callback */); list<cls_rgw_bucket_instance_entry> status; int r = br.get_status(dpp(), &status); if (r < 0) { cerr << "ERROR: could not get resharding status for bucket " << bucket_name << std::endl; return -r; } show_reshard_status(status, formatter.get()); } if (opt_cmd == OPT::RESHARD_PROCESS) { RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), true, &cout); int ret = reshard.process_all_logshards(dpp(), null_yield); if (ret < 0) { cerr << "ERROR: failed to process reshard logs, error=" << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::RESHARD_CANCEL) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } bool bucket_initable = true; ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { if (yes_i_really_mean_it) { bucket_initable = false; } else { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << "; if you want to cancel the reshard request nonetheless, please " "use the --yes-i-really-mean-it option" << std::endl; return -ret; } } bool resharding_underway = true; if (bucket_initable) { // we did not encounter an error, so let's work with the bucket RGWBucketReshard br(static_cast<rgw::sal::RadosStore*>(driver), bucket->get_info(), bucket->get_attrs(), nullptr /* no callback */); int ret = br.cancel(dpp(), null_yield); if (ret < 0) { if (ret == -EBUSY) { cerr << "There is ongoing resharding, please retry after " << driver->ctx()->_conf.get_val<uint64_t>("rgw_reshard_bucket_lock_duration") << " seconds." << std::endl; return -ret; } else if (ret == -EINVAL) { resharding_underway = false; // we can continue and try to unschedule } else { cerr << "Error cancelling bucket \"" << bucket_name << "\" resharding: " << cpp_strerror(-ret) << std::endl; return -ret; } } } RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), dpp()); cls_rgw_reshard_entry entry; entry.tenant = tenant; entry.bucket_name = bucket_name; ret = reshard.remove(dpp(), entry, null_yield); if (ret == -ENOENT) { if (!resharding_underway) { cerr << "Error, bucket \"" << bucket_name << "\" is neither undergoing resharding nor scheduled to undergo " "resharding." << std::endl; return EINVAL; } else { // we cancelled underway resharding above, so we're good return 0; } } else if (ret < 0) { cerr << "Error in updating reshard log with bucket \"" << bucket_name << "\": " << cpp_strerror(-ret) << std::endl; return -ret; } } // OPT_RESHARD_CANCEL if (opt_cmd == OPT::OBJECT_UNLINK) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } list<rgw_obj_index_key> oid_list; rgw_obj_key key(object, object_version); rgw_obj_index_key index_key; key.get_index_key(&index_key); oid_list.push_back(index_key); // note: under rados this removes directly from rados index objects ret = bucket->remove_objs_from_index(dpp(), oid_list); if (ret < 0) { cerr << "ERROR: remove_obj_from_index() returned error: " << cpp_strerror(-ret) << std::endl; return 1; } } if (opt_cmd == OPT::OBJECT_STAT) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object); obj->set_instance(object_version); ret = obj->get_obj_attrs(null_yield, dpp()); if (ret < 0) { cerr << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << std::endl; return 1; } formatter->open_object_section("object_metadata"); formatter->dump_string("name", object); formatter->dump_unsigned("size", obj->get_obj_size()); map<string, bufferlist>::iterator iter; map<string, bufferlist> other_attrs; for (iter = obj->get_attrs().begin(); iter != obj->get_attrs().end(); ++iter) { bufferlist& bl = iter->second; bool handled = false; if (iter->first == RGW_ATTR_MANIFEST) { handled = decode_dump<RGWObjManifest>("manifest", bl, formatter.get()); } else if (iter->first == RGW_ATTR_ACL) { handled = decode_dump<RGWAccessControlPolicy>("policy", bl, formatter.get()); } else if (iter->first == RGW_ATTR_ID_TAG) { handled = dump_string("tag", bl, formatter.get()); } else if (iter->first == RGW_ATTR_ETAG) { handled = dump_string("etag", bl, formatter.get()); } else if (iter->first == RGW_ATTR_COMPRESSION) { handled = decode_dump<RGWCompressionInfo>("compression", bl, formatter.get()); } else if (iter->first == RGW_ATTR_DELETE_AT) { handled = decode_dump<utime_t>("delete_at", bl, formatter.get()); } else if (iter->first == RGW_ATTR_TORRENT) { // contains bencoded binary data which shouldn't be output directly // TODO: decode torrent info for display as json? formatter->dump_string("torrent", "<contains binary data>"); handled = true; } if (!handled) other_attrs[iter->first] = bl; } formatter->open_object_section("attrs"); for (iter = other_attrs.begin(); iter != other_attrs.end(); ++iter) { dump_string(iter->first.c_str(), iter->second, formatter.get()); } formatter->close_section(); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BUCKET_CHECK) { if (check_head_obj_locator) { if (bucket_name.empty()) { cerr << "ERROR: need to specify bucket name" << std::endl; return EINVAL; } do_check_object_locator(tenant, bucket_name, fix, remove_bad, formatter.get()); } else { RGWBucketAdminOp::check_index(driver, bucket_op, stream_flusher, null_yield, dpp()); } } if (opt_cmd == OPT::BUCKET_RM) { if (!inconsistent_index) { RGWBucketAdminOp::remove_bucket(driver, bucket_op, null_yield, dpp(), bypass_gc, true); } else { if (!yes_i_really_mean_it) { cerr << "using --inconsistent_index can corrupt the bucket index " << std::endl << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return 1; } RGWBucketAdminOp::remove_bucket(driver, bucket_op, null_yield, dpp(), bypass_gc, false); } } if (opt_cmd == OPT::GC_LIST) { int index = 0; bool truncated; bool processing_queue = false; formatter->open_array_section("entries"); do { list<cls_rgw_gc_obj_info> result; int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->list_gc_objs(&index, marker, 1000, !include_all, result, &truncated, processing_queue); if (ret < 0) { cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret) << std::endl; return 1; } list<cls_rgw_gc_obj_info>::iterator iter; for (iter = result.begin(); iter != result.end(); ++iter) { cls_rgw_gc_obj_info& info = *iter; formatter->open_object_section("chain_info"); formatter->dump_string("tag", info.tag); formatter->dump_stream("time") << info.time; formatter->open_array_section("objs"); list<cls_rgw_obj>::iterator liter; cls_rgw_obj_chain& chain = info.chain; for (liter = chain.objs.begin(); liter != chain.objs.end(); ++liter) { cls_rgw_obj& obj = *liter; encode_json("obj", obj, formatter.get()); } formatter->close_section(); // objs formatter->close_section(); // obj_chain formatter->flush(cout); } } while (truncated); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::GC_PROCESS) { rgw::sal::RadosStore* rados_store = dynamic_cast<rgw::sal::RadosStore*>(driver); if (!rados_store) { cerr << "WARNING: this command can only work when the cluster has a RADOS backing store." << std::endl; return 0; } RGWRados* store = rados_store->getRados(); int ret = store->process_gc(!include_all, null_yield); if (ret < 0) { cerr << "ERROR: gc processing returned error: " << cpp_strerror(-ret) << std::endl; return 1; } } if (opt_cmd == OPT::LC_LIST) { formatter->open_array_section("lifecycle_list"); vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>> bucket_lc_map; string marker; int index{0}; #define MAX_LC_LIST_ENTRIES 100 if (max_entries < 0) { max_entries = MAX_LC_LIST_ENTRIES; } do { int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->list_lc_progress(marker, max_entries, bucket_lc_map, index); if (ret < 0) { cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret) << std::endl; return 1; } for (const auto& entry : bucket_lc_map) { formatter->open_object_section("bucket_lc_info"); formatter->dump_string("bucket", entry->get_bucket()); formatter->dump_string("shard", entry->get_oid()); char exp_buf[100]; time_t t{time_t(entry->get_start_time())}; if (std::strftime( exp_buf, sizeof(exp_buf), "%a, %d %b %Y %T %Z", std::gmtime(&t))) { formatter->dump_string("started", exp_buf); } string lc_status = LC_STATUS[entry->get_status()]; formatter->dump_string("status", lc_status); formatter->close_section(); // objs formatter->flush(cout); } } while (!bucket_lc_map.empty()); formatter->close_section(); //lifecycle list formatter->flush(cout); } if (opt_cmd == OPT::LC_GET) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } RGWLifecycleConfiguration config; ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } auto aiter = bucket->get_attrs().find(RGW_ATTR_LC); if (aiter == bucket->get_attrs().end()) { return -ENOENT; } bufferlist::const_iterator iter{&aiter->second}; try { config.decode(iter); } catch (const buffer::error& e) { cerr << "ERROR: decode life cycle config failed" << std::endl; return -EIO; } encode_json("result", config, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::LC_PROCESS) { if ((! bucket_name.empty()) || (! bucket_id.empty())) { int ret = init_bucket(nullptr, tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return ret; } } int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->process_lc(bucket); if (ret < 0) { cerr << "ERROR: lc processing returned error: " << cpp_strerror(-ret) << std::endl; return 1; } } if (opt_cmd == OPT::LC_RESHARD_FIX) { ret = RGWBucketAdminOp::fix_lc_shards(driver, bucket_op, stream_flusher, dpp(), null_yield); if (ret < 0) { cerr << "ERROR: fixing lc shards: " << cpp_strerror(-ret) << std::endl; } } if (opt_cmd == OPT::ORPHANS_FIND) { if (!yes_i_really_mean_it) { cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; " << "accidental removal of active objects cannot be reversed; " << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return EINVAL; } else { cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool" << std::endl; } RGWOrphanSearch search(static_cast<rgw::sal::RadosStore*>(driver), max_concurrent_ios, orphan_stale_secs); if (job_id.empty()) { cerr << "ERROR: --job-id not specified" << std::endl; return EINVAL; } if (pool_name.empty()) { cerr << "ERROR: --pool not specified" << std::endl; return EINVAL; } RGWOrphanSearchInfo info; info.pool = pool; info.job_name = job_id; info.num_shards = num_shards; int ret = search.init(dpp(), job_id, &info, detail); if (ret < 0) { cerr << "could not init search, ret=" << ret << std::endl; return -ret; } ret = search.run(dpp()); if (ret < 0) { return -ret; } } if (opt_cmd == OPT::ORPHANS_FINISH) { if (!yes_i_really_mean_it) { cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; " << "accidental removal of active objects cannot be reversed; " << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return EINVAL; } else { cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool" << std::endl; } RGWOrphanSearch search(static_cast<rgw::sal::RadosStore*>(driver), max_concurrent_ios, orphan_stale_secs); if (job_id.empty()) { cerr << "ERROR: --job-id not specified" << std::endl; return EINVAL; } int ret = search.init(dpp(), job_id, NULL); if (ret < 0) { if (ret == -ENOENT) { cerr << "job not found" << std::endl; } return -ret; } ret = search.finish(); if (ret < 0) { return -ret; } } if (opt_cmd == OPT::ORPHANS_LIST_JOBS){ if (!yes_i_really_mean_it) { cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; " << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl; return EINVAL; } else { cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool" << std::endl; } RGWOrphanStore orphan_store(static_cast<rgw::sal::RadosStore*>(driver)); int ret = orphan_store.init(dpp()); if (ret < 0){ cerr << "connection to cluster failed!" << std::endl; return -ret; } map <string,RGWOrphanSearchState> m; ret = orphan_store.list_jobs(m); if (ret < 0) { cerr << "job list failed" << std::endl; return -ret; } formatter->open_array_section("entries"); for (const auto &it: m){ if (!extra_info){ formatter->dump_string("job-id",it.first); } else { encode_json("orphan_search_state", it.second, formatter.get()); } } formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::USER_CHECK) { check_bad_user_bucket_mapping(driver, *user.get(), fix, null_yield, dpp()); } if (opt_cmd == OPT::USER_STATS) { if (rgw::sal::User::empty(user)) { cerr << "ERROR: uid not specified" << std::endl; return EINVAL; } if (reset_stats) { if (!bucket_name.empty()) { cerr << "ERROR: --reset-stats does not work on buckets and " "bucket specified" << std::endl; return EINVAL; } if (sync_stats) { cerr << "ERROR: sync-stats includes the reset-stats functionality, " "so at most one of the two should be specified" << std::endl; return EINVAL; } ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->user->reset_bucket_stats(dpp(), user->get_id(), null_yield); if (ret < 0) { cerr << "ERROR: could not reset user stats: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (sync_stats) { if (!bucket_name.empty()) { int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = bucket->sync_user_stats(dpp(), null_yield); if (ret < 0) { cerr << "ERROR: could not sync bucket stats: " << cpp_strerror(-ret) << std::endl; return -ret; } } else { int ret = rgw_user_sync_all_stats(dpp(), driver, user.get(), null_yield); if (ret < 0) { cerr << "ERROR: could not sync user stats: " << cpp_strerror(-ret) << std::endl; return -ret; } } } constexpr bool omit_utilized_stats = false; RGWStorageStats stats(omit_utilized_stats); ceph::real_time last_stats_sync; ceph::real_time last_stats_update; int ret = user->read_stats(dpp(), null_yield, &stats, &last_stats_sync, &last_stats_update); if (ret < 0) { if (ret == -ENOENT) { /* in case of ENOENT */ cerr << "User has not been initialized or user does not exist" << std::endl; } else { cerr << "ERROR: can't read user: " << cpp_strerror(ret) << std::endl; } return -ret; } { Formatter::ObjectSection os(*formatter, "result"); encode_json("stats", stats, formatter.get()); utime_t last_sync_ut(last_stats_sync); encode_json("last_stats_sync", last_sync_ut, formatter.get()); utime_t last_update_ut(last_stats_update); encode_json("last_stats_update", last_update_ut, formatter.get()); } formatter->flush(cout); } if (opt_cmd == OPT::METADATA_GET) { int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->get(metadata_key, formatter.get(), null_yield, dpp()); if (ret < 0) { cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->flush(cout); } if (opt_cmd == OPT::METADATA_PUT) { bufferlist bl; int ret = read_input(infile, bl); if (ret < 0) { cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl; return -ret; } ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->put(metadata_key, bl, null_yield, dpp(), RGWMDLogSyncType::APPLY_ALWAYS, false); if (ret < 0) { cerr << "ERROR: can't put key: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::METADATA_RM) { int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->remove(metadata_key, null_yield, dpp()); if (ret < 0) { cerr << "ERROR: can't remove key: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::METADATA_LIST || opt_cmd == OPT::USER_LIST) { if (opt_cmd == OPT::USER_LIST) { metadata_key = "user"; } void *handle; int max = 1000; int ret = driver->meta_list_keys_init(dpp(), metadata_key, marker, &handle); if (ret < 0) { cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl; return -ret; } bool truncated; uint64_t count = 0; if (max_entries_specified) { formatter->open_object_section("result"); } formatter->open_array_section("keys"); uint64_t left; do { list<string> keys; left = (max_entries_specified ? max_entries - count : max); ret = driver->meta_list_keys_next(dpp(), handle, left, keys, &truncated); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: lists_keys_next(): " << cpp_strerror(-ret) << std::endl; return -ret; } if (ret != -ENOENT) { for (list<string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) { formatter->dump_string("key", *iter); ++count; } formatter->flush(cout); } } while (truncated && left > 0); formatter->close_section(); if (max_entries_specified) { encode_json("truncated", truncated, formatter.get()); encode_json("count", count, formatter.get()); if (truncated) { encode_json("marker", driver->meta_get_marker(handle), formatter.get()); } formatter->close_section(); } formatter->flush(cout); driver->meta_list_keys_complete(handle); } if (opt_cmd == OPT::MDLOG_LIST) { if (!start_date.empty()) { std::cerr << "start-date not allowed." << std::endl; return -EINVAL; } if (!end_date.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!end_marker.empty()) { std::cerr << "end-marker not allowed." << std::endl; return -EINVAL; } if (!start_marker.empty()) { if (marker.empty()) { marker = start_marker; } else { std::cerr << "start-marker and marker not both allowed." << std::endl; return -EINVAL; } } int i = (specified_shard_id ? shard_id : 0); if (period_id.empty()) { // use realm's current period RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 ) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } period_id = realm.current_period; std::cerr << "No --period given, using current period=" << period_id << std::endl; } RGWMetadataLog *meta_log = static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->get_log(period_id); formatter->open_array_section("entries"); for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) { void *handle; list<cls_log_entry> entries; meta_log->init_list_entries(i, {}, {}, marker, &handle); bool truncated; do { int ret = meta_log->list_entries(dpp(), handle, 1000, entries, NULL, &truncated); if (ret < 0) { cerr << "ERROR: meta_log->list_entries(): " << cpp_strerror(-ret) << std::endl; return -ret; } for (list<cls_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) { cls_log_entry& entry = *iter; static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->dump_log_entry(entry, formatter.get()); } formatter->flush(cout); } while (truncated); meta_log->complete_list_entries(handle); if (specified_shard_id) break; } formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::MDLOG_STATUS) { int i = (specified_shard_id ? shard_id : 0); if (period_id.empty()) { // use realm's current period RGWRealm realm; int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(), realm_id, realm_name, realm); if (ret < 0 ) { cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl; return -ret; } period_id = realm.current_period; std::cerr << "No --period given, using current period=" << period_id << std::endl; } RGWMetadataLog *meta_log = static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->get_log(period_id); formatter->open_array_section("entries"); for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) { RGWMetadataLogInfo info; meta_log->get_info(dpp(), i, &info); ::encode_json("info", info, formatter.get()); if (specified_shard_id) break; } formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::MDLOG_AUTOTRIM) { // need a full history for purging old mdlog periods static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->init_oldest_log_period(null_yield, dpp()); RGWCoroutinesManager crs(driver->ctx(), driver->get_cr_registry()); RGWHTTPManager http(driver->ctx(), crs.get_completion_mgr()); int ret = http.start(); if (ret < 0) { cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl; return -ret; } auto num_shards = g_conf()->rgw_md_log_max_shards; auto mltcr = create_admin_meta_log_trim_cr( dpp(), static_cast<rgw::sal::RadosStore*>(driver), &http, num_shards); if (!mltcr) { cerr << "Cluster misconfigured! Unable to trim." << std::endl; return -EIO; } ret = crs.run(dpp(), mltcr); if (ret < 0) { cerr << "automated mdlog trim failed with " << cpp_strerror(ret) << std::endl; return -ret; } } if (opt_cmd == OPT::MDLOG_TRIM) { if (!start_date.empty()) { std::cerr << "start-date not allowed." << std::endl; return -EINVAL; } if (!end_date.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!start_marker.empty()) { std::cerr << "start-marker not allowed." << std::endl; return -EINVAL; } if (!end_marker.empty()) { if (marker.empty()) { marker = end_marker; } else { std::cerr << "end-marker and marker not both allowed." << std::endl; return -EINVAL; } } if (!specified_shard_id) { cerr << "ERROR: shard-id must be specified for trim operation" << std::endl; return EINVAL; } if (marker.empty()) { cerr << "ERROR: marker must be specified for trim operation" << std::endl; return EINVAL; } if (period_id.empty()) { std::cerr << "missing --period argument" << std::endl; return EINVAL; } RGWMetadataLog *meta_log = static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->get_log(period_id); // trim until -ENODATA do { ret = meta_log->trim(dpp(), shard_id, {}, {}, {}, marker); } while (ret == 0); if (ret < 0 && ret != -ENODATA) { cerr << "ERROR: meta_log->trim(): " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::SYNC_INFO) { sync_info(opt_effective_zone_id, opt_bucket, zone_formatter.get()); } if (opt_cmd == OPT::SYNC_STATUS) { sync_status(formatter.get()); } if (opt_cmd == OPT::METADATA_SYNC_STATUS) { RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor()); int ret = sync.init(dpp()); if (ret < 0) { cerr << "ERROR: sync.init() returned ret=" << ret << std::endl; return -ret; } rgw_meta_sync_status sync_status; ret = sync.read_sync_status(dpp(), &sync_status); if (ret < 0) { cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl; return -ret; } formatter->open_object_section("summary"); encode_json("sync_status", sync_status, formatter.get()); uint64_t full_total = 0; uint64_t full_complete = 0; for (auto marker_iter : sync_status.sync_markers) { full_total += marker_iter.second.total_entries; if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) { full_complete += marker_iter.second.pos; } else { full_complete += marker_iter.second.total_entries; } } formatter->open_object_section("full_sync"); encode_json("total", full_total, formatter.get()); encode_json("complete", full_complete, formatter.get()); formatter->close_section(); formatter->dump_string("current_time", to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms)); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::METADATA_SYNC_INIT) { RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor()); int ret = sync.init(dpp()); if (ret < 0) { cerr << "ERROR: sync.init() returned ret=" << ret << std::endl; return -ret; } ret = sync.init_sync_status(dpp()); if (ret < 0) { cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl; return -ret; } } if (opt_cmd == OPT::METADATA_SYNC_RUN) { RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor()); int ret = sync.init(dpp()); if (ret < 0) { cerr << "ERROR: sync.init() returned ret=" << ret << std::endl; return -ret; } ret = sync.run(dpp(), null_yield); if (ret < 0) { cerr << "ERROR: sync.run() returned ret=" << ret << std::endl; return -ret; } } if (opt_cmd == OPT::DATA_SYNC_STATUS) { if (source_zone.empty()) { cerr << "ERROR: source zone not specified" << std::endl; return EINVAL; } RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr); int ret = sync.init(dpp()); if (ret < 0) { cerr << "ERROR: sync.init() returned ret=" << ret << std::endl; return -ret; } rgw_data_sync_status sync_status; if (specified_shard_id) { set<string> pending_buckets; set<string> recovering_buckets; rgw_data_sync_marker sync_marker; ret = sync.read_shard_status(dpp(), shard_id, pending_buckets, recovering_buckets, &sync_marker, max_entries_specified ? max_entries : 20); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: sync.read_shard_status() returned ret=" << ret << std::endl; return -ret; } formatter->open_object_section("summary"); encode_json("shard_id", shard_id, formatter.get()); encode_json("marker", sync_marker, formatter.get()); encode_json("pending_buckets", pending_buckets, formatter.get()); encode_json("recovering_buckets", recovering_buckets, formatter.get()); formatter->dump_string("current_time", to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms)); formatter->close_section(); formatter->flush(cout); } else { ret = sync.read_sync_status(dpp(), &sync_status); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl; return -ret; } formatter->open_object_section("summary"); encode_json("sync_status", sync_status, formatter.get()); uint64_t full_total = 0; uint64_t full_complete = 0; for (auto marker_iter : sync_status.sync_markers) { full_total += marker_iter.second.total_entries; if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) { full_complete += marker_iter.second.pos; } else { full_complete += marker_iter.second.total_entries; } } formatter->open_object_section("full_sync"); encode_json("total", full_total, formatter.get()); encode_json("complete", full_complete, formatter.get()); formatter->close_section(); formatter->dump_string("current_time", to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms)); formatter->close_section(); formatter->flush(cout); } } if (opt_cmd == OPT::DATA_SYNC_INIT) { if (source_zone.empty()) { cerr << "ERROR: source zone not specified" << std::endl; return EINVAL; } RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr); int ret = sync.init(dpp()); if (ret < 0) { cerr << "ERROR: sync.init() returned ret=" << ret << std::endl; return -ret; } ret = sync.init_sync_status(dpp()); if (ret < 0) { cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl; return -ret; } } if (opt_cmd == OPT::DATA_SYNC_RUN) { if (source_zone.empty()) { cerr << "ERROR: source zone not specified" << std::endl; return EINVAL; } RGWSyncModuleInstanceRef sync_module; int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager()->create_instance(dpp(), g_ceph_context, static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone().tier_type, static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_params().tier_config, &sync_module); if (ret < 0) { ldpp_dout(dpp(), -1) << "ERROR: failed to init sync module instance, ret=" << ret << dendl; return ret; } RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr, sync_module); ret = sync.init(dpp()); if (ret < 0) { cerr << "ERROR: sync.init() returned ret=" << ret << std::endl; return -ret; } ret = sync.run(dpp()); if (ret < 0) { cerr << "ERROR: sync.run() returned ret=" << ret << std::endl; return -ret; } } if (opt_cmd == OPT::BUCKET_SYNC_INIT) { if (source_zone.empty()) { cerr << "ERROR: source zone not specified" << std::endl; return EINVAL; } if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket_for_sync(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } auto opt_sb = opt_source_bucket; if (opt_sb && opt_sb->bucket_id.empty()) { string sbid; std::unique_ptr<rgw::sal::Bucket> sbuck; int ret = init_bucket_for_sync(user.get(), opt_sb->tenant, opt_sb->name, sbid, &sbuck); if (ret < 0) { return -ret; } opt_sb = sbuck->get_key(); } auto sync = RGWBucketPipeSyncStatusManager::construct( dpp(), static_cast<rgw::sal::RadosStore*>(driver), source_zone, opt_sb, bucket->get_key(), extra_info ? &std::cout : nullptr); if (!sync) { cerr << "ERROR: sync.init() returned error=" << sync.error() << std::endl; return -sync.error(); } ret = (*sync)->init_sync_status(dpp()); if (ret < 0) { cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl; return -ret; } } if (opt_cmd == OPT::BUCKET_SYNC_CHECKPOINT) { std::optional<rgw_zone_id> opt_source_zone; if (!source_zone.empty()) { opt_source_zone = source_zone; } if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } if (!static_cast<rgw::sal::RadosStore*>(driver)->ctl()->bucket->bucket_imports_data(bucket->get_key(), null_yield, dpp())) { std::cout << "Sync is disabled for bucket " << bucket_name << std::endl; return 0; } RGWBucketSyncPolicyHandlerRef handler; ret = driver->get_sync_policy_handler(dpp(), std::nullopt, bucket->get_key(), &handler, null_yield); if (ret < 0) { std::cerr << "ERROR: failed to get policy handler for bucket (" << bucket << "): r=" << ret << ": " << cpp_strerror(-ret) << std::endl; return -ret; } auto timeout_at = ceph::coarse_mono_clock::now() + opt_timeout_sec; ret = rgw_bucket_sync_checkpoint(dpp(), static_cast<rgw::sal::RadosStore*>(driver), *handler, bucket->get_info(), opt_source_zone, opt_source_bucket, opt_retry_delay_ms, timeout_at); if (ret < 0) { ldpp_dout(dpp(), -1) << "bucket sync checkpoint failed: " << cpp_strerror(ret) << dendl; return -ret; } } if ((opt_cmd == OPT::BUCKET_SYNC_DISABLE) || (opt_cmd == OPT::BUCKET_SYNC_ENABLE)) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } if (opt_cmd == OPT::BUCKET_SYNC_DISABLE) { bucket_op.set_sync_bucket(false); } else { bucket_op.set_sync_bucket(true); } bucket_op.set_tenant(tenant); string err_msg; ret = RGWBucketAdminOp::sync_bucket(driver, bucket_op, dpp(), null_yield, &err_msg); if (ret < 0) { cerr << err_msg << std::endl; return -ret; } } if (opt_cmd == OPT::BUCKET_SYNC_INFO) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } bucket_sync_info(driver, bucket->get_info(), std::cout); } if (opt_cmd == OPT::BUCKET_SYNC_STATUS) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } bucket_sync_status(driver, bucket->get_info(), source_zone, opt_source_bucket, std::cout); } if (opt_cmd == OPT::BUCKET_SYNC_MARKERS) { if (source_zone.empty()) { cerr << "ERROR: source zone not specified" << std::endl; return EINVAL; } if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket_for_sync(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } auto sync = RGWBucketPipeSyncStatusManager::construct( dpp(), static_cast<rgw::sal::RadosStore*>(driver), source_zone, opt_source_bucket, bucket->get_key(), nullptr); if (!sync) { cerr << "ERROR: sync.init() returned error=" << sync.error() << std::endl; return -sync.error(); } auto sync_status = (*sync)->read_sync_status(dpp()); if (!sync_status) { cerr << "ERROR: sync.read_sync_status() returned error=" << sync_status.error() << std::endl; return -sync_status.error(); } encode_json("sync_status", *sync_status, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::BUCKET_SYNC_RUN) { if (source_zone.empty()) { cerr << "ERROR: source zone not specified" << std::endl; return EINVAL; } if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket_for_sync(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { return -ret; } auto sync = RGWBucketPipeSyncStatusManager::construct( dpp(), static_cast<rgw::sal::RadosStore*>(driver), source_zone, opt_source_bucket, bucket->get_key(), extra_info ? &std::cout : nullptr); if (!sync) { cerr << "ERROR: sync.init() returned error=" << sync.error() << std::endl; return -sync.error(); } ret = (*sync)->run(dpp()); if (ret < 0) { cerr << "ERROR: sync.run() returned ret=" << ret << std::endl; return -ret; } } if (opt_cmd == OPT::BILOG_LIST) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->open_array_section("entries"); bool truncated; int count = 0; if (max_entries < 0) max_entries = 1000; const auto& logs = bucket->get_info().layout.logs; auto log_layout = std::reference_wrapper{logs.back()}; if (gen) { auto i = std::find_if(logs.begin(), logs.end(), rgw::matches_gen(*gen)); if (i == logs.end()) { cerr << "ERROR: no log layout with gen=" << *gen << std::endl; return ENOENT; } log_layout = *i; } do { list<rgw_bi_log_entry> entries; ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->bilog_rados->log_list(dpp(), bucket->get_info(), log_layout, shard_id, marker, max_entries - count, entries, &truncated); if (ret < 0) { cerr << "ERROR: list_bi_log_entries(): " << cpp_strerror(-ret) << std::endl; return -ret; } count += entries.size(); for (list<rgw_bi_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) { rgw_bi_log_entry& entry = *iter; encode_json("entry", entry, formatter.get()); marker = entry.id; } formatter->flush(cout); } while (truncated && count < max_entries); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::SYNC_ERROR_LIST) { if (max_entries < 0) { max_entries = 1000; } if (!start_date.empty()) { std::cerr << "start-date not allowed." << std::endl; return -EINVAL; } if (!end_date.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!end_marker.empty()) { std::cerr << "end-marker not allowed." << std::endl; return -EINVAL; } if (!start_marker.empty()) { if (marker.empty()) { marker = start_marker; } else { std::cerr << "start-marker and marker not both allowed." << std::endl; return -EINVAL; } } bool truncated; if (shard_id < 0) { shard_id = 0; } formatter->open_array_section("entries"); for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) { formatter->open_object_section("shard"); encode_json("shard_id", shard_id, formatter.get()); formatter->open_array_section("entries"); int count = 0; string oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX, shard_id); do { list<cls_log_entry> entries; ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->timelog.list(dpp(), oid, {}, {}, max_entries - count, entries, marker, &marker, &truncated, null_yield); if (ret == -ENOENT) { break; } if (ret < 0) { cerr << "ERROR: svc.cls->timelog.list(): " << cpp_strerror(-ret) << std::endl; return -ret; } count += entries.size(); for (auto& cls_entry : entries) { rgw_sync_error_info log_entry; auto iter = cls_entry.data.cbegin(); try { decode(log_entry, iter); } catch (buffer::error& err) { cerr << "ERROR: failed to decode log entry" << std::endl; continue; } formatter->open_object_section("entry"); encode_json("id", cls_entry.id, formatter.get()); encode_json("section", cls_entry.section, formatter.get()); encode_json("name", cls_entry.name, formatter.get()); encode_json("timestamp", cls_entry.timestamp, formatter.get()); encode_json("info", log_entry, formatter.get()); formatter->close_section(); formatter->flush(cout); } } while (truncated && count < max_entries); formatter->close_section(); formatter->close_section(); if (specified_shard_id) { break; } } formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::SYNC_ERROR_TRIM) { if (!start_date.empty()) { std::cerr << "start-date not allowed." << std::endl; return -EINVAL; } if (!end_date.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!start_marker.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!end_marker.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (shard_id < 0) { shard_id = 0; } for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) { ret = trim_sync_error_log(shard_id, marker, trim_delay_ms); if (ret < 0) { cerr << "ERROR: sync error trim: " << cpp_strerror(-ret) << std::endl; return -ret; } if (specified_shard_id) { break; } } } if (opt_cmd == OPT::SYNC_GROUP_CREATE || opt_cmd == OPT::SYNC_GROUP_MODIFY) { CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_status), "ERROR: --status is not specified (options: forbidden, allowed, enabled)", EINVAL); SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); if (opt_cmd == OPT::SYNC_GROUP_MODIFY) { auto iter = sync_policy.groups.find(*opt_group_id); if (iter == sync_policy.groups.end()) { cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl; return ENOENT; } } auto& group = sync_policy.groups[*opt_group_id]; group.id = *opt_group_id; if (opt_status) { if (!group.set_status(*opt_status)) { cerr << "ERROR: unrecognized status (options: forbidden, allowed, enabled)" << std::endl; return EINVAL; } } ret = sync_policy_ctx.write_policy(); if (ret < 0) { return -ret; } show_result(sync_policy, zone_formatter.get(), cout); } if (opt_cmd == OPT::SYNC_GROUP_GET) { SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); auto& groups = sync_policy.groups; if (!opt_group_id) { show_result(groups, zone_formatter.get(), cout); } else { auto iter = sync_policy.groups.find(*opt_group_id); if (iter == sync_policy.groups.end()) { cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl; return ENOENT; } show_result(iter->second, zone_formatter.get(), cout); } } if (opt_cmd == OPT::SYNC_GROUP_REMOVE) { CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL); SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); sync_policy.groups.erase(*opt_group_id); ret = sync_policy_ctx.write_policy(); if (ret < 0) { return -ret; } { Formatter::ObjectSection os(*zone_formatter.get(), "result"); encode_json("sync_policy", sync_policy, zone_formatter.get()); } zone_formatter->flush(cout); } if (opt_cmd == OPT::SYNC_GROUP_FLOW_CREATE) { CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_flow_id), "ERROR: --flow-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_flow_type), "ERROR: --flow-type not specified (options: symmetrical, directional)", EINVAL); CHECK_TRUE((symmetrical_flow_opt(*opt_flow_type) || directional_flow_opt(*opt_flow_type)), "ERROR: --flow-type invalid (options: symmetrical, directional)", EINVAL); SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); auto iter = sync_policy.groups.find(*opt_group_id); if (iter == sync_policy.groups.end()) { cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl; return ENOENT; } auto& group = iter->second; if (symmetrical_flow_opt(*opt_flow_type)) { CHECK_TRUE(require_non_empty_opt(opt_zone_ids), "ERROR: --zones not provided for symmetrical flow, or is empty", EINVAL); rgw_sync_symmetric_group *flow_group; group.data_flow.find_or_create_symmetrical(*opt_flow_id, &flow_group); for (auto& z : *opt_zone_ids) { flow_group->zones.insert(z); } } else { /* directional */ CHECK_TRUE(require_non_empty_opt(opt_source_zone_id), "ERROR: --source-zone not provided for directional flow rule, or is empty", EINVAL); CHECK_TRUE(require_non_empty_opt(opt_dest_zone_id), "ERROR: --dest-zone not provided for directional flow rule, or is empty", EINVAL); rgw_sync_directional_rule *flow_rule; group.data_flow.find_or_create_directional(*opt_source_zone_id, *opt_dest_zone_id, &flow_rule); } ret = sync_policy_ctx.write_policy(); if (ret < 0) { return -ret; } show_result(sync_policy, zone_formatter.get(), cout); } if (opt_cmd == OPT::SYNC_GROUP_FLOW_REMOVE) { CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_flow_id), "ERROR: --flow-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_flow_type), "ERROR: --flow-type not specified (options: symmetrical, directional)", EINVAL); CHECK_TRUE((symmetrical_flow_opt(*opt_flow_type) || directional_flow_opt(*opt_flow_type)), "ERROR: --flow-type invalid (options: symmetrical, directional)", EINVAL); SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); auto iter = sync_policy.groups.find(*opt_group_id); if (iter == sync_policy.groups.end()) { cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl; return ENOENT; } auto& group = iter->second; if (symmetrical_flow_opt(*opt_flow_type)) { group.data_flow.remove_symmetrical(*opt_flow_id, opt_zone_ids); } else { /* directional */ CHECK_TRUE(require_non_empty_opt(opt_source_zone_id), "ERROR: --source-zone not provided for directional flow rule, or is empty", EINVAL); CHECK_TRUE(require_non_empty_opt(opt_dest_zone_id), "ERROR: --dest-zone not provided for directional flow rule, or is empty", EINVAL); group.data_flow.remove_directional(*opt_source_zone_id, *opt_dest_zone_id); } ret = sync_policy_ctx.write_policy(); if (ret < 0) { return -ret; } show_result(sync_policy, zone_formatter.get(), cout); } if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE || opt_cmd == OPT::SYNC_GROUP_PIPE_MODIFY) { CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_pipe_id), "ERROR: --pipe-id not specified", EINVAL); if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE) { CHECK_TRUE(require_non_empty_opt(opt_source_zone_ids), "ERROR: --source-zones not provided or is empty; should be list of zones or '*'", EINVAL); CHECK_TRUE(require_non_empty_opt(opt_dest_zone_ids), "ERROR: --dest-zones not provided or is empty; should be list of zones or '*'", EINVAL); } SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); auto iter = sync_policy.groups.find(*opt_group_id); if (iter == sync_policy.groups.end()) { cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl; return ENOENT; } auto& group = iter->second; rgw_sync_bucket_pipes *pipe; if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE) { group.find_pipe(*opt_pipe_id, true, &pipe); } else { if (!group.find_pipe(*opt_pipe_id, false, &pipe)) { cerr << "ERROR: could not find pipe '" << *opt_pipe_id << "'" << std::endl; return ENOENT; } } if (opt_source_zone_ids) { pipe->source.add_zones(*opt_source_zone_ids); } pipe->source.set_bucket(opt_source_tenant, opt_source_bucket_name, opt_source_bucket_id); if (opt_dest_zone_ids) { pipe->dest.add_zones(*opt_dest_zone_ids); } pipe->dest.set_bucket(opt_dest_tenant, opt_dest_bucket_name, opt_dest_bucket_id); pipe->params.source.filter.set_prefix(opt_prefix, !!opt_prefix_rm); pipe->params.source.filter.set_tags(tags_add, tags_rm); if (opt_dest_owner) { pipe->params.dest.set_owner(*opt_dest_owner); } if (opt_storage_class) { pipe->params.dest.set_storage_class(*opt_storage_class); } if (opt_priority) { pipe->params.priority = *opt_priority; } if (opt_mode) { if (*opt_mode == "system") { pipe->params.mode = rgw_sync_pipe_params::MODE_SYSTEM; } else if (*opt_mode == "user") { pipe->params.mode = rgw_sync_pipe_params::MODE_USER; } else { cerr << "ERROR: bad mode value: should be one of the following: system, user" << std::endl; return EINVAL; } } if (!rgw::sal::User::empty(user)) { pipe->params.user = user->get_id(); } else if (pipe->params.user.empty()) { auto owner = sync_policy_ctx.get_owner(); if (owner) { pipe->params.user = *owner; } } ret = sync_policy_ctx.write_policy(); if (ret < 0) { return -ret; } show_result(sync_policy, zone_formatter.get(), cout); } if (opt_cmd == OPT::SYNC_GROUP_PIPE_REMOVE) { CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL); CHECK_TRUE(require_opt(opt_pipe_id), "ERROR: --pipe-id not specified", EINVAL); SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); auto iter = sync_policy.groups.find(*opt_group_id); if (iter == sync_policy.groups.end()) { cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl; return ENOENT; } auto& group = iter->second; rgw_sync_bucket_pipes *pipe; if (!group.find_pipe(*opt_pipe_id, false, &pipe)) { cerr << "ERROR: could not find pipe '" << *opt_pipe_id << "'" << std::endl; return ENOENT; } if (opt_source_zone_ids) { pipe->source.remove_zones(*opt_source_zone_ids); } pipe->source.remove_bucket(opt_source_tenant, opt_source_bucket_name, opt_source_bucket_id); if (opt_dest_zone_ids) { pipe->dest.remove_zones(*opt_dest_zone_ids); } pipe->dest.remove_bucket(opt_dest_tenant, opt_dest_bucket_name, opt_dest_bucket_id); if (!(opt_source_zone_ids || opt_source_tenant || opt_source_bucket || opt_source_bucket_id || opt_dest_zone_ids || opt_dest_tenant || opt_dest_bucket || opt_dest_bucket_id)) { group.remove_pipe(*opt_pipe_id); } ret = sync_policy_ctx.write_policy(); if (ret < 0) { return -ret; } show_result(sync_policy, zone_formatter.get(), cout); } if (opt_cmd == OPT::SYNC_POLICY_GET) { SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket); ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name); if (ret < 0) { return -ret; } auto& sync_policy = sync_policy_ctx.get_policy(); show_result(sync_policy, zone_formatter.get(), cout); } if (opt_cmd == OPT::BILOG_TRIM) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } if (!gen) { gen = 0; } ret = bilog_trim(dpp(), static_cast<rgw::sal::RadosStore*>(driver), bucket->get_info(), *gen, shard_id, start_marker, end_marker); if (ret < 0) { cerr << "ERROR: trim_bi_log_entries(): " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::BILOG_STATUS) { if (bucket_name.empty()) { cerr << "ERROR: bucket not specified" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } map<int, string> markers; const auto& logs = bucket->get_info().layout.logs; auto log_layout = std::reference_wrapper{logs.back()}; if (gen) { auto i = std::find_if(logs.begin(), logs.end(), rgw::matches_gen(*gen)); if (i == logs.end()) { cerr << "ERROR: no log layout with gen=" << *gen << std::endl; return ENOENT; } log_layout = *i; } ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->bilog_rados->get_log_status(dpp(), bucket->get_info(), log_layout, shard_id, &markers, null_yield); if (ret < 0) { cerr << "ERROR: get_bi_log_status(): " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->open_object_section("entries"); encode_json("markers", markers, formatter.get()); formatter->dump_string("current_time", to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms)); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::BILOG_AUTOTRIM) { RGWCoroutinesManager crs(driver->ctx(), driver->get_cr_registry()); RGWHTTPManager http(driver->ctx(), crs.get_completion_mgr()); int ret = http.start(); if (ret < 0) { cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl; return -ret; } rgw::BucketTrimConfig config; configure_bucket_trim(driver->ctx(), config); rgw::BucketTrimManager trim(static_cast<rgw::sal::RadosStore*>(driver), config); ret = trim.init(); if (ret < 0) { cerr << "trim manager init failed with " << cpp_strerror(ret) << std::endl; return -ret; } ret = crs.run(dpp(), trim.create_admin_bucket_trim_cr(&http)); if (ret < 0) { cerr << "automated bilog trim failed with " << cpp_strerror(ret) << std::endl; return -ret; } } if (opt_cmd == OPT::DATALOG_LIST) { formatter->open_array_section("entries"); bool truncated; int count = 0; if (max_entries < 0) max_entries = 1000; if (!start_date.empty()) { std::cerr << "start-date not allowed." << std::endl; return -EINVAL; } if (!end_date.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!end_marker.empty()) { std::cerr << "end-marker not allowed." << std::endl; return -EINVAL; } if (!start_marker.empty()) { if (marker.empty()) { marker = start_marker; } else { std::cerr << "start-marker and marker not both allowed." << std::endl; return -EINVAL; } } auto datalog_svc = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados; RGWDataChangesLog::LogMarker log_marker; do { std::vector<rgw_data_change_log_entry> entries; if (specified_shard_id) { ret = datalog_svc->list_entries(dpp(), shard_id, max_entries - count, entries, marker, &marker, &truncated, null_yield); } else { ret = datalog_svc->list_entries(dpp(), max_entries - count, entries, log_marker, &truncated, null_yield); } if (ret < 0) { cerr << "ERROR: datalog_svc->list_entries(): " << cpp_strerror(-ret) << std::endl; return -ret; } count += entries.size(); for (const auto& entry : entries) { if (!extra_info) { encode_json("entry", entry.entry, formatter.get()); } else { encode_json("entry", entry, formatter.get()); } } formatter.get()->flush(cout); } while (truncated && count < max_entries); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::DATALOG_STATUS) { int i = (specified_shard_id ? shard_id : 0); formatter->open_array_section("entries"); for (; i < g_ceph_context->_conf->rgw_data_log_num_shards; i++) { list<cls_log_entry> entries; RGWDataChangesLogInfo info; static_cast<rgw::sal::RadosStore*>(driver)->svc()-> datalog_rados->get_info(dpp(), i, &info, null_yield); ::encode_json("info", info, formatter.get()); if (specified_shard_id) break; } formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::DATALOG_AUTOTRIM) { RGWCoroutinesManager crs(driver->ctx(), driver->get_cr_registry()); RGWHTTPManager http(driver->ctx(), crs.get_completion_mgr()); int ret = http.start(); if (ret < 0) { cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl; return -ret; } auto num_shards = g_conf()->rgw_data_log_num_shards; std::vector<std::string> markers(num_shards); ret = crs.run(dpp(), create_admin_data_log_trim_cr(dpp(), static_cast<rgw::sal::RadosStore*>(driver), &http, num_shards, markers)); if (ret < 0) { cerr << "automated datalog trim failed with " << cpp_strerror(ret) << std::endl; return -ret; } } if (opt_cmd == OPT::DATALOG_TRIM) { if (!start_date.empty()) { std::cerr << "start-date not allowed." << std::endl; return -EINVAL; } if (!end_date.empty()) { std::cerr << "end-date not allowed." << std::endl; return -EINVAL; } if (!start_marker.empty()) { std::cerr << "start-marker not allowed." << std::endl; return -EINVAL; } if (!end_marker.empty()) { if (marker.empty()) { marker = end_marker; } else { std::cerr << "end-marker and marker not both allowed." << std::endl; return -EINVAL; } } if (!specified_shard_id) { cerr << "ERROR: requires a --shard-id" << std::endl; return EINVAL; } if (marker.empty()) { cerr << "ERROR: requires a --marker" << std::endl; return EINVAL; } auto datalog = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados; ret = datalog->trim_entries(dpp(), shard_id, marker, null_yield); if (ret < 0 && ret != -ENODATA) { cerr << "ERROR: trim_entries(): " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::DATALOG_TYPE) { if (!opt_log_type) { std::cerr << "log-type not specified." << std::endl; return -EINVAL; } auto datalog = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados; ret = datalog->change_format(dpp(), *opt_log_type, null_yield); if (ret < 0) { cerr << "ERROR: change_format(): " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::DATALOG_PRUNE) { auto datalog = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados; std::optional<uint64_t> through; ret = datalog->trim_generations(dpp(), through, null_yield); if (ret < 0) { cerr << "ERROR: trim_generations(): " << cpp_strerror(-ret) << std::endl; return -ret; } if (through) { std::cout << "Pruned " << *through << " empty generations." << std::endl; } else { std::cout << "No empty generations." << std::endl; } } bool quota_op = (opt_cmd == OPT::QUOTA_SET || opt_cmd == OPT::QUOTA_ENABLE || opt_cmd == OPT::QUOTA_DISABLE); if (quota_op) { if (bucket_name.empty() && rgw::sal::User::empty(user)) { cerr << "ERROR: bucket name or uid is required for quota operation" << std::endl; return EINVAL; } if (!bucket_name.empty()) { if (!quota_scope.empty() && quota_scope != "bucket") { cerr << "ERROR: invalid quota scope specification." << std::endl; return EINVAL; } set_bucket_quota(driver, opt_cmd, tenant, bucket_name, max_size, max_objects, have_max_size, have_max_objects); } else if (!rgw::sal::User::empty(user)) { if (quota_scope == "bucket") { return set_user_bucket_quota(opt_cmd, ruser, user_op, max_size, max_objects, have_max_size, have_max_objects); } else if (quota_scope == "user") { return set_user_quota(opt_cmd, ruser, user_op, max_size, max_objects, have_max_size, have_max_objects); } else { cerr << "ERROR: invalid quota scope specification. Please specify either --quota-scope=bucket, or --quota-scope=user" << std::endl; return EINVAL; } } } bool ratelimit_op_set = (opt_cmd == OPT::RATELIMIT_SET || opt_cmd == OPT::RATELIMIT_ENABLE || opt_cmd == OPT::RATELIMIT_DISABLE); bool ratelimit_op_get = opt_cmd == OPT::RATELIMIT_GET; if (ratelimit_op_set) { if (bucket_name.empty() && rgw::sal::User::empty(user)) { cerr << "ERROR: bucket name or uid is required for ratelimit operation" << std::endl; return EINVAL; } if (!bucket_name.empty()) { if (!ratelimit_scope.empty() && ratelimit_scope != "bucket") { cerr << "ERROR: invalid ratelimit scope specification. (bucket scope is not bucket but bucket has been specified)" << std::endl; return EINVAL; } return set_bucket_ratelimit(driver, opt_cmd, tenant, bucket_name, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); } else if (!rgw::sal::User::empty(user)) { if (ratelimit_scope == "user") { return set_user_ratelimit(opt_cmd, user, max_read_ops, max_write_ops, max_read_bytes, max_write_bytes, have_max_read_ops, have_max_write_ops, have_max_read_bytes, have_max_write_bytes); } else { cerr << "ERROR: invalid ratelimit scope specification. Please specify either --ratelimit-scope=bucket, or --ratelimit-scope=user" << std::endl; return EINVAL; } } } if (ratelimit_op_get) { if (bucket_name.empty() && rgw::sal::User::empty(user)) { cerr << "ERROR: bucket name or uid is required for ratelimit operation" << std::endl; return EINVAL; } if (!bucket_name.empty()) { if (!ratelimit_scope.empty() && ratelimit_scope != "bucket") { cerr << "ERROR: invalid ratelimit scope specification. (bucket scope is not bucket but bucket has been specified)" << std::endl; return EINVAL; } return show_bucket_ratelimit(driver, tenant, bucket_name, formatter.get()); } else if (!rgw::sal::User::empty(user)) { if (ratelimit_scope == "user") { return show_user_ratelimit(user, formatter.get()); } else { cerr << "ERROR: invalid ratelimit scope specification. Please specify either --ratelimit-scope=bucket, or --ratelimit-scope=user" << std::endl; return EINVAL; } } } if (opt_cmd == OPT::MFA_CREATE) { rados::cls::otp::otp_info_t config; if (rgw::sal::User::empty(user)) { cerr << "ERROR: user id was not provided (via --uid)" << std::endl; return EINVAL; } if (totp_serial.empty()) { cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl; return EINVAL; } if (totp_seed.empty()) { cerr << "ERROR: TOTP device seed was not provided (via --totp-seed)" << std::endl; return EINVAL; } rados::cls::otp::SeedType seed_type; if (totp_seed_type == "hex") { seed_type = rados::cls::otp::OTP_SEED_HEX; } else if (totp_seed_type == "base32") { seed_type = rados::cls::otp::OTP_SEED_BASE32; } else { cerr << "ERROR: invalid seed type: " << totp_seed_type << std::endl; return EINVAL; } config.id = totp_serial; config.seed = totp_seed; config.seed_type = seed_type; if (totp_seconds > 0) { config.step_size = totp_seconds; } if (totp_window > 0) { config.window = totp_window; } real_time mtime = real_clock::now(); string oid = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.get_mfa_oid(user->get_id()); int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user->get_id()), mtime, &objv_tracker, null_yield, dpp(), MDLOG_STATUS_WRITE, [&] { return static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.create_mfa(dpp(), user->get_id(), config, &objv_tracker, mtime, null_yield); }); if (ret < 0) { cerr << "MFA creation failed, error: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWUserInfo& user_info = user_op.get_user_info(); user_info.mfa_ids.insert(totp_serial); user_op.set_mfa_ids(user_info.mfa_ids); string err; ret = ruser.modify(dpp(), user_op, null_yield, &err); if (ret < 0) { cerr << "ERROR: failed storing user info, error: " << err << std::endl; return -ret; } } if (opt_cmd == OPT::MFA_REMOVE) { if (rgw::sal::User::empty(user)) { cerr << "ERROR: user id was not provided (via --uid)" << std::endl; return EINVAL; } if (totp_serial.empty()) { cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl; return EINVAL; } real_time mtime = real_clock::now(); int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user->get_id()), mtime, &objv_tracker, null_yield, dpp(), MDLOG_STATUS_WRITE, [&] { return static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.remove_mfa(dpp(), user->get_id(), totp_serial, &objv_tracker, mtime, null_yield); }); if (ret < 0) { cerr << "MFA removal failed, error: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWUserInfo& user_info = user_op.get_user_info(); user_info.mfa_ids.erase(totp_serial); user_op.set_mfa_ids(user_info.mfa_ids); string err; ret = ruser.modify(dpp(), user_op, null_yield, &err); if (ret < 0) { cerr << "ERROR: failed storing user info, error: " << err << std::endl; return -ret; } } if (opt_cmd == OPT::MFA_GET) { if (rgw::sal::User::empty(user)) { cerr << "ERROR: user id was not provided (via --uid)" << std::endl; return EINVAL; } if (totp_serial.empty()) { cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl; return EINVAL; } rados::cls::otp::otp_info_t result; int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.get_mfa(dpp(), user->get_id(), totp_serial, &result, null_yield); if (ret < 0) { if (ret == -ENOENT || ret == -ENODATA) { cerr << "MFA serial id not found" << std::endl; } else { cerr << "MFA retrieval failed, error: " << cpp_strerror(-ret) << std::endl; } return -ret; } formatter->open_object_section("result"); encode_json("entry", result, formatter.get()); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::MFA_LIST) { if (rgw::sal::User::empty(user)) { cerr << "ERROR: user id was not provided (via --uid)" << std::endl; return EINVAL; } list<rados::cls::otp::otp_info_t> result; int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.list_mfa(dpp(), user->get_id(), &result, null_yield); if (ret < 0 && ret != -ENOENT) { cerr << "MFA listing failed, error: " << cpp_strerror(-ret) << std::endl; return -ret; } formatter->open_object_section("result"); encode_json("entries", result, formatter.get()); formatter->close_section(); formatter->flush(cout); } if (opt_cmd == OPT::MFA_CHECK) { if (rgw::sal::User::empty(user)) { cerr << "ERROR: user id was not provided (via --uid)" << std::endl; return EINVAL; } if (totp_serial.empty()) { cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl; return EINVAL; } if (totp_pin.empty()) { cerr << "ERROR: TOTP device serial number was not provided (via --totp-pin)" << std::endl; return EINVAL; } list<rados::cls::otp::otp_info_t> result; int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.check_mfa(dpp(), user->get_id(), totp_serial, totp_pin.front(), null_yield); if (ret < 0) { cerr << "MFA check failed, error: " << cpp_strerror(-ret) << std::endl; return -ret; } cout << "ok" << std::endl; } if (opt_cmd == OPT::MFA_RESYNC) { if (rgw::sal::User::empty(user)) { cerr << "ERROR: user id was not provided (via --uid)" << std::endl; return EINVAL; } if (totp_serial.empty()) { cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl; return EINVAL; } if (totp_pin.size() != 2) { cerr << "ERROR: missing two --totp-pin params (--totp-pin=<first> --totp-pin=<second>)" << std::endl; return EINVAL; } rados::cls::otp::otp_info_t config; int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.get_mfa(dpp(), user->get_id(), totp_serial, &config, null_yield); if (ret < 0) { if (ret == -ENOENT || ret == -ENODATA) { cerr << "MFA serial id not found" << std::endl; } else { cerr << "MFA retrieval failed, error: " << cpp_strerror(-ret) << std::endl; } return -ret; } ceph::real_time now; ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.otp_get_current_time(dpp(), user->get_id(), &now, null_yield); if (ret < 0) { cerr << "ERROR: failed to fetch current time from osd: " << cpp_strerror(-ret) << std::endl; return -ret; } time_t time_ofs; ret = scan_totp(driver->ctx(), now, config, totp_pin, &time_ofs); if (ret < 0) { if (ret == -ENOENT) { cerr << "failed to resync, TOTP values not found in range" << std::endl; } else { cerr << "ERROR: failed to scan for TOTP values: " << cpp_strerror(-ret) << std::endl; } return -ret; } // time offset is a small number and unlikely to overflow // coverity[store_truncates_time_t:SUPPRESS] config.time_ofs = time_ofs; /* now update the backend */ real_time mtime = real_clock::now(); ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user->get_id()), mtime, &objv_tracker, null_yield, dpp(), MDLOG_STATUS_WRITE, [&] { return static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.create_mfa(dpp(), user->get_id(), config, &objv_tracker, mtime, null_yield); }); if (ret < 0) { cerr << "MFA update failed, error: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::RESHARD_STALE_INSTANCES_LIST) { if (!static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->can_reshard() && !yes_i_really_mean_it) { cerr << "Resharding disabled in a multisite env, stale instances unlikely from resharding" << std::endl; cerr << "These instances may not be safe to delete." << std::endl; cerr << "Use --yes-i-really-mean-it to force displaying these instances." << std::endl; return EINVAL; } ret = RGWBucketAdminOp::list_stale_instances(driver, bucket_op, stream_flusher, dpp(), null_yield); if (ret < 0) { cerr << "ERROR: listing stale instances" << cpp_strerror(-ret) << std::endl; } } if (opt_cmd == OPT::RESHARD_STALE_INSTANCES_DELETE) { if (!static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->can_reshard()) { cerr << "Resharding disabled in a multisite env. Stale instances are not safe to be deleted." << std::endl; return EINVAL; } ret = RGWBucketAdminOp::clear_stale_instances(driver, bucket_op, stream_flusher, dpp(), null_yield); if (ret < 0) { cerr << "ERROR: deleting stale instances" << cpp_strerror(-ret) << std::endl; } } if (opt_cmd == OPT::PUBSUB_NOTIFICATION_LIST) { if (bucket_name.empty()) { cerr << "ERROR: bucket name was not provided (via --bucket)" << std::endl; return EINVAL; } RGWPubSub ps(driver, tenant); rgw_pubsub_bucket_topics result; int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } const RGWPubSub::Bucket b(ps, bucket.get()); ret = b.get_topics(dpp(), result, null_yield); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: could not get topics: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("result", result, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::PUBSUB_TOPIC_LIST) { RGWPubSub ps(driver, tenant); rgw_pubsub_topics result; int ret = ps.get_topics(dpp(), result, null_yield); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: could not get topics: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("result", result, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::PUBSUB_TOPIC_GET) { if (topic_name.empty()) { cerr << "ERROR: topic name was not provided (via --topic)" << std::endl; return EINVAL; } RGWPubSub ps(driver, tenant); rgw_pubsub_topic topic; ret = ps.get_topic(dpp(), topic_name, topic, null_yield); if (ret < 0) { cerr << "ERROR: could not get topic: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("topic", topic, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::PUBSUB_NOTIFICATION_GET) { if (notification_id.empty()) { cerr << "ERROR: notification-id was not provided (via --notification-id)" << std::endl; return EINVAL; } if (bucket_name.empty()) { cerr << "ERROR: bucket name was not provided (via --bucket)" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWPubSub ps(driver, tenant); rgw_pubsub_bucket_topics bucket_topics; const RGWPubSub::Bucket b(ps, bucket.get()); ret = b.get_topics(dpp(), bucket_topics, null_yield); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: could not get bucket notifications: " << cpp_strerror(-ret) << std::endl; return -ret; } rgw_pubsub_topic_filter bucket_topic; ret = b.get_notification_by_id(dpp(), notification_id, bucket_topic, null_yield); if (ret < 0) { cerr << "ERROR: could not get notification: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("notification", bucket_topic, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::PUBSUB_TOPIC_RM) { if (topic_name.empty()) { cerr << "ERROR: topic name was not provided (via --topic)" << std::endl; return EINVAL; } ret = rgw::notify::remove_persistent_topic( dpp(), static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_notif_pool_ctx(), topic_name, null_yield); if (ret < 0) { cerr << "ERROR: could not remove persistent topic: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWPubSub ps(driver, tenant); ret = ps.remove_topic(dpp(), topic_name, null_yield); if (ret < 0) { cerr << "ERROR: could not remove topic: " << cpp_strerror(-ret) << std::endl; return -ret; } } if (opt_cmd == OPT::PUBSUB_NOTIFICATION_RM) { if (bucket_name.empty()) { cerr << "ERROR: bucket name was not provided (via --bucket)" << std::endl; return EINVAL; } int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket); if (ret < 0) { cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl; return -ret; } RGWPubSub ps(driver, tenant); rgw_pubsub_bucket_topics bucket_topics; const RGWPubSub::Bucket b(ps, bucket.get()); ret = b.get_topics(dpp(), bucket_topics, null_yield); if (ret < 0 && ret != -ENOENT) { cerr << "ERROR: could not get bucket notifications: " << cpp_strerror(-ret) << std::endl; return -ret; } rgw_pubsub_topic_filter bucket_topic; if(notification_id.empty()) { ret = b.remove_notifications(dpp(), null_yield); } else { ret = b.remove_notification_by_id(dpp(), notification_id, null_yield); } } if (opt_cmd == OPT::PUBSUB_TOPIC_STATS) { if (topic_name.empty()) { cerr << "ERROR: topic name was not provided (via --topic)" << std::endl; return EINVAL; } rgw::notify::rgw_topic_stats stats; ret = rgw::notify::get_persistent_queue_stats_by_topic_name( dpp(), static_cast<rgw::sal::RadosStore *>(driver)->getRados()->get_notif_pool_ctx(), topic_name, stats, null_yield); if (ret < 0) { cerr << "ERROR: could not get persistent queue: " << cpp_strerror(-ret) << std::endl; return -ret; } encode_json("", stats, formatter.get()); formatter->flush(cout); } if (opt_cmd == OPT::SCRIPT_PUT) { if (!str_script_ctx) { cerr << "ERROR: context was not provided (via --context)" << std::endl; return EINVAL; } if (infile.empty()) { cerr << "ERROR: infile was not provided (via --infile)" << std::endl; return EINVAL; } bufferlist bl; auto rc = read_input(infile, bl); if (rc < 0) { cerr << "ERROR: failed to read script: '" << infile << "'. error: " << rc << std::endl; return -rc; } const std::string script = bl.to_str(); std::string err_msg; if (!rgw::lua::verify(script, err_msg)) { cerr << "ERROR: script: '" << infile << "' has error: " << std::endl << err_msg << std::endl; return EINVAL; } const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx); if (script_ctx == rgw::lua::context::none) { cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl; return EINVAL; } if (script_ctx == rgw::lua::context::background && !tenant.empty()) { cerr << "ERROR: cannot specify tenant in background context" << std::endl; return EINVAL; } auto lua_manager = driver->get_lua_manager(); rc = rgw::lua::write_script(dpp(), lua_manager.get(), tenant, null_yield, script_ctx, script); if (rc < 0) { cerr << "ERROR: failed to put script. error: " << rc << std::endl; return -rc; } } if (opt_cmd == OPT::SCRIPT_GET) { if (!str_script_ctx) { cerr << "ERROR: context was not provided (via --context)" << std::endl; return EINVAL; } const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx); if (script_ctx == rgw::lua::context::none) { cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl; return EINVAL; } auto lua_manager = driver->get_lua_manager(); std::string script; const auto rc = rgw::lua::read_script(dpp(), lua_manager.get(), tenant, null_yield, script_ctx, script); if (rc == -ENOENT) { std::cout << "no script exists for context: " << *str_script_ctx << (tenant.empty() ? "" : (" in tenant: " + tenant)) << std::endl; } else if (rc < 0) { cerr << "ERROR: failed to read script. error: " << rc << std::endl; return -rc; } else { std::cout << script << std::endl; } } if (opt_cmd == OPT::SCRIPT_RM) { if (!str_script_ctx) { cerr << "ERROR: context was not provided (via --context)" << std::endl; return EINVAL; } const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx); if (script_ctx == rgw::lua::context::none) { cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl; return EINVAL; } auto lua_manager = driver->get_lua_manager(); const auto rc = rgw::lua::delete_script(dpp(), lua_manager.get(), tenant, null_yield, script_ctx); if (rc < 0) { cerr << "ERROR: failed to remove script. error: " << rc << std::endl; return -rc; } } if (opt_cmd == OPT::SCRIPT_PACKAGE_ADD) { #ifdef WITH_RADOSGW_LUA_PACKAGES if (!script_package) { cerr << "ERROR: lua package name was not provided (via --package)" << std::endl; return EINVAL; } const auto rc = rgw::lua::add_package(dpp(), driver, null_yield, *script_package, bool(allow_compilation)); if (rc < 0) { cerr << "ERROR: failed to add lua package: " << script_package << " .error: " << rc << std::endl; return -rc; } #else cerr << "ERROR: adding lua packages is not permitted" << std::endl; return EPERM; #endif } if (opt_cmd == OPT::SCRIPT_PACKAGE_RM) { #ifdef WITH_RADOSGW_LUA_PACKAGES if (!script_package) { cerr << "ERROR: lua package name was not provided (via --package)" << std::endl; return EINVAL; } const auto rc = rgw::lua::remove_package(dpp(), driver, null_yield, *script_package); if (rc == -ENOENT) { cerr << "WARNING: package " << script_package << " did not exists or already removed" << std::endl; return 0; } if (rc < 0) { cerr << "ERROR: failed to remove lua package: " << script_package << " .error: " << rc << std::endl; return -rc; } #else cerr << "ERROR: removing lua packages in not permitted" << std::endl; return EPERM; #endif } if (opt_cmd == OPT::SCRIPT_PACKAGE_LIST) { #ifdef WITH_RADOSGW_LUA_PACKAGES rgw::lua::packages_t packages; const auto rc = rgw::lua::list_packages(dpp(), driver, null_yield, packages); if (rc == -ENOENT) { std::cout << "no lua packages in allowlist" << std::endl; } else if (rc < 0) { cerr << "ERROR: failed to read lua packages allowlist. error: " << rc << std::endl; return rc; } else { for (const auto& package : packages) { std::cout << package << std::endl; } } #else cerr << "ERROR: listing lua packages in not permitted" << std::endl; return EPERM; #endif } return 0; }
379,777
34.410536
211
cc
null
ceph-main/src/rgw/rgw_aio.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <type_traits> #include "include/rados/librados.hpp" #include "librados/librados_asio.h" #include "rgw_aio.h" #include "rgw_d3n_cacherequest.h" namespace rgw { namespace { void cb(librados::completion_t, void* arg); struct state { Aio* aio; librados::IoCtx ctx; librados::AioCompletion* c; state(Aio* aio, librados::IoCtx ctx, AioResult& r) : aio(aio), ctx(std::move(ctx)), c(librados::Rados::aio_create_completion(&r, &cb)) {} }; void cb(librados::completion_t, void* arg) { static_assert(sizeof(AioResult::user_data) >= sizeof(state)); auto& r = *(static_cast<AioResult*>(arg)); auto s = reinterpret_cast<state*>(&r.user_data); r.result = s->c->get_return_value(); s->c->release(); Aio* aio = s->aio; // manually destroy the state that was constructed with placement new s->~state(); aio->put(r); } template <typename Op> Aio::OpFunc aio_abstract(librados::IoCtx ctx, Op&& op) { return [ctx = std::move(ctx), op = std::move(op)] (Aio* aio, AioResult& r) mutable { constexpr bool read = std::is_same_v<std::decay_t<Op>, librados::ObjectReadOperation>; // use placement new to construct the rados state inside of user_data auto s = new (&r.user_data) state(aio, ctx, r); if constexpr (read) { r.result = ctx.aio_operate(r.obj.oid, s->c, &op, &r.data); } else { r.result = ctx.aio_operate(r.obj.oid, s->c, &op); } if (r.result < 0) { // cb() won't be called, so release everything here s->c->release(); aio->put(r); s->~state(); } }; } struct Handler { Aio* throttle = nullptr; librados::IoCtx ctx; AioResult& r; // write callback void operator()(boost::system::error_code ec) const { r.result = -ec.value(); throttle->put(r); } // read callback void operator()(boost::system::error_code ec, bufferlist bl) const { r.result = -ec.value(); r.data = std::move(bl); throttle->put(r); } }; template <typename Op> Aio::OpFunc aio_abstract(librados::IoCtx ctx, Op&& op, boost::asio::io_context& context, yield_context yield) { return [ctx = std::move(ctx), op = std::move(op), &context, yield] (Aio* aio, AioResult& r) mutable { // arrange for the completion Handler to run on the yield_context's strand // executor so it can safely call back into Aio without locking using namespace boost::asio; async_completion<yield_context, void()> init(yield); auto ex = get_associated_executor(init.completion_handler); librados::async_operate(context, ctx, r.obj.oid, &op, 0, bind_executor(ex, Handler{aio, ctx, r})); }; } Aio::OpFunc d3n_cache_aio_abstract(const DoutPrefixProvider *dpp, optional_yield y, off_t read_ofs, off_t read_len, std::string& cache_location) { return [dpp, y, read_ofs, read_len, cache_location] (Aio* aio, AioResult& r) mutable { // d3n data cache requires yield context (rgw_beast_enable_async=true) ceph_assert(y); auto c = std::make_unique<D3nL1CacheRequest>(); lsubdout(g_ceph_context, rgw_datacache, 20) << "D3nDataCache: d3n_cache_aio_abstract(): libaio Read From Cache, oid=" << r.obj.oid << dendl; c->file_aio_read_abstract(dpp, y.get_io_context(), y.get_yield_context(), cache_location, read_ofs, read_len, aio, r); }; } template <typename Op> Aio::OpFunc aio_abstract(librados::IoCtx ctx, Op&& op, optional_yield y) { static_assert(std::is_base_of_v<librados::ObjectOperation, std::decay_t<Op>>); static_assert(!std::is_lvalue_reference_v<Op>); static_assert(!std::is_const_v<Op>); if (y) { return aio_abstract(std::move(ctx), std::forward<Op>(op), y.get_io_context(), y.get_yield_context()); } return aio_abstract(std::move(ctx), std::forward<Op>(op)); } } // anonymous namespace Aio::OpFunc Aio::librados_op(librados::IoCtx ctx, librados::ObjectReadOperation&& op, optional_yield y) { return aio_abstract(std::move(ctx), std::move(op), y); } Aio::OpFunc Aio::librados_op(librados::IoCtx ctx, librados::ObjectWriteOperation&& op, optional_yield y) { return aio_abstract(std::move(ctx), std::move(op), y); } Aio::OpFunc Aio::d3n_cache_op(const DoutPrefixProvider *dpp, optional_yield y, off_t read_ofs, off_t read_len, std::string& cache_location) { return d3n_cache_aio_abstract(dpp, y, read_ofs, read_len, cache_location); } } // namespace rgw
5,020
33.156463
146
cc
null
ceph-main/src/rgw/rgw_aio.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 <cstdint> #include <memory> #include <type_traits> #include <boost/intrusive/list.hpp> #include "include/rados/librados_fwd.hpp" #include "common/async/yield_context.h" #include "rgw_common.h" #include "include/function2.hpp" struct D3nGetObjData; namespace rgw { struct AioResult { rgw_raw_obj obj; uint64_t id = 0; // id allows caller to associate a result with its request bufferlist data; // result buffer for reads int result = 0; std::aligned_storage_t<3 * sizeof(void*)> user_data; AioResult() = default; AioResult(const AioResult&) = delete; AioResult& operator =(const AioResult&) = delete; AioResult(AioResult&&) = delete; AioResult& operator =(AioResult&&) = delete; }; struct AioResultEntry : AioResult, boost::intrusive::list_base_hook<> { virtual ~AioResultEntry() {} }; // a list of polymorphic entries that frees them on destruction template <typename T, typename ...Args> struct OwningList : boost::intrusive::list<T, Args...> { OwningList() = default; ~OwningList() { this->clear_and_dispose(std::default_delete<T>{}); } OwningList(OwningList&&) = default; OwningList& operator=(OwningList&&) = default; OwningList(const OwningList&) = delete; OwningList& operator=(const OwningList&) = delete; }; using AioResultList = OwningList<AioResultEntry>; // returns the first error code or 0 if all succeeded inline int check_for_errors(const AioResultList& results) { for (auto& e : results) { if (e.result < 0) { return e.result; } } return 0; } // interface to submit async librados operations and wait on their completions. // each call returns a list of results from prior completions class Aio { public: using OpFunc = fu2::unique_function<void(Aio*, AioResult&) &&>; virtual ~Aio() {} virtual AioResultList get(rgw_raw_obj obj, OpFunc&& f, uint64_t cost, uint64_t id) = 0; virtual void put(AioResult& r) = 0; // poll for any ready completions without waiting virtual AioResultList poll() = 0; // return any ready completions. if there are none, wait for the next virtual AioResultList wait() = 0; // wait for all outstanding completions and return their results virtual AioResultList drain() = 0; static OpFunc librados_op(librados::IoCtx ctx, librados::ObjectReadOperation&& op, optional_yield y); static OpFunc librados_op(librados::IoCtx ctx, librados::ObjectWriteOperation&& op, optional_yield y); static OpFunc d3n_cache_op(const DoutPrefixProvider *dpp, optional_yield y, off_t read_ofs, off_t read_len, std::string& location); }; } // namespace rgw
3,161
29.114286
84
h
null
ceph-main/src/rgw/rgw_aio_throttle.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "rgw_aio_throttle.h" namespace rgw { bool Throttle::waiter_ready() const { switch (waiter) { case Wait::Available: return is_available(); case Wait::Completion: return has_completion(); case Wait::Drained: return is_drained(); default: return false; } } AioResultList BlockingAioThrottle::get(rgw_raw_obj obj, OpFunc&& f, uint64_t cost, uint64_t id) { auto p = std::make_unique<Pending>(); p->obj = std::move(obj); p->id = id; p->cost = cost; std::unique_lock lock{mutex}; if (cost > window) { p->result = -EDEADLK; // would never succeed completed.push_back(*p); } else { // wait for the write size to become available pending_size += p->cost; if (!is_available()) { ceph_assert(waiter == Wait::None); waiter = Wait::Available; cond.wait(lock, [this] { return is_available(); }); waiter = Wait::None; } // register the pending write and attach a completion p->parent = this; pending.push_back(*p); lock.unlock(); std::move(f)(this, *static_cast<AioResult*>(p.get())); lock.lock(); } // coverity[leaked_storage:SUPPRESS] p.release(); return std::move(completed); } void BlockingAioThrottle::put(AioResult& r) { auto& p = static_cast<Pending&>(r); std::scoped_lock lock{mutex}; // move from pending to completed pending.erase(pending.iterator_to(p)); completed.push_back(p); pending_size -= p.cost; if (waiter_ready()) { cond.notify_one(); } } AioResultList BlockingAioThrottle::poll() { std::unique_lock lock{mutex}; return std::move(completed); } AioResultList BlockingAioThrottle::wait() { std::unique_lock lock{mutex}; if (completed.empty() && !pending.empty()) { ceph_assert(waiter == Wait::None); waiter = Wait::Completion; cond.wait(lock, [this] { return has_completion(); }); waiter = Wait::None; } return std::move(completed); } AioResultList BlockingAioThrottle::drain() { std::unique_lock lock{mutex}; if (!pending.empty()) { ceph_assert(waiter == Wait::None); waiter = Wait::Drained; cond.wait(lock, [this] { return is_drained(); }); waiter = Wait::None; } return std::move(completed); } template <typename CompletionToken> auto YieldingAioThrottle::async_wait(CompletionToken&& token) { using boost::asio::async_completion; using Signature = void(boost::system::error_code); async_completion<CompletionToken, Signature> init(token); completion = Completion::create(context.get_executor(), std::move(init.completion_handler)); return init.result.get(); } AioResultList YieldingAioThrottle::get(rgw_raw_obj obj, OpFunc&& f, uint64_t cost, uint64_t id) { auto p = std::make_unique<Pending>(); p->obj = std::move(obj); p->id = id; p->cost = cost; if (cost > window) { p->result = -EDEADLK; // would never succeed completed.push_back(*p); } else { // wait for the write size to become available pending_size += p->cost; if (!is_available()) { ceph_assert(waiter == Wait::None); ceph_assert(!completion); boost::system::error_code ec; waiter = Wait::Available; async_wait(yield[ec]); } // register the pending write and initiate the operation pending.push_back(*p); std::move(f)(this, *static_cast<AioResult*>(p.get())); } // coverity[leaked_storage:SUPPRESS] p.release(); return std::move(completed); } void YieldingAioThrottle::put(AioResult& r) { auto& p = static_cast<Pending&>(r); // move from pending to completed pending.erase(pending.iterator_to(p)); completed.push_back(p); pending_size -= p.cost; if (waiter_ready()) { ceph_assert(completion); ceph::async::post(std::move(completion), boost::system::error_code{}); waiter = Wait::None; } } AioResultList YieldingAioThrottle::poll() { return std::move(completed); } AioResultList YieldingAioThrottle::wait() { if (!has_completion() && !pending.empty()) { ceph_assert(waiter == Wait::None); ceph_assert(!completion); boost::system::error_code ec; waiter = Wait::Completion; async_wait(yield[ec]); } return std::move(completed); } AioResultList YieldingAioThrottle::drain() { if (!is_drained()) { ceph_assert(waiter == Wait::None); ceph_assert(!completion); boost::system::error_code ec; waiter = Wait::Drained; async_wait(yield[ec]); } return std::move(completed); } } // namespace rgw
5,041
23.837438
74
cc
null
ceph-main/src/rgw/rgw_aio_throttle.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 <memory> #include "common/ceph_mutex.h" #include "common/async/completion.h" #include "common/async/yield_context.h" #include "rgw_aio.h" namespace rgw { class Throttle { protected: const uint64_t window; uint64_t pending_size = 0; AioResultList pending; AioResultList completed; bool is_available() const { return pending_size <= window; } bool has_completion() const { return !completed.empty(); } bool is_drained() const { return pending.empty(); } enum class Wait { None, Available, Completion, Drained }; Wait waiter = Wait::None; bool waiter_ready() const; public: Throttle(uint64_t window) : window(window) {} virtual ~Throttle() { // must drain before destructing ceph_assert(pending.empty()); ceph_assert(completed.empty()); } }; // a throttle for aio operations. all public functions must be called from // the same thread class BlockingAioThrottle final : public Aio, private Throttle { ceph::mutex mutex = ceph::make_mutex("AioThrottle"); ceph::condition_variable cond; struct Pending : AioResultEntry { BlockingAioThrottle *parent = nullptr; uint64_t cost = 0; }; public: BlockingAioThrottle(uint64_t window) : Throttle(window) {} virtual ~BlockingAioThrottle() override {}; AioResultList get(rgw_raw_obj obj, OpFunc&& f, uint64_t cost, uint64_t id) override final; void put(AioResult& r) override final; AioResultList poll() override final; AioResultList wait() override final; AioResultList drain() override final; }; // a throttle that yields the coroutine instead of blocking. all public // functions must be called within the coroutine strand class YieldingAioThrottle final : public Aio, private Throttle { boost::asio::io_context& context; yield_context yield; struct Handler; // completion callback associated with the waiter using Completion = ceph::async::Completion<void(boost::system::error_code)>; std::unique_ptr<Completion> completion; template <typename CompletionToken> auto async_wait(CompletionToken&& token); struct Pending : AioResultEntry { uint64_t cost = 0; }; public: YieldingAioThrottle(uint64_t window, boost::asio::io_context& context, yield_context yield) : Throttle(window), context(context), yield(yield) {} virtual ~YieldingAioThrottle() override {}; AioResultList get(rgw_raw_obj obj, OpFunc&& f, uint64_t cost, uint64_t id) override final; void put(AioResult& r) override final; AioResultList poll() override final; AioResultList wait() override final; AioResultList drain() override final; }; // return a smart pointer to Aio inline auto make_throttle(uint64_t window_size, optional_yield y) { std::unique_ptr<Aio> aio; if (y) { aio = std::make_unique<YieldingAioThrottle>(window_size, y.get_io_context(), y.get_yield_context()); } else { aio = std::make_unique<BlockingAioThrottle>(window_size); } return aio; } } // namespace rgw
3,530
25.954198
78
h
null
ceph-main/src/rgw/rgw_amqp.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_amqp.h" #include <amqp.h> #include <amqp_ssl_socket.h> #include <amqp_tcp_socket.h> #include <amqp_framing.h> #include "include/ceph_assert.h" #include <sstream> #include <cstring> #include <unordered_map> #include <string> #include <vector> #include <thread> #include <atomic> #include <mutex> #include <boost/lockfree/queue.hpp> #include <boost/functional/hash.hpp> #include "common/dout.h" #include <openssl/ssl.h> #define dout_subsys ceph_subsys_rgw // TODO investigation, not necessarily issues: // (1) in case of single threaded writer context use spsc_queue // (2) support multiple channels // (3) check performance of emptying queue to local list, and go over the list and publish // (4) use std::shared_mutex (c++17) or equivalent for the connections lock namespace rgw::amqp { // RGW AMQP status codes for publishing static const int RGW_AMQP_STATUS_BROKER_NACK = -0x1001; static const int RGW_AMQP_STATUS_CONNECTION_CLOSED = -0x1002; static const int RGW_AMQP_STATUS_QUEUE_FULL = -0x1003; static const int RGW_AMQP_STATUS_MAX_INFLIGHT = -0x1004; static const int RGW_AMQP_STATUS_MANAGER_STOPPED = -0x1005; // RGW AMQP status code for connection opening static const int RGW_AMQP_STATUS_CONN_ALLOC_FAILED = -0x2001; static const int RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED = -0x2002; static const int RGW_AMQP_STATUS_SOCKET_OPEN_FAILED = -0x2003; static const int RGW_AMQP_STATUS_LOGIN_FAILED = -0x2004; static const int RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED = -0x2005; static const int RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED = -0x2006; static const int RGW_AMQP_STATUS_Q_DECLARE_FAILED = -0x2007; static const int RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED = -0x2008; static const int RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED = -0x2009; static const int RGW_AMQP_STATUS_SOCKET_CACERT_FAILED = -0x2010; static const int RGW_AMQP_RESPONSE_SOCKET_ERROR = -0x3008; static const int RGW_AMQP_NO_REPLY_CODE = 0x0; // the amqp_connection_info struct does not hold any memory and just points to the URL string // so, strings are copied into connection_id_t connection_id_t::connection_id_t(const amqp_connection_info& info, const std::string& _exchange) : host(info.host), port(info.port), vhost(info.vhost), exchange(_exchange), ssl(info.ssl) {} // equality operator and hasher functor are needed // so that connection_id_t could be used as key in unordered_map bool operator==(const connection_id_t& lhs, const connection_id_t& rhs) { return lhs.host == rhs.host && lhs.port == rhs.port && lhs.vhost == rhs.vhost && lhs.exchange == rhs.exchange; } struct connection_id_hasher { std::size_t operator()(const connection_id_t& k) const { std::size_t h = 0; boost::hash_combine(h, k.host); boost::hash_combine(h, k.port); boost::hash_combine(h, k.vhost); boost::hash_combine(h, k.exchange); return h; } }; std::string to_string(const connection_id_t& id) { return fmt::format("{}://{}:{}{}?exchange={}", id.ssl ? "amqps" : "amqp", id.host, id.port, id.vhost, id.exchange); } // automatically cleans amqp state when gets out of scope class ConnectionCleaner { private: amqp_connection_state_t state; public: ConnectionCleaner(amqp_connection_state_t _state) : state(_state) {} ~ConnectionCleaner() { if (state) { amqp_destroy_connection(state); } } // call reset() if cleanup is not needed anymore void reset() { state = nullptr; } }; // struct for holding the callback and its tag in the callback list struct reply_callback_with_tag_t { uint64_t tag; reply_callback_t cb; reply_callback_with_tag_t(uint64_t _tag, reply_callback_t _cb) : tag(_tag), cb(_cb) {} bool operator==(uint64_t rhs) { return tag == rhs; } }; typedef std::vector<reply_callback_with_tag_t> CallbackList; // struct for holding the connection state object as well as the exchange struct connection_t { CephContext* cct = nullptr; amqp_connection_state_t state = nullptr; amqp_bytes_t reply_to_queue = amqp_empty_bytes; uint64_t delivery_tag = 1; int status = AMQP_STATUS_OK; int reply_type = AMQP_RESPONSE_NORMAL; int reply_code = RGW_AMQP_NO_REPLY_CODE; CallbackList callbacks; ceph::coarse_real_clock::time_point next_reconnect = ceph::coarse_real_clock::now(); bool mandatory = false; const bool use_ssl = false; std::string user; std::string password; bool verify_ssl = true; boost::optional<std::string> ca_location; utime_t timestamp = ceph_clock_now(); connection_t(CephContext* _cct, const amqp_connection_info& info, bool _verify_ssl, boost::optional<const std::string&> _ca_location) : cct(_cct), use_ssl(info.ssl), user(info.user), password(info.password), verify_ssl(_verify_ssl), ca_location(_ca_location) {} // cleanup of all internal connection resource // the object can still remain, and internal connection // resources created again on successful reconnection void destroy(int s) { status = s; ConnectionCleaner clean_state(state); state = nullptr; amqp_bytes_free(reply_to_queue); reply_to_queue = amqp_empty_bytes; // fire all remaining callbacks std::for_each(callbacks.begin(), callbacks.end(), [this](auto& cb_tag) { cb_tag.cb(status); ldout(cct, 20) << "AMQP destroy: invoking callback with tag=" << cb_tag.tag << dendl; }); callbacks.clear(); delivery_tag = 1; } bool is_ok() const { return (state != nullptr); } // dtor also destroys the internals ~connection_t() { destroy(RGW_AMQP_STATUS_CONNECTION_CLOSED); } }; // convert connection info to string std::string to_string(const amqp_connection_info& info) { std::stringstream ss; ss << "connection info:" << "\nHost: " << info.host << "\nPort: " << info.port << "\nUser: " << info.user << "\nPassword: " << info.password << "\nvhost: " << info.vhost << "\nSSL support: " << info.ssl << std::endl; return ss.str(); } // convert reply to error code int reply_to_code(const amqp_rpc_reply_t& reply) { switch (reply.reply_type) { case AMQP_RESPONSE_NONE: case AMQP_RESPONSE_NORMAL: return RGW_AMQP_NO_REPLY_CODE; case AMQP_RESPONSE_LIBRARY_EXCEPTION: return reply.library_error; case AMQP_RESPONSE_SERVER_EXCEPTION: if (reply.reply.decoded) { const amqp_connection_close_t* m = (amqp_connection_close_t*)reply.reply.decoded; return m->reply_code; } return reply.reply.id; } return RGW_AMQP_NO_REPLY_CODE; } // convert reply to string std::string to_string(const amqp_rpc_reply_t& reply) { std::stringstream ss; switch (reply.reply_type) { case AMQP_RESPONSE_NORMAL: return ""; case AMQP_RESPONSE_NONE: return "missing RPC reply type"; case AMQP_RESPONSE_LIBRARY_EXCEPTION: return amqp_error_string2(reply.library_error); case AMQP_RESPONSE_SERVER_EXCEPTION: { switch (reply.reply.id) { case AMQP_CONNECTION_CLOSE_METHOD: ss << "server connection error: "; break; case AMQP_CHANNEL_CLOSE_METHOD: ss << "server channel error: "; break; default: ss << "server unknown error: "; break; } if (reply.reply.decoded) { amqp_connection_close_t* m = (amqp_connection_close_t*)reply.reply.decoded; ss << m->reply_code << " text: " << std::string((char*)m->reply_text.bytes, m->reply_text.len); } return ss.str(); } default: ss << "unknown error, method id: " << reply.reply.id; return ss.str(); } } // convert status enum to string std::string to_string(amqp_status_enum s) { switch (s) { case AMQP_STATUS_OK: return "AMQP_STATUS_OK"; case AMQP_STATUS_NO_MEMORY: return "AMQP_STATUS_NO_MEMORY"; case AMQP_STATUS_BAD_AMQP_DATA: return "AMQP_STATUS_BAD_AMQP_DATA"; case AMQP_STATUS_UNKNOWN_CLASS: return "AMQP_STATUS_UNKNOWN_CLASS"; case AMQP_STATUS_UNKNOWN_METHOD: return "AMQP_STATUS_UNKNOWN_METHOD"; case AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED: return "AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED"; case AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION: return "AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION"; case AMQP_STATUS_CONNECTION_CLOSED: return "AMQP_STATUS_CONNECTION_CLOSED"; case AMQP_STATUS_BAD_URL: return "AMQP_STATUS_BAD_URL"; case AMQP_STATUS_SOCKET_ERROR: return "AMQP_STATUS_SOCKET_ERROR"; case AMQP_STATUS_INVALID_PARAMETER: return "AMQP_STATUS_INVALID_PARAMETER"; case AMQP_STATUS_TABLE_TOO_BIG: return "AMQP_STATUS_TABLE_TOO_BIG"; case AMQP_STATUS_WRONG_METHOD: return "AMQP_STATUS_WRONG_METHOD"; case AMQP_STATUS_TIMEOUT: return "AMQP_STATUS_TIMEOUT"; case AMQP_STATUS_TIMER_FAILURE: return "AMQP_STATUS_TIMER_FAILURE"; case AMQP_STATUS_HEARTBEAT_TIMEOUT: return "AMQP_STATUS_HEARTBEAT_TIMEOUT"; case AMQP_STATUS_UNEXPECTED_STATE: return "AMQP_STATUS_UNEXPECTED_STATE"; case AMQP_STATUS_SOCKET_CLOSED: return "AMQP_STATUS_SOCKET_CLOSED"; case AMQP_STATUS_SOCKET_INUSE: return "AMQP_STATUS_SOCKET_INUSE"; case AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD: return "AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD"; #if AMQP_VERSION >= AMQP_VERSION_CODE(0, 8, 0, 0) case AMQP_STATUS_UNSUPPORTED: return "AMQP_STATUS_UNSUPPORTED"; #endif case _AMQP_STATUS_NEXT_VALUE: return "AMQP_STATUS_INTERNAL"; case AMQP_STATUS_TCP_ERROR: return "AMQP_STATUS_TCP_ERROR"; case AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR: return "AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR"; case _AMQP_STATUS_TCP_NEXT_VALUE: return "AMQP_STATUS_INTERNAL"; case AMQP_STATUS_SSL_ERROR: return "AMQP_STATUS_SSL_ERROR"; case AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED: return "AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED"; case AMQP_STATUS_SSL_PEER_VERIFY_FAILED: return "AMQP_STATUS_SSL_PEER_VERIFY_FAILED"; case AMQP_STATUS_SSL_CONNECTION_FAILED: return "AMQP_STATUS_SSL_CONNECTION_FAILED"; case _AMQP_STATUS_SSL_NEXT_VALUE: return "AMQP_STATUS_INTERNAL"; #if AMQP_VERSION >= AMQP_VERSION_CODE(0, 11, 0, 0) case AMQP_STATUS_SSL_SET_ENGINE_FAILED: return "AMQP_STATUS_SSL_SET_ENGINE_FAILED"; #endif default: return "AMQP_STATUS_UNKNOWN"; } } // TODO: add status_to_string on the connection object to prinf full status // convert int status to string - including RGW specific values std::string status_to_string(int s) { switch (s) { case RGW_AMQP_STATUS_BROKER_NACK: return "RGW_AMQP_STATUS_BROKER_NACK"; case RGW_AMQP_STATUS_CONNECTION_CLOSED: return "RGW_AMQP_STATUS_CONNECTION_CLOSED"; case RGW_AMQP_STATUS_QUEUE_FULL: return "RGW_AMQP_STATUS_QUEUE_FULL"; case RGW_AMQP_STATUS_MAX_INFLIGHT: return "RGW_AMQP_STATUS_MAX_INFLIGHT"; case RGW_AMQP_STATUS_MANAGER_STOPPED: return "RGW_AMQP_STATUS_MANAGER_STOPPED"; case RGW_AMQP_STATUS_CONN_ALLOC_FAILED: return "RGW_AMQP_STATUS_CONN_ALLOC_FAILED"; case RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED: return "RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED"; case RGW_AMQP_STATUS_SOCKET_OPEN_FAILED: return "RGW_AMQP_STATUS_SOCKET_OPEN_FAILED"; case RGW_AMQP_STATUS_LOGIN_FAILED: return "RGW_AMQP_STATUS_LOGIN_FAILED"; case RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED: return "RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED"; case RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED: return "RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED"; case RGW_AMQP_STATUS_Q_DECLARE_FAILED: return "RGW_AMQP_STATUS_Q_DECLARE_FAILED"; case RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED: return "RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED"; case RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED: return "RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED"; case RGW_AMQP_STATUS_SOCKET_CACERT_FAILED: return "RGW_AMQP_STATUS_SOCKET_CACERT_FAILED"; } return to_string((amqp_status_enum)s); } // check the result from calls and return if error (=null) #define RETURN_ON_ERROR(C, S, OK) \ if (!OK) { \ C->status = S; \ return false; \ } // in case of RPC calls, getting the RPC reply and return if an error is detected #define RETURN_ON_REPLY_ERROR(C, ST, S) { \ const auto reply = amqp_get_rpc_reply(ST); \ if (reply.reply_type != AMQP_RESPONSE_NORMAL) { \ C->status = S; \ C->reply_type = reply.reply_type; \ C->reply_code = reply_to_code(reply); \ return false; \ } \ } static const amqp_channel_t CHANNEL_ID = 1; static const amqp_channel_t CONFIRMING_CHANNEL_ID = 2; // utility function to create a connection, when the connection object already exists bool new_state(connection_t* conn, const connection_id_t& conn_id) { // state must be null at this point ceph_assert(!conn->state); // reset all status codes conn->status = AMQP_STATUS_OK; conn->reply_type = AMQP_RESPONSE_NORMAL; conn->reply_code = RGW_AMQP_NO_REPLY_CODE; auto state = amqp_new_connection(); if (!state) { conn->status = RGW_AMQP_STATUS_CONN_ALLOC_FAILED; return false; } // make sure that the connection state is cleaned up in case of error ConnectionCleaner state_guard(state); // create and open socket amqp_socket_t *socket = nullptr; if (conn->use_ssl) { socket = amqp_ssl_socket_new(state); #if AMQP_VERSION >= AMQP_VERSION_CODE(0, 10, 0, 1) SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(amqp_ssl_socket_get_context(socket)); #else // taken from https://github.com/alanxz/rabbitmq-c/pull/560 struct hack { const struct amqp_socket_class_t *klass; SSL_CTX *ctx; }; struct hack *h = reinterpret_cast<struct hack*>(socket); SSL_CTX* ssl_ctx = h->ctx; #endif // ensure system CA certificates get loaded SSL_CTX_set_default_verify_paths(ssl_ctx); } else { socket = amqp_tcp_socket_new(state); } if (!socket) { conn->status = RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED; return false; } if (conn->use_ssl) { if (!conn->verify_ssl) { amqp_ssl_socket_set_verify_peer(socket, 0); amqp_ssl_socket_set_verify_hostname(socket, 0); } if (conn->ca_location.has_value()) { const auto s = amqp_ssl_socket_set_cacert(socket, conn->ca_location.get().c_str()); if (s != AMQP_STATUS_OK) { conn->status = RGW_AMQP_STATUS_SOCKET_CACERT_FAILED; conn->reply_code = s; return false; } } } const auto s = amqp_socket_open(socket, conn_id.host.c_str(), conn_id.port); if (s < 0) { conn->status = RGW_AMQP_STATUS_SOCKET_OPEN_FAILED; conn->reply_type = RGW_AMQP_RESPONSE_SOCKET_ERROR; conn->reply_code = s; return false; } // login to broker const auto reply = amqp_login(state, conn_id.vhost.c_str(), AMQP_DEFAULT_MAX_CHANNELS, AMQP_DEFAULT_FRAME_SIZE, 0, // no heartbeat TODO: add conf AMQP_SASL_METHOD_PLAIN, // TODO: add other types of security conn->user.c_str(), conn->password.c_str()); if (reply.reply_type != AMQP_RESPONSE_NORMAL) { conn->status = RGW_AMQP_STATUS_LOGIN_FAILED; conn->reply_type = reply.reply_type; conn->reply_code = reply_to_code(reply); return false; } // open channels { const auto ok = amqp_channel_open(state, CHANNEL_ID); RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED, ok); RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED); } { const auto ok = amqp_channel_open(state, CONFIRMING_CHANNEL_ID); RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED, ok); RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED); } { const auto ok = amqp_confirm_select(state, CONFIRMING_CHANNEL_ID); RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED, ok); RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED); } // verify that the topic exchange is there // TODO: make this step optional { const auto ok = amqp_exchange_declare(state, CHANNEL_ID, amqp_cstring_bytes(conn_id.exchange.c_str()), amqp_cstring_bytes("topic"), 1, // passive - exchange must already exist on broker 1, // durable 0, // dont auto-delete 0, // not internal amqp_empty_table); RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED, ok); RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED); } { // create queue for confirmations const auto queue_ok = amqp_queue_declare(state, CHANNEL_ID, // use the regular channel for this call amqp_empty_bytes, // let broker allocate queue name 0, // not passive - create the queue 0, // not durable 1, // exclusive 1, // auto-delete amqp_empty_table // not args TODO add args from conf: TTL, max length etc. ); RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_Q_DECLARE_FAILED, queue_ok); RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_Q_DECLARE_FAILED); // define consumption for connection const auto consume_ok = amqp_basic_consume(state, CONFIRMING_CHANNEL_ID, queue_ok->queue, amqp_empty_bytes, // broker will generate consumer tag 1, // messages sent from client are never routed back 1, // client does not ack thr acks 1, // exclusive access to queue amqp_empty_table // no parameters ); RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED, consume_ok); RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED); // broker generated consumer_tag could be used to cancel sending of n/acks from broker - not needed state_guard.reset(); conn->state = state; conn->reply_to_queue = amqp_bytes_malloc_dup(queue_ok->queue); } return true; } /// struct used for holding messages in the message queue struct message_wrapper_t { connection_id_t conn_id; std::string topic; std::string message; reply_callback_t cb; message_wrapper_t(const connection_id_t& _conn_id, const std::string& _topic, const std::string& _message, reply_callback_t _cb) : conn_id(_conn_id), topic(_topic), message(_message), cb(_cb) {} }; using connection_t_ptr = std::unique_ptr<connection_t>; typedef std::unordered_map<connection_id_t, connection_t_ptr, connection_id_hasher> ConnectionList; typedef boost::lockfree::queue<message_wrapper_t*, boost::lockfree::fixed_sized<true>> MessageQueue; // macros used inside a loop where an iterator is either incremented or erased #define INCREMENT_AND_CONTINUE(IT) \ ++IT; \ continue; #define ERASE_AND_CONTINUE(IT,CONTAINER) \ IT=CONTAINER.erase(IT); \ --connection_count; \ continue; class Manager { public: const size_t max_connections; const size_t max_inflight; const size_t max_queue; const size_t max_idle_time; private: std::atomic<size_t> connection_count; std::atomic<bool> stopped; struct timeval read_timeout; ConnectionList connections; MessageQueue messages; std::atomic<size_t> queued; std::atomic<size_t> dequeued; CephContext* const cct; mutable std::mutex connections_lock; const ceph::coarse_real_clock::duration idle_time; const ceph::coarse_real_clock::duration reconnect_time; std::thread runner; void publish_internal(message_wrapper_t* message) { const std::unique_ptr<message_wrapper_t> msg_owner(message); const auto& conn_id = message->conn_id; auto conn_it = connections.find(conn_id); if (conn_it == connections.end()) { ldout(cct, 1) << "AMQP publish: connection '" << to_string(conn_id) << "' not found" << dendl; if (message->cb) { message->cb(RGW_AMQP_STATUS_CONNECTION_CLOSED); } return; } auto& conn = conn_it->second; conn->timestamp = ceph_clock_now(); if (!conn->is_ok()) { // connection had an issue while message was in the queue ldout(cct, 1) << "AMQP publish: connection '" << to_string(conn_id) << "' is closed" << dendl; if (message->cb) { message->cb(RGW_AMQP_STATUS_CONNECTION_CLOSED); } return; } if (message->cb == nullptr) { const auto rc = amqp_basic_publish(conn->state, CHANNEL_ID, amqp_cstring_bytes(conn_id.exchange.c_str()), amqp_cstring_bytes(message->topic.c_str()), 0, // does not have to be routable 0, // not immediate nullptr, // no properties needed amqp_cstring_bytes(message->message.c_str())); if (rc == AMQP_STATUS_OK) { ldout(cct, 20) << "AMQP publish (no callback): OK" << dendl; return; } ldout(cct, 1) << "AMQP publish (no callback): failed with error " << status_to_string(rc) << dendl; // an error occurred, close connection // it will be retied by the main loop conn->destroy(rc); return; } amqp_basic_properties_t props; props._flags = AMQP_BASIC_DELIVERY_MODE_FLAG | AMQP_BASIC_REPLY_TO_FLAG; props.delivery_mode = 2; // persistent delivery TODO take from conf props.reply_to = conn->reply_to_queue; const auto rc = amqp_basic_publish(conn->state, CONFIRMING_CHANNEL_ID, amqp_cstring_bytes(conn_id.exchange.c_str()), amqp_cstring_bytes(message->topic.c_str()), conn->mandatory, 0, // not immediate &props, amqp_cstring_bytes(message->message.c_str())); if (rc == AMQP_STATUS_OK) { auto const q_len = conn->callbacks.size(); if (q_len < max_inflight) { ldout(cct, 20) << "AMQP publish (with callback, tag=" << conn->delivery_tag << "): OK. Queue has: " << q_len << " callbacks" << dendl; conn->callbacks.emplace_back(conn->delivery_tag++, message->cb); } else { // immediately invoke callback with error ldout(cct, 1) << "AMQP publish (with callback): failed with error: callback queue full" << dendl; message->cb(RGW_AMQP_STATUS_MAX_INFLIGHT); } } else { // an error occurred, close connection // it will be retied by the main loop ldout(cct, 1) << "AMQP publish (with callback): failed with error: " << status_to_string(rc) << dendl; conn->destroy(rc); // immediately invoke callback with error message->cb(rc); } } // the managers thread: // (1) empty the queue of messages to be published // (2) loop over all connections and read acks // (3) manages deleted connections // (4) TODO reconnect on connection errors // (5) TODO cleanup timedout callbacks void run() noexcept { amqp_frame_t frame; while (!stopped) { // publish all messages in the queue const auto count = messages.consume_all(std::bind(&Manager::publish_internal, this, std::placeholders::_1)); dequeued += count; ConnectionList::iterator conn_it; ConnectionList::const_iterator end_it; { // thread safe access to the connection list // once the iterators are fetched they are guaranteed to remain valid std::lock_guard lock(connections_lock); conn_it = connections.begin(); end_it = connections.end(); } auto incoming_message = false; // loop over all connections to read acks for (;conn_it != end_it;) { const auto& conn_id = conn_it->first; auto& conn = conn_it->second; if(conn->timestamp.sec() + max_idle_time < ceph_clock_now()) { ldout(cct, 20) << "AMQP run: Time for deleting a connection due to idle behaviour: " << ceph_clock_now() << dendl; ERASE_AND_CONTINUE(conn_it, connections); } // try to reconnect the connection if it has an error if (!conn->is_ok()) { const auto now = ceph::coarse_real_clock::now(); if (now >= conn->next_reconnect) { // pointers are used temporarily inside the amqp_connection_info object // as read-only values, hence the assignment, and const_cast are safe here ldout(cct, 20) << "AMQP run: retry connection" << dendl; if (!new_state(conn.get(), conn_id)) { ldout(cct, 10) << "AMQP run: connection '" << to_string(conn_id) << "' retry failed. error: " << status_to_string(conn->status) << " (" << conn->reply_code << ")" << dendl; // TODO: add error counter for failed retries // TODO: add exponential backoff for retries conn->next_reconnect = now + reconnect_time; } else { ldout(cct, 10) << "AMQP run: connection '" << to_string(conn_id) << "' retry successfull" << dendl; } } INCREMENT_AND_CONTINUE(conn_it); } const auto rc = amqp_simple_wait_frame_noblock(conn->state, &frame, &read_timeout); if (rc == AMQP_STATUS_TIMEOUT) { // TODO mark connection as idle INCREMENT_AND_CONTINUE(conn_it); } // this is just to prevent spinning idle, does not indicate that a message // was successfully processed or not incoming_message = true; // check if error occurred that require reopening the connection if (rc != AMQP_STATUS_OK) { // an error occurred, close connection // it will be retied by the main loop ldout(cct, 1) << "AMQP run: connection read error: " << status_to_string(rc) << dendl; conn->destroy(rc); INCREMENT_AND_CONTINUE(conn_it); } if (frame.frame_type != AMQP_FRAME_METHOD) { ldout(cct, 10) << "AMQP run: ignoring non n/ack messages. frame type: " << unsigned(frame.frame_type) << dendl; // handler is for publish confirmation only - handle only method frames INCREMENT_AND_CONTINUE(conn_it); } uint64_t tag; bool multiple; int result; switch (frame.payload.method.id) { case AMQP_BASIC_ACK_METHOD: { result = AMQP_STATUS_OK; const auto ack = (amqp_basic_ack_t*)frame.payload.method.decoded; ceph_assert(ack); tag = ack->delivery_tag; multiple = ack->multiple; break; } case AMQP_BASIC_NACK_METHOD: { result = RGW_AMQP_STATUS_BROKER_NACK; const auto nack = (amqp_basic_nack_t*)frame.payload.method.decoded; ceph_assert(nack); tag = nack->delivery_tag; multiple = nack->multiple; break; } case AMQP_BASIC_REJECT_METHOD: { result = RGW_AMQP_STATUS_BROKER_NACK; const auto reject = (amqp_basic_reject_t*)frame.payload.method.decoded; tag = reject->delivery_tag; multiple = false; break; } case AMQP_CONNECTION_CLOSE_METHOD: // TODO on channel close, no need to reopen the connection case AMQP_CHANNEL_CLOSE_METHOD: { // other side closed the connection, no need to continue ldout(cct, 10) << "AMQP run: connection was closed by broker" << dendl; conn->destroy(rc); INCREMENT_AND_CONTINUE(conn_it); } case AMQP_BASIC_RETURN_METHOD: // message was not delivered, returned to sender ldout(cct, 10) << "AMQP run: message was not routable" << dendl; INCREMENT_AND_CONTINUE(conn_it); break; default: // unexpected method ldout(cct, 10) << "AMQP run: unexpected message" << dendl; INCREMENT_AND_CONTINUE(conn_it); } const auto tag_it = std::find(conn->callbacks.begin(), conn->callbacks.end(), tag); if (tag_it != conn->callbacks.end()) { if (multiple) { // n/ack all up to (and including) the tag ldout(cct, 20) << "AMQP run: multiple n/acks received with tag=" << tag << " and result=" << result << dendl; auto it = conn->callbacks.begin(); while (it->tag <= tag && it != conn->callbacks.end()) { ldout(cct, 20) << "AMQP run: invoking callback with tag=" << it->tag << dendl; it->cb(result); it = conn->callbacks.erase(it); } } else { // n/ack a specific tag ldout(cct, 20) << "AMQP run: n/ack received, invoking callback with tag=" << tag << " and result=" << result << dendl; tag_it->cb(result); conn->callbacks.erase(tag_it); } } else { ldout(cct, 10) << "AMQP run: unsolicited n/ack received with tag=" << tag << dendl; } // just increment the iterator ++conn_it; } // if no messages were received or published, sleep for 100ms if (count == 0 && !incoming_message) { std::this_thread::sleep_for(idle_time); } } } // used in the dtor for message cleanup static void delete_message(const message_wrapper_t* message) { delete message; } public: Manager(size_t _max_connections, size_t _max_inflight, size_t _max_queue, long _usec_timeout, unsigned reconnect_time_ms, unsigned idle_time_ms, CephContext* _cct) : max_connections(_max_connections), max_inflight(_max_inflight), max_queue(_max_queue), max_idle_time(30), connection_count(0), stopped(false), read_timeout{0, _usec_timeout}, connections(_max_connections), messages(max_queue), queued(0), dequeued(0), cct(_cct), idle_time(std::chrono::milliseconds(idle_time_ms)), reconnect_time(std::chrono::milliseconds(reconnect_time_ms)), runner(&Manager::run, this) { // The hashmap has "max connections" as the initial number of buckets, // and allows for 10 collisions per bucket before rehash. // This is to prevent rehashing so that iterators are not invalidated // when a new connection is added. connections.max_load_factor(10.0); // give the runner thread a name for easier debugging const auto rc = ceph_pthread_setname(runner.native_handle(), "amqp_manager"); ceph_assert(rc==0); } // non copyable Manager(const Manager&) = delete; const Manager& operator=(const Manager&) = delete; // stop the main thread void stop() { stopped = true; } // connect to a broker, or reuse an existing connection if already connected bool connect(connection_id_t& id, const std::string& url, const std::string& exchange, bool mandatory_delivery, bool verify_ssl, boost::optional<const std::string&> ca_location) { if (stopped) { ldout(cct, 1) << "AMQP connect: manager is stopped" << dendl; return false; } amqp_connection_info info; // cache the URL so that parsing could happen in-place std::vector<char> url_cache(url.c_str(), url.c_str()+url.size()+1); const auto retcode = amqp_parse_url(url_cache.data(), &info); if (AMQP_STATUS_OK != retcode) { ldout(cct, 1) << "AMQP connect: URL parsing failed. error: " << retcode << dendl; return false; } connection_id_t tmp_id(info, exchange); std::lock_guard lock(connections_lock); const auto it = connections.find(tmp_id); if (it != connections.end()) { // connection found - return even if non-ok ldout(cct, 20) << "AMQP connect: connection found" << dendl; id = it->first; return true; } // connection not found, creating a new one if (connection_count >= max_connections) { ldout(cct, 1) << "AMQP connect: max connections exceeded" << dendl; return false; } // if error occurred during creation the creation will be retried in the main thread ++connection_count; auto conn = connections.emplace(tmp_id, std::make_unique<connection_t>(cct, info, verify_ssl, ca_location)).first->second.get(); ldout(cct, 10) << "AMQP connect: new connection is created. Total connections: " << connection_count << dendl; if (!new_state(conn, tmp_id)) { ldout(cct, 1) << "AMQP connect: new connection '" << to_string(tmp_id) << "' is created. but state creation failed (will retry). error: " << status_to_string(conn->status) << " (" << conn->reply_code << ")" << dendl; } id = std::move(tmp_id); return true; } // TODO publish with confirm is needed in "none" case as well, cb should be invoked publish is ok (no ack) int publish(const connection_id_t& conn_id, const std::string& topic, const std::string& message) { if (stopped) { ldout(cct, 1) << "AMQP publish: manager is not running" << dendl; return RGW_AMQP_STATUS_MANAGER_STOPPED; } auto wrapper = std::make_unique<message_wrapper_t>(conn_id, topic, message, nullptr); if (messages.push(wrapper.get())) { std::ignore = wrapper.release(); ++queued; return AMQP_STATUS_OK; } ldout(cct, 1) << "AMQP publish: queue is full" << dendl; return RGW_AMQP_STATUS_QUEUE_FULL; } int publish_with_confirm(const connection_id_t& conn_id, const std::string& topic, const std::string& message, reply_callback_t cb) { if (stopped) { ldout(cct, 1) << "AMQP publish_with_confirm: manager is not running" << dendl; return RGW_AMQP_STATUS_MANAGER_STOPPED; } auto wrapper = std::make_unique<message_wrapper_t>(conn_id, topic, message, cb); if (messages.push(wrapper.get())) { std::ignore = wrapper.release(); ++queued; return AMQP_STATUS_OK; } ldout(cct, 1) << "AMQP publish_with_confirm: queue is full" << dendl; return RGW_AMQP_STATUS_QUEUE_FULL; } // dtor wait for thread to stop // then connection are cleaned-up ~Manager() { stopped = true; runner.join(); messages.consume_all(delete_message); } // get the number of connections size_t get_connection_count() const { return connection_count; } // get the number of in-flight messages size_t get_inflight() const { size_t sum = 0; std::lock_guard lock(connections_lock); std::for_each(connections.begin(), connections.end(), [&sum](auto& conn_pair) { // concurrent access to the callback vector is safe without locking sum += conn_pair.second->callbacks.size(); }); return sum; } // running counter of the queued messages size_t get_queued() const { return queued; } // running counter of the dequeued messages size_t get_dequeued() const { return dequeued; } }; // singleton manager // note that the manager itself is not a singleton, and multiple instances may co-exist // TODO make the pointer atomic in allocation and deallocation to avoid race conditions static Manager* s_manager = nullptr; static const size_t MAX_CONNECTIONS_DEFAULT = 256; static const size_t MAX_INFLIGHT_DEFAULT = 8192; static const size_t MAX_QUEUE_DEFAULT = 8192; static const long READ_TIMEOUT_USEC = 100; static const unsigned IDLE_TIME_MS = 100; static const unsigned RECONNECT_TIME_MS = 100; bool init(CephContext* cct) { if (s_manager) { return false; } // TODO: take conf from CephContext s_manager = new Manager(MAX_CONNECTIONS_DEFAULT, MAX_INFLIGHT_DEFAULT, MAX_QUEUE_DEFAULT, READ_TIMEOUT_USEC, IDLE_TIME_MS, RECONNECT_TIME_MS, cct); return true; } void shutdown() { delete s_manager; s_manager = nullptr; } bool connect(connection_id_t& conn_id, const std::string& url, const std::string& exchange, bool mandatory_delivery, bool verify_ssl, boost::optional<const std::string&> ca_location) { if (!s_manager) return false; return s_manager->connect(conn_id, url, exchange, mandatory_delivery, verify_ssl, ca_location); } int publish(const connection_id_t& conn_id, const std::string& topic, const std::string& message) { if (!s_manager) return RGW_AMQP_STATUS_MANAGER_STOPPED; return s_manager->publish(conn_id, topic, message); } int publish_with_confirm(const connection_id_t& conn_id, const std::string& topic, const std::string& message, reply_callback_t cb) { if (!s_manager) return RGW_AMQP_STATUS_MANAGER_STOPPED; return s_manager->publish_with_confirm(conn_id, topic, message, cb); } size_t get_connection_count() { if (!s_manager) return 0; return s_manager->get_connection_count(); } size_t get_inflight() { if (!s_manager) return 0; return s_manager->get_inflight(); } size_t get_queued() { if (!s_manager) return 0; return s_manager->get_queued(); } size_t get_dequeued() { if (!s_manager) return 0; return s_manager->get_dequeued(); } size_t get_max_connections() { if (!s_manager) return MAX_CONNECTIONS_DEFAULT; return s_manager->max_connections; } size_t get_max_inflight() { if (!s_manager) return MAX_INFLIGHT_DEFAULT; return s_manager->max_inflight; } size_t get_max_queue() { if (!s_manager) return MAX_QUEUE_DEFAULT; return s_manager->max_queue; } } // namespace amqp
37,625
34.76616
146
cc
null
ceph-main/src/rgw/rgw_amqp.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string> #include <functional> #include <boost/optional.hpp> #include "include/common_fwd.h" struct amqp_connection_info; namespace rgw::amqp { // the reply callback is expected to get an integer parameter // indicating the result, and not to return anything typedef std::function<void(int)> reply_callback_t; // initialize the amqp manager bool init(CephContext* cct); // shutdown the amqp manager void shutdown(); // key class for the connection list struct connection_id_t { std::string host; int port; std::string vhost; std::string exchange; bool ssl; connection_id_t() = default; connection_id_t(const amqp_connection_info& info, const std::string& _exchange); }; std::string to_string(const connection_id_t& id); // connect to an amqp endpoint bool connect(connection_id_t& conn_id, const std::string& url, const std::string& exchange, bool mandatory_delivery, bool verify_ssl, boost::optional<const std::string&> ca_location); // publish a message over a connection that was already created int publish(const connection_id_t& conn_id, const std::string& topic, const std::string& message); // publish a message over a connection that was already created // and pass a callback that will be invoked (async) when broker confirms // receiving the message int publish_with_confirm(const connection_id_t& conn_id, const std::string& topic, const std::string& message, reply_callback_t cb); // convert the integer status returned from the "publish" function to a string std::string status_to_string(int s); // number of connections size_t get_connection_count(); // return the number of messages that were sent // to broker, but were not yet acked/nacked/timedout size_t get_inflight(); // running counter of successfully queued messages size_t get_queued(); // running counter of dequeued messages size_t get_dequeued(); // number of maximum allowed connections size_t get_max_connections(); // number of maximum allowed inflight messages size_t get_max_inflight(); // maximum number of messages in the queue size_t get_max_queue(); }
2,234
25.927711
133
h
null
ceph-main/src/rgw/rgw_appmain.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2022 Red Hat, Inc * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <boost/intrusive/list.hpp> #include "global/global_init.h" #include "global/signal_handler.h" #include "common/config.h" #include "common/errno.h" #include "common/Timer.h" #include "common/TracepointProvider.h" #include "common/openssl_opts_handler.h" #include "common/numa.h" #include "include/compat.h" #include "include/str_list.h" #include "include/stringify.h" #include "rgw_main.h" #include "rgw_common.h" #include "rgw_sal.h" #include "rgw_sal_config.h" #include "rgw_period_pusher.h" #include "rgw_realm_reloader.h" #include "rgw_rest.h" #include "rgw_rest_s3.h" #include "rgw_rest_swift.h" #include "rgw_rest_admin.h" #include "rgw_rest_info.h" #include "rgw_rest_usage.h" #include "rgw_rest_bucket.h" #include "rgw_rest_metadata.h" #include "rgw_rest_log.h" #include "rgw_rest_config.h" #include "rgw_rest_realm.h" #include "rgw_rest_ratelimit.h" #include "rgw_rest_zero.h" #include "rgw_swift_auth.h" #include "rgw_log.h" #include "rgw_lib.h" #include "rgw_frontend.h" #include "rgw_lib_frontend.h" #include "rgw_tools.h" #include "rgw_resolve.h" #include "rgw_process.h" #include "rgw_frontend.h" #include "rgw_http_client_curl.h" #include "rgw_kmip_client.h" #include "rgw_kmip_client_impl.h" #include "rgw_perf_counters.h" #include "rgw_signal.h" #ifdef WITH_RADOSGW_AMQP_ENDPOINT #include "rgw_amqp.h" #endif #ifdef WITH_RADOSGW_KAFKA_ENDPOINT #include "rgw_kafka.h" #endif #ifdef WITH_ARROW_FLIGHT #include "rgw_flight_frontend.h" #endif #include "rgw_asio_frontend.h" #include "rgw_dmclock_scheduler_ctx.h" #include "rgw_lua.h" #ifdef WITH_RADOSGW_DBSTORE #include "rgw_sal_dbstore.h" #endif #include "rgw_lua_background.h" #include "services/svc_zone.h" #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #define dout_subsys ceph_subsys_rgw using namespace std; namespace { TracepointProvider::Traits rgw_op_tracepoint_traits( "librgw_op_tp.so", "rgw_op_tracing"); TracepointProvider::Traits rgw_rados_tracepoint_traits( "librgw_rados_tp.so", "rgw_rados_tracing"); } OpsLogFile* rgw::AppMain::ops_log_file; rgw::AppMain::AppMain(const DoutPrefixProvider* dpp) : dpp(dpp) { } rgw::AppMain::~AppMain() = default; void rgw::AppMain::init_frontends1(bool nfs) { this->nfs = nfs; std::string fe_key = (nfs) ? "rgw_nfs_frontends" : "rgw_frontends"; std::vector<std::string> frontends; std::string rgw_frontends_str = g_conf().get_val<string>(fe_key); g_conf().early_expand_meta(rgw_frontends_str, &cerr); get_str_vec(rgw_frontends_str, ",", frontends); /* default frontends */ if (nfs) { const auto is_rgw_nfs = [](const auto& s){return s == "rgw-nfs";}; if (std::find_if(frontends.begin(), frontends.end(), is_rgw_nfs) == frontends.end()) { frontends.push_back("rgw-nfs"); } } else { if (frontends.empty()) { frontends.push_back("beast"); } } for (auto &f : frontends) { if (f.find("beast") != string::npos) { have_http_frontend = true; if (f.find("port") != string::npos) { // check for the most common ws problems if ((f.find("port=") == string::npos) || (f.find("port= ") != string::npos)) { derr << R"(WARNING: radosgw frontend config found unexpected spacing around 'port' (ensure frontend port parameter has the form 'port=80' with no spaces before or after '='))" << dendl; } } } else { if (f.find("civetweb") != string::npos) { have_http_frontend = true; } } /* fe !beast */ RGWFrontendConfig *config = new RGWFrontendConfig(f); int r = config->init(); if (r < 0) { delete config; cerr << "ERROR: failed to init config: " << f << std::endl; continue; } fe_configs.push_back(config); fe_map.insert( pair<string, RGWFrontendConfig *>(config->get_framework(), config)); } /* for each frontend */ // maintain existing region root pool for new multisite objects if (!g_conf()->rgw_region_root_pool.empty()) { const char *root_pool = g_conf()->rgw_region_root_pool.c_str(); if (g_conf()->rgw_zonegroup_root_pool.empty()) { g_conf().set_val_or_die("rgw_zonegroup_root_pool", root_pool); } if (g_conf()->rgw_period_root_pool.empty()) { g_conf().set_val_or_die("rgw_period_root_pool", root_pool); } if (g_conf()->rgw_realm_root_pool.empty()) { g_conf().set_val_or_die("rgw_realm_root_pool", root_pool); } } // for region -> zonegroup conversion (must happen before // common_init_finish()) if (!g_conf()->rgw_region.empty() && g_conf()->rgw_zonegroup.empty()) { g_conf().set_val_or_die("rgw_zonegroup", g_conf()->rgw_region.c_str()); } ceph::crypto::init_openssl_engine_once(); } /* init_frontends1 */ void rgw::AppMain::init_numa() { if (nfs) { return; } int numa_node = g_conf().get_val<int64_t>("rgw_numa_node"); size_t numa_cpu_set_size = 0; cpu_set_t numa_cpu_set; if (numa_node >= 0) { int r = get_numa_node_cpu_set(numa_node, &numa_cpu_set_size, &numa_cpu_set); if (r < 0) { dout(1) << __func__ << " unable to determine rgw numa node " << numa_node << " CPUs" << dendl; numa_node = -1; } else { r = set_cpu_affinity_all_threads(numa_cpu_set_size, &numa_cpu_set); if (r < 0) { derr << __func__ << " failed to set numa affinity: " << cpp_strerror(r) << dendl; } } } else { dout(1) << __func__ << " not setting numa affinity" << dendl; } } /* init_numa */ int rgw::AppMain::init_storage() { auto config_store_type = g_conf().get_val<std::string>("rgw_config_store"); cfgstore = DriverManager::create_config_store(dpp, config_store_type); if (!cfgstore) { return -EIO; } env.cfgstore = cfgstore.get(); int r = site.load(dpp, null_yield, cfgstore.get()); if (r < 0) { return r; } env.site = &site; auto run_gc = (g_conf()->rgw_enable_gc_threads && ((!nfs) || (nfs && g_conf()->rgw_nfs_run_gc_threads))); auto run_lc = (g_conf()->rgw_enable_lc_threads && ((!nfs) || (nfs && g_conf()->rgw_nfs_run_lc_threads))); auto run_quota = (g_conf()->rgw_enable_quota_threads && ((!nfs) || (nfs && g_conf()->rgw_nfs_run_quota_threads))); auto run_sync = (g_conf()->rgw_run_sync_thread && ((!nfs) || (nfs && g_conf()->rgw_nfs_run_sync_thread))); DriverManager::Config cfg = DriverManager::get_config(false, g_ceph_context); env.driver = DriverManager::get_storage(dpp, dpp->get_cct(), cfg, run_gc, run_lc, run_quota, run_sync, g_conf().get_val<bool>("rgw_dynamic_resharding"), true, null_yield, // run notification thread g_conf()->rgw_cache_enabled); if (!env.driver) { return -EIO; } return 0; } /* init_storage */ void rgw::AppMain::init_perfcounters() { (void) rgw_perf_start(dpp->get_cct()); } /* init_perfcounters */ void rgw::AppMain::init_http_clients() { rgw_init_resolver(); rgw::curl::setup_curl(fe_map); rgw_http_client_init(dpp->get_cct()); rgw_kmip_client_init(*new RGWKMIPManagerImpl(dpp->get_cct())); } /* init_http_clients */ void rgw::AppMain::cond_init_apis() { rgw_rest_init(g_ceph_context, env.driver->get_zone()->get_zonegroup()); if (have_http_frontend) { std::vector<std::string> apis; get_str_vec(g_conf()->rgw_enable_apis, apis); std::map<std::string, bool> apis_map; for (auto &api : apis) { apis_map[api] = true; } /* warn about insecure keystone secret config options */ if (!(g_ceph_context->_conf->rgw_keystone_admin_token.empty() || g_ceph_context->_conf->rgw_keystone_admin_password.empty())) { dout(0) << "WARNING: rgw_keystone_admin_token and " "rgw_keystone_admin_password should be avoided as they can " "expose secrets. Prefer the new rgw_keystone_admin_token_path " "and rgw_keystone_admin_password_path options, which read their " "secrets from files." << dendl; } // S3 website mode is a specialization of S3 const bool s3website_enabled = apis_map.count("s3website") > 0; const bool sts_enabled = apis_map.count("sts") > 0; const bool iam_enabled = apis_map.count("iam") > 0; const bool pubsub_enabled = apis_map.count("pubsub") > 0 || apis_map.count("notifications") > 0; // Swift API entrypoint could placed in the root instead of S3 const bool swift_at_root = g_conf()->rgw_swift_url_prefix == "/"; if (apis_map.count("s3") > 0 || s3website_enabled) { if (!swift_at_root) { rest.register_default_mgr(set_logging( rest_filter(env.driver, RGW_REST_S3, new RGWRESTMgr_S3(s3website_enabled, sts_enabled, iam_enabled, pubsub_enabled)))); } else { derr << "Cannot have the S3 or S3 Website enabled together with " << "Swift API placed in the root of hierarchy" << dendl; } } if (apis_map.count("swift") > 0) { RGWRESTMgr_SWIFT* const swift_resource = new RGWRESTMgr_SWIFT; if (! g_conf()->rgw_cross_domain_policy.empty()) { swift_resource->register_resource("crossdomain.xml", set_logging(new RGWRESTMgr_SWIFT_CrossDomain)); } swift_resource->register_resource("healthcheck", set_logging(new RGWRESTMgr_SWIFT_HealthCheck)); swift_resource->register_resource("info", set_logging(new RGWRESTMgr_SWIFT_Info)); if (! swift_at_root) { rest.register_resource(g_conf()->rgw_swift_url_prefix, set_logging(rest_filter(env.driver, RGW_REST_SWIFT, swift_resource))); } else { if (env.driver->get_zone()->get_zonegroup().get_zone_count() > 1) { derr << "Placing Swift API in the root of URL hierarchy while running" << " multi-site configuration requires another instance of RadosGW" << " with S3 API enabled!" << dendl; } rest.register_default_mgr(set_logging(swift_resource)); } } if (apis_map.count("swift_auth") > 0) { rest.register_resource(g_conf()->rgw_swift_auth_entry, set_logging(new RGWRESTMgr_SWIFT_Auth)); } if (apis_map.count("admin") > 0) { RGWRESTMgr_Admin *admin_resource = new RGWRESTMgr_Admin; admin_resource->register_resource("info", new RGWRESTMgr_Info); admin_resource->register_resource("usage", new RGWRESTMgr_Usage); /* Register driver-specific admin APIs */ env.driver->register_admin_apis(admin_resource); rest.register_resource(g_conf()->rgw_admin_entry, admin_resource); } if (apis_map.count("zero")) { rest.register_resource("zero", new rgw::RESTMgr_Zero()); } } /* have_http_frontend */ } /* init_apis */ void rgw::AppMain::init_ldap() { CephContext* cct = env.driver->ctx(); const string &ldap_uri = cct->_conf->rgw_ldap_uri; const string &ldap_binddn = cct->_conf->rgw_ldap_binddn; const string &ldap_searchdn = cct->_conf->rgw_ldap_searchdn; const string &ldap_searchfilter = cct->_conf->rgw_ldap_searchfilter; const string &ldap_dnattr = cct->_conf->rgw_ldap_dnattr; std::string ldap_bindpw = parse_rgw_ldap_bindpw(cct); ldh.reset(new rgw::LDAPHelper(ldap_uri, ldap_binddn, ldap_bindpw.c_str(), ldap_searchdn, ldap_searchfilter, ldap_dnattr)); ldh->init(); ldh->bind(); } /* init_ldap */ void rgw::AppMain::init_opslog() { rgw_log_usage_init(dpp->get_cct(), env.driver); OpsLogManifold *olog_manifold = new OpsLogManifold(); if (!g_conf()->rgw_ops_log_socket_path.empty()) { OpsLogSocket *olog_socket = new OpsLogSocket(g_ceph_context, g_conf()->rgw_ops_log_data_backlog); olog_socket->init(g_conf()->rgw_ops_log_socket_path); olog_manifold->add_sink(olog_socket); } if (!g_conf()->rgw_ops_log_file_path.empty()) { ops_log_file = new OpsLogFile(g_ceph_context, g_conf()->rgw_ops_log_file_path, g_conf()->rgw_ops_log_data_backlog); ops_log_file->start(); olog_manifold->add_sink(ops_log_file); } olog_manifold->add_sink(new OpsLogRados(env.driver)); olog = olog_manifold; } /* init_opslog */ int rgw::AppMain::init_frontends2(RGWLib* rgwlib) { int r{0}; vector<string> frontends_def; std::string frontend_defs_str = g_conf().get_val<string>("rgw_frontend_defaults"); get_str_vec(frontend_defs_str, ",", frontends_def); service_map_meta["pid"] = stringify(getpid()); std::map<std::string, std::unique_ptr<RGWFrontendConfig> > fe_def_map; for (auto& f : frontends_def) { RGWFrontendConfig *config = new RGWFrontendConfig(f); int r = config->init(); if (r < 0) { delete config; cerr << "ERROR: failed to init default config: " << f << std::endl; continue; } fe_def_map[config->get_framework()].reset(config); } /* Initialize the registry of auth strategies which will coordinate * the dynamic reconfiguration. */ implicit_tenant_context.reset(new rgw::auth::ImplicitTenants{g_conf()}); g_conf().add_observer(implicit_tenant_context.get()); /* allocate a mime table (you'd never guess that from the name) */ rgw_tools_init(dpp, dpp->get_cct()); /* Header custom behavior */ rest.register_x_headers(g_conf()->rgw_log_http_headers); sched_ctx.reset(new rgw::dmclock::SchedulerCtx{dpp->get_cct()}); ratelimiter.reset(new ActiveRateLimiter{dpp->get_cct()}); ratelimiter->start(); // initialize RGWProcessEnv env.rest = &rest; env.olog = olog; env.auth_registry = rgw::auth::StrategyRegistry::create( dpp->get_cct(), *implicit_tenant_context, env.driver); env.ratelimiting = ratelimiter.get(); int fe_count = 0; for (multimap<string, RGWFrontendConfig *>::iterator fiter = fe_map.begin(); fiter != fe_map.end(); ++fiter, ++fe_count) { RGWFrontendConfig *config = fiter->second; string framework = config->get_framework(); auto def_iter = fe_def_map.find(framework); if (def_iter != fe_def_map.end()) { config->set_default_config(*def_iter->second); } RGWFrontend* fe = nullptr; if (framework == "loadgen") { fe = new RGWLoadGenFrontend(env, config); } else if (framework == "beast") { fe = new RGWAsioFrontend(env, config, *sched_ctx); } else if (framework == "rgw-nfs") { fe = new RGWLibFrontend(env, config); if (rgwlib) { rgwlib->set_fe(static_cast<RGWLibFrontend*>(fe)); } } else if (framework == "arrow_flight") { #ifdef WITH_ARROW_FLIGHT int port; config->get_val("port", 8077, &port); fe = new rgw::flight::FlightFrontend(env, config, port); #else derr << "WARNING: arrow_flight frontend requested, but not included in build; skipping" << dendl; continue; #endif } service_map_meta["frontend_type#" + stringify(fe_count)] = framework; service_map_meta["frontend_config#" + stringify(fe_count)] = config->get_config(); if (! fe) { dout(0) << "WARNING: skipping unknown framework: " << framework << dendl; continue; } dout(0) << "starting handler: " << fiter->first << dendl; int r = fe->init(); if (r < 0) { derr << "ERROR: failed initializing frontend" << dendl; return -r; } r = fe->run(); if (r < 0) { derr << "ERROR: failed run" << dendl; return -r; } fes.push_back(fe); } std::string daemon_type = (nfs) ? "rgw-nfs" : "rgw"; r = env.driver->register_to_service_map(dpp, daemon_type, service_map_meta); if (r < 0) { derr << "ERROR: failed to register to service map: " << cpp_strerror(-r) << dendl; /* ignore error */ } if (env.driver->get_name() == "rados") { // add a watcher to respond to realm configuration changes pusher = std::make_unique<RGWPeriodPusher>(dpp, env.driver, null_yield); fe_pauser = std::make_unique<RGWFrontendPauser>(fes, pusher.get()); rgw_pauser = std::make_unique<RGWPauser>(); rgw_pauser->add_pauser(fe_pauser.get()); if (env.lua.background) { rgw_pauser->add_pauser(env.lua.background); } reloader = std::make_unique<RGWRealmReloader>( env, *implicit_tenant_context, service_map_meta, rgw_pauser.get()); realm_watcher = std::make_unique<RGWRealmWatcher>(dpp, g_ceph_context, static_cast<rgw::sal::RadosStore*>(env.driver)->svc()->zone->get_realm()); realm_watcher->add_watcher(RGWRealmNotify::Reload, *reloader); realm_watcher->add_watcher(RGWRealmNotify::ZonesNeedPeriod, *pusher.get()); } return r; } /* init_frontends2 */ void rgw::AppMain::init_tracepoints() { TracepointProvider::initialize<rgw_rados_tracepoint_traits>(dpp->get_cct()); TracepointProvider::initialize<rgw_op_tracepoint_traits>(dpp->get_cct()); tracing::rgw::tracer.init("rgw"); } /* init_tracepoints() */ void rgw::AppMain::init_notification_endpoints() { #ifdef WITH_RADOSGW_AMQP_ENDPOINT if (!rgw::amqp::init(dpp->get_cct())) { derr << "ERROR: failed to initialize AMQP manager" << dendl; } #endif #ifdef WITH_RADOSGW_KAFKA_ENDPOINT if (!rgw::kafka::init(dpp->get_cct())) { derr << "ERROR: failed to initialize Kafka manager" << dendl; } #endif } /* init_notification_endpoints */ void rgw::AppMain::init_lua() { rgw::sal::Driver* driver = env.driver; int r{0}; std::string path = g_conf().get_val<std::string>("rgw_luarocks_location"); if (!path.empty()) { path += "/" + g_conf()->name.to_str(); } env.lua.luarocks_path = path; #ifdef WITH_RADOSGW_LUA_PACKAGES rgw::lua::packages_t failed_packages; std::string output; r = rgw::lua::install_packages(dpp, driver, null_yield, path, failed_packages, output); if (r < 0) { dout(1) << "WARNING: failed to install lua packages from allowlist. error: " << r << dendl; } if (!output.empty()) { dout(10) << "INFO: lua packages installation output: \n" << output << dendl; } for (const auto &p : failed_packages) { dout(5) << "WARNING: failed to install lua package: " << p << " from allowlist" << dendl; } #endif env.lua.manager = env.driver->get_lua_manager(); if (driver->get_name() == "rados") { /* Supported for only RadosStore */ lua_background = std::make_unique< rgw::lua::Background>(driver, dpp->get_cct(), path); lua_background->start(); env.lua.background = lua_background.get(); } } /* init_lua */ void rgw::AppMain::shutdown(std::function<void(void)> finalize_async_signals) { if (env.driver->get_name() == "rados") { reloader.reset(); // stop the realm reloader } for (auto& fe : fes) { fe->stop(); } for (auto& fe : fes) { fe->join(); delete fe; } for (auto& fec : fe_configs) { delete fec; } ldh.reset(nullptr); // deletes finalize_async_signals(); // callback rgw_log_usage_finalize(); delete olog; if (lua_background) { lua_background->shutdown(); } cfgstore.reset(); // deletes DriverManager::close_storage(env.driver); rgw_tools_cleanup(); rgw_shutdown_resolver(); rgw_http_client_cleanup(); rgw_kmip_client_cleanup(); rgw::curl::cleanup_curl(); g_conf().remove_observer(implicit_tenant_context.get()); implicit_tenant_context.reset(); // deletes #ifdef WITH_RADOSGW_AMQP_ENDPOINT rgw::amqp::shutdown(); #endif #ifdef WITH_RADOSGW_KAFKA_ENDPOINT rgw::kafka::shutdown(); #endif rgw_perf_stop(g_ceph_context); ratelimiter.reset(); // deletes--ensure this happens before we destruct } /* AppMain::shutdown */
20,164
30.755906
103
cc
null
ceph-main/src/rgw/rgw_arn.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_arn.h" #include "rgw_common.h" #include <regex> using namespace std; namespace rgw { namespace { boost::optional<Partition> to_partition(const smatch::value_type& p, bool wildcards) { if (p == "aws") { return Partition::aws; } else if (p == "aws-cn") { return Partition::aws_cn; } else if (p == "aws-us-gov") { return Partition::aws_us_gov; } else if (p == "*" && wildcards) { return Partition::wildcard; } else { return boost::none; } ceph_abort(); } boost::optional<Service> to_service(const smatch::value_type& s, bool wildcards) { static const unordered_map<string, Service> services = { { "acm", Service::acm }, { "apigateway", Service::apigateway }, { "appstream", Service::appstream }, { "artifact", Service::artifact }, { "autoscaling", Service::autoscaling }, { "aws-marketplace", Service::aws_marketplace }, { "aws-marketplace-management", Service::aws_marketplace_management }, { "aws-portal", Service::aws_portal }, { "cloudformation", Service::cloudformation }, { "cloudfront", Service::cloudfront }, { "cloudhsm", Service::cloudhsm }, { "cloudsearch", Service::cloudsearch }, { "cloudtrail", Service::cloudtrail }, { "cloudwatch", Service::cloudwatch }, { "codebuild", Service::codebuild }, { "codecommit", Service::codecommit }, { "codedeploy", Service::codedeploy }, { "codepipeline", Service::codepipeline }, { "cognito-identity", Service::cognito_identity }, { "cognito-idp", Service::cognito_idp }, { "cognito-sync", Service::cognito_sync }, { "config", Service::config }, { "datapipeline", Service::datapipeline }, { "devicefarm", Service::devicefarm }, { "directconnect", Service::directconnect }, { "dms", Service::dms }, { "ds", Service::ds }, { "dynamodb", Service::dynamodb }, { "ec2", Service::ec2 }, { "ecr", Service::ecr }, { "ecs", Service::ecs }, { "elasticache", Service::elasticache }, { "elasticbeanstalk", Service::elasticbeanstalk }, { "elasticfilesystem", Service::elasticfilesystem }, { "elasticloadbalancing", Service::elasticloadbalancing }, { "elasticmapreduce", Service::elasticmapreduce }, { "elastictranscoder", Service::elastictranscoder }, { "es", Service::es }, { "events", Service::events }, { "firehose", Service::firehose }, { "gamelift", Service::gamelift }, { "glacier", Service::glacier }, { "health", Service::health }, { "iam", Service::iam }, { "importexport", Service::importexport }, { "inspector", Service::inspector }, { "iot", Service::iot }, { "kinesis", Service::kinesis }, { "kinesisanalytics", Service::kinesisanalytics }, { "kms", Service::kms }, { "lambda", Service::lambda }, { "lightsail", Service::lightsail }, { "logs", Service::logs }, { "machinelearning", Service::machinelearning }, { "mobileanalytics", Service::mobileanalytics }, { "mobilehub", Service::mobilehub }, { "opsworks", Service::opsworks }, { "opsworks-cm", Service::opsworks_cm }, { "polly", Service::polly }, { "rds", Service::rds }, { "redshift", Service::redshift }, { "route53", Service::route53 }, { "route53domains", Service::route53domains }, { "s3", Service::s3 }, { "sdb", Service::sdb }, { "servicecatalog", Service::servicecatalog }, { "ses", Service::ses }, { "sns", Service::sns }, { "sqs", Service::sqs }, { "ssm", Service::ssm }, { "states", Service::states }, { "storagegateway", Service::storagegateway }, { "sts", Service::sts }, { "support", Service::support }, { "swf", Service::swf }, { "trustedadvisor", Service::trustedadvisor }, { "waf", Service::waf }, { "workmail", Service::workmail }, { "workspaces", Service::workspaces }}; if (wildcards && s == "*") { return Service::wildcard; } auto i = services.find(s); if (i == services.end()) { return boost::none; } else { return i->second; } } } ARN::ARN(const rgw_obj& o) : partition(Partition::aws), service(Service::s3), region(), account(o.bucket.tenant), resource(o.bucket.name) { resource.push_back('/'); resource.append(o.key.name); } ARN::ARN(const rgw_bucket& b) : partition(Partition::aws), service(Service::s3), region(), account(b.tenant), resource(b.name) { } ARN::ARN(const rgw_bucket& b, const std::string& o) : partition(Partition::aws), service(Service::s3), region(), account(b.tenant), resource(b.name) { resource.push_back('/'); resource.append(o); } ARN::ARN(const std::string& resource_name, const std::string& type, const std::string& tenant, bool has_path) : partition(Partition::aws), service(Service::iam), region(), account(tenant), resource(type) { if (! has_path) resource.push_back('/'); resource.append(resource_name); } boost::optional<ARN> ARN::parse(const std::string& s, bool wildcards) { static const std::regex rx_wild("arn:([^:]*):([^:]*):([^:]*):([^:]*):([^:]*)", std::regex_constants::ECMAScript | std::regex_constants::optimize); static const std::regex rx_no_wild( "arn:([^:*]*):([^:*]*):([^:*]*):([^:*]*):(.*)", std::regex_constants::ECMAScript | std::regex_constants::optimize); smatch match; if ((s == "*") && wildcards) { return ARN(Partition::wildcard, Service::wildcard, "*", "*", "*"); } else if (regex_match(s, match, wildcards ? rx_wild : rx_no_wild) && match.size() == 6) { if (auto p = to_partition(match[1], wildcards)) { if (auto s = to_service(match[2], wildcards)) { return ARN(*p, *s, match[3], match[4], match[5]); } } } return boost::none; } std::string ARN::to_string() const { std::string s{"arn:"}; if (partition == Partition::aws) { s.append("aws:"); } else if (partition == Partition::aws_cn) { s.append("aws-cn:"); } else if (partition == Partition::aws_us_gov) { s.append("aws-us-gov:"); } else { s.append("*:"); } static const std::unordered_map<Service, string> services = { { Service::acm, "acm" }, { Service::apigateway, "apigateway" }, { Service::appstream, "appstream" }, { Service::artifact, "artifact" }, { Service::autoscaling, "autoscaling" }, { Service::aws_marketplace, "aws-marketplace" }, { Service::aws_marketplace_management, "aws-marketplace-management" }, { Service::aws_portal, "aws-portal" }, { Service::cloudformation, "cloudformation" }, { Service::cloudfront, "cloudfront" }, { Service::cloudhsm, "cloudhsm" }, { Service::cloudsearch, "cloudsearch" }, { Service::cloudtrail, "cloudtrail" }, { Service::cloudwatch, "cloudwatch" }, { Service::codebuild, "codebuild" }, { Service::codecommit, "codecommit" }, { Service::codedeploy, "codedeploy" }, { Service::codepipeline, "codepipeline" }, { Service::cognito_identity, "cognito-identity" }, { Service::cognito_idp, "cognito-idp" }, { Service::cognito_sync, "cognito-sync" }, { Service::config, "config" }, { Service::datapipeline, "datapipeline" }, { Service::devicefarm, "devicefarm" }, { Service::directconnect, "directconnect" }, { Service::dms, "dms" }, { Service::ds, "ds" }, { Service::dynamodb, "dynamodb" }, { Service::ec2, "ec2" }, { Service::ecr, "ecr" }, { Service::ecs, "ecs" }, { Service::elasticache, "elasticache" }, { Service::elasticbeanstalk, "elasticbeanstalk" }, { Service::elasticfilesystem, "elasticfilesystem" }, { Service::elasticloadbalancing, "elasticloadbalancing" }, { Service::elasticmapreduce, "elasticmapreduce" }, { Service::elastictranscoder, "elastictranscoder" }, { Service::es, "es" }, { Service::events, "events" }, { Service::firehose, "firehose" }, { Service::gamelift, "gamelift" }, { Service::glacier, "glacier" }, { Service::health, "health" }, { Service::iam, "iam" }, { Service::importexport, "importexport" }, { Service::inspector, "inspector" }, { Service::iot, "iot" }, { Service::kinesis, "kinesis" }, { Service::kinesisanalytics, "kinesisanalytics" }, { Service::kms, "kms" }, { Service::lambda, "lambda" }, { Service::lightsail, "lightsail" }, { Service::logs, "logs" }, { Service::machinelearning, "machinelearning" }, { Service::mobileanalytics, "mobileanalytics" }, { Service::mobilehub, "mobilehub" }, { Service::opsworks, "opsworks" }, { Service::opsworks_cm, "opsworks-cm" }, { Service::polly, "polly" }, { Service::rds, "rds" }, { Service::redshift, "redshift" }, { Service::route53, "route53" }, { Service::route53domains, "route53domains" }, { Service::s3, "s3" }, { Service::sdb, "sdb" }, { Service::servicecatalog, "servicecatalog" }, { Service::ses, "ses" }, { Service::sns, "sns" }, { Service::sqs, "sqs" }, { Service::ssm, "ssm" }, { Service::states, "states" }, { Service::storagegateway, "storagegateway" }, { Service::sts, "sts" }, { Service::support, "support" }, { Service::swf, "swf" }, { Service::trustedadvisor, "trustedadvisor" }, { Service::waf, "waf" }, { Service::workmail, "workmail" }, { Service::workspaces, "workspaces" }}; auto i = services.find(service); if (i != services.end()) { s.append(i->second); } else { s.push_back('*'); } s.push_back(':'); s.append(region); s.push_back(':'); s.append(account); s.push_back(':'); s.append(resource); return s; } bool operator ==(const ARN& l, const ARN& r) { return ((l.partition == r.partition) && (l.service == r.service) && (l.region == r.region) && (l.account == r.account) && (l.resource == r.resource)); } bool operator <(const ARN& l, const ARN& r) { return ((l.partition < r.partition) || (l.service < r.service) || (l.region < r.region) || (l.account < r.account) || (l.resource < r.resource)); } // The candidate is not allowed to have wildcards. The only way to // do that sanely would be to use unification rather than matching. bool ARN::match(const ARN& candidate) const { if ((candidate.partition == Partition::wildcard) || (partition != candidate.partition && partition != Partition::wildcard)) { return false; } if ((candidate.service == Service::wildcard) || (service != candidate.service && service != Service::wildcard)) { return false; } if (!match_policy(region, candidate.region, MATCH_POLICY_ARN)) { return false; } if (!match_policy(account, candidate.account, MATCH_POLICY_ARN)) { return false; } if (!match_policy(resource, candidate.resource, MATCH_POLICY_RESOURCE)) { return false; } return true; } boost::optional<ARNResource> ARNResource::parse(const std::string& s) { static const std::regex rx("^([^:/]*)[:/]?([^:/]*)?[:/]?(.*)$", std::regex_constants::ECMAScript | std::regex_constants::optimize); std::smatch match; if (!regex_match(s, match, rx)) { return boost::none; } if (match[2].str().empty() && match[3].str().empty()) { // only resource exist return rgw::ARNResource("", match[1], ""); } // resource type also exist, and cannot be wildcard if (match[1] != std::string(wildcard)) { // resource type cannot be wildcard return rgw::ARNResource(match[1], match[2], match[3]); } return boost::none; } std::string ARNResource::to_string() const { std::string s; if (!resource_type.empty()) { s.append(resource_type); s.push_back(':'); s.append(resource); s.push_back(':'); s.append(qualifier); } else { s.append(resource); } return s; } }
11,916
29.713918
109
cc
null
ceph-main/src/rgw/rgw_arn.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 <boost/optional.hpp> class rgw_obj; class rgw_bucket; namespace rgw { enum struct Partition { aws, aws_cn, aws_us_gov, wildcard // If we wanted our own ARNs for principal type unique to us // (maybe to integrate better with Swift) or for anything else we // provide that doesn't map onto S3, we could add an 'rgw' // partition type. }; enum struct Service { apigateway, appstream, artifact, autoscaling, aws_portal, acm, cloudformation, cloudfront, cloudhsm, cloudsearch, cloudtrail, cloudwatch, events, logs, codebuild, codecommit, codedeploy, codepipeline, cognito_idp, cognito_identity, cognito_sync, config, datapipeline, dms, devicefarm, directconnect, ds, dynamodb, ec2, ecr, ecs, ssm, elasticbeanstalk, elasticfilesystem, elasticloadbalancing, elasticmapreduce, elastictranscoder, elasticache, es, gamelift, glacier, health, iam, importexport, inspector, iot, kms, kinesisanalytics, firehose, kinesis, lambda, lightsail, machinelearning, aws_marketplace, aws_marketplace_management, mobileanalytics, mobilehub, opsworks, opsworks_cm, polly, redshift, rds, route53, route53domains, sts, servicecatalog, ses, sns, sqs, s3, swf, sdb, states, storagegateway, support, trustedadvisor, waf, workmail, workspaces, wildcard }; /* valid format: * 'arn:partition:service:region:account-id:resource' * The 'resource' part can be further broken down via ARNResource */ struct ARN { Partition partition; Service service; std::string region; // Once we refit tenant, we should probably use that instead of a // string. std::string account; std::string resource; ARN() : partition(Partition::wildcard), service(Service::wildcard) {} ARN(Partition partition, Service service, std::string region, std::string account, std::string resource) : partition(partition), service(service), region(std::move(region)), account(std::move(account)), resource(std::move(resource)) {} ARN(const rgw_obj& o); ARN(const rgw_bucket& b); ARN(const rgw_bucket& b, const std::string& o); ARN(const std::string& resource_name, const std::string& type, const std::string& tenant, bool has_path=false); static boost::optional<ARN> parse(const std::string& s, bool wildcard = false); std::string to_string() const; // `this` is the pattern bool match(const ARN& candidate) const; }; inline std::string to_string(const ARN& a) { return a.to_string(); } inline std::ostream& operator <<(std::ostream& m, const ARN& a) { return m << to_string(a); } bool operator ==(const ARN& l, const ARN& r); bool operator <(const ARN& l, const ARN& r); /* valid formats (only resource part): * 'resource' * 'resourcetype/resource' * 'resourcetype/resource/qualifier' * 'resourcetype/resource:qualifier' * 'resourcetype:resource' * 'resourcetype:resource:qualifier' * Note that 'resourceType' cannot be wildcard */ struct ARNResource { constexpr static const char* const wildcard = "*"; std::string resource_type; std::string resource; std::string qualifier; ARNResource() : resource_type(""), resource(wildcard), qualifier("") {} ARNResource(const std::string& _resource_type, const std::string& _resource, const std::string& _qualifier) : resource_type(std::move(_resource_type)), resource(std::move(_resource)), qualifier(std::move(_qualifier)) {} static boost::optional<ARNResource> parse(const std::string& s); std::string to_string() const; }; inline std::string to_string(const ARNResource& r) { return r.to_string(); } } // namespace rgw namespace std { template<> struct hash<::rgw::Service> { size_t operator()(const ::rgw::Service& s) const noexcept { // Invoke a default-constructed hash object for int. return hash<int>()(static_cast<int>(s)); } }; } // namespace std
3,948
31.368852
113
h
null
ceph-main/src/rgw/rgw_asio_client.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <boost/algorithm/string/predicate.hpp> #include <boost/asio/write.hpp> #include "rgw_asio_client.h" #include "rgw_perf_counters.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace rgw::asio; ClientIO::ClientIO(parser_type& parser, bool is_ssl, const endpoint_type& local_endpoint, const endpoint_type& remote_endpoint) : parser(parser), is_ssl(is_ssl), local_endpoint(local_endpoint), remote_endpoint(remote_endpoint), txbuf(*this) { } ClientIO::~ClientIO() = default; int ClientIO::init_env(CephContext *cct) { env.init(cct); perfcounter->inc(l_rgw_qlen); perfcounter->inc(l_rgw_qactive); const auto& request = parser.get(); const auto& headers = request; for (auto header = headers.begin(); header != headers.end(); ++header) { const auto& field = header->name(); // enum type for known headers const auto& name = header->name_string(); const auto& value = header->value(); if (field == beast::http::field::content_length) { env.set("CONTENT_LENGTH", std::string(value)); continue; } if (field == beast::http::field::content_type) { env.set("CONTENT_TYPE", std::string(value)); continue; } static const std::string_view HTTP_{"HTTP_"}; char buf[name.size() + HTTP_.size() + 1]; auto dest = std::copy(std::begin(HTTP_), std::end(HTTP_), buf); for (auto src = name.begin(); src != name.end(); ++src, ++dest) { if (*src == '-') { *dest = '_'; } else if (*src == '_') { *dest = '-'; } else { *dest = std::toupper(*src); } } *dest = '\0'; env.set(buf, std::string(value)); } int major = request.version() / 10; int minor = request.version() % 10; env.set("HTTP_VERSION", std::to_string(major) + '.' + std::to_string(minor)); env.set("REQUEST_METHOD", std::string(request.method_string())); // split uri from query auto uri = request.target(); auto pos = uri.find('?'); if (pos != uri.npos) { auto query = uri.substr(pos + 1); env.set("QUERY_STRING", std::string(query)); uri = uri.substr(0, pos); } env.set("SCRIPT_URI", std::string(uri)); env.set("REQUEST_URI", std::string(request.target())); char port_buf[16]; snprintf(port_buf, sizeof(port_buf), "%d", local_endpoint.port()); env.set("SERVER_PORT", port_buf); if (is_ssl) { env.set("SERVER_PORT_SECURE", port_buf); } env.set("REMOTE_ADDR", remote_endpoint.address().to_string()); // TODO: set REMOTE_USER if authenticated return 0; } size_t ClientIO::complete_request() { perfcounter->inc(l_rgw_qlen, -1); perfcounter->inc(l_rgw_qactive, -1); return 0; } void ClientIO::flush() { txbuf.pubsync(); } size_t ClientIO::send_status(int status, const char* status_name) { static constexpr size_t STATUS_BUF_SIZE = 128; char statusbuf[STATUS_BUF_SIZE]; const auto statuslen = snprintf(statusbuf, sizeof(statusbuf), "HTTP/1.1 %d %s\r\n", status, status_name); return txbuf.sputn(statusbuf, statuslen); } size_t ClientIO::send_100_continue() { const char HTTTP_100_CONTINUE[] = "HTTP/1.1 100 CONTINUE\r\n\r\n"; const size_t sent = txbuf.sputn(HTTTP_100_CONTINUE, sizeof(HTTTP_100_CONTINUE) - 1); flush(); sent100continue = true; return sent; } static constexpr size_t TIME_BUF_SIZE = 128; static size_t dump_date_header(char (&timestr)[TIME_BUF_SIZE]) { const time_t gtime = time(nullptr); struct tm result; struct tm const * const tmp = gmtime_r(&gtime, &result); if (tmp == nullptr) { return 0; } return strftime(timestr, sizeof(timestr), "Date: %a, %d %b %Y %H:%M:%S %Z\r\n", tmp); } size_t ClientIO::complete_header() { size_t sent = 0; char timestr[TIME_BUF_SIZE]; if (dump_date_header(timestr)) { sent += txbuf.sputn(timestr, strlen(timestr)); } if (parser.keep_alive()) { constexpr char CONN_KEEP_ALIVE[] = "Connection: Keep-Alive\r\n"; sent += txbuf.sputn(CONN_KEEP_ALIVE, sizeof(CONN_KEEP_ALIVE) - 1); } else { constexpr char CONN_KEEP_CLOSE[] = "Connection: close\r\n"; sent += txbuf.sputn(CONN_KEEP_CLOSE, sizeof(CONN_KEEP_CLOSE) - 1); } constexpr char HEADER_END[] = "\r\n"; sent += txbuf.sputn(HEADER_END, sizeof(HEADER_END) - 1); flush(); return sent; } size_t ClientIO::send_header(const std::string_view& name, const std::string_view& value) { static constexpr char HEADER_SEP[] = ": "; static constexpr char HEADER_END[] = "\r\n"; size_t sent = 0; sent += txbuf.sputn(name.data(), name.length()); sent += txbuf.sputn(HEADER_SEP, sizeof(HEADER_SEP) - 1); sent += txbuf.sputn(value.data(), value.length()); sent += txbuf.sputn(HEADER_END, sizeof(HEADER_END) - 1); return sent; } size_t ClientIO::send_content_length(uint64_t len) { static constexpr size_t CONLEN_BUF_SIZE = 128; char sizebuf[CONLEN_BUF_SIZE]; const auto sizelen = snprintf(sizebuf, sizeof(sizebuf), "Content-Length: %" PRIu64 "\r\n", len); return txbuf.sputn(sizebuf, sizelen); }
5,299
26.46114
79
cc
null
ceph-main/src/rgw/rgw_asio_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <boost/asio/ip/tcp.hpp> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include "include/ceph_assert.h" #include "rgw_client_io.h" namespace rgw { namespace asio { namespace beast = boost::beast; using parser_type = beast::http::request_parser<beast::http::buffer_body>; class ClientIO : public io::RestfulClient, public io::BuffererSink { protected: parser_type& parser; private: const bool is_ssl; using endpoint_type = boost::asio::ip::tcp::endpoint; endpoint_type local_endpoint; endpoint_type remote_endpoint; RGWEnv env; rgw::io::StaticOutputBufferer<> txbuf; bool sent100continue = false; public: ClientIO(parser_type& parser, bool is_ssl, const endpoint_type& local_endpoint, const endpoint_type& remote_endpoint); ~ClientIO() override; int init_env(CephContext *cct) override; size_t complete_request() override; void flush() override; 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 send_content_length(uint64_t len) override; size_t complete_header() override; size_t send_body(const char* buf, size_t len) override { return write_data(buf, len); } RGWEnv& get_env() noexcept override { return env; } bool sent_100_continue() const { return sent100continue; } }; } // namespace asio } // namespace rgw
1,640
25.047619
74
h
null
ceph-main/src/rgw/rgw_asio_frontend.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <atomic> #include <ctime> #include <thread> #include <vector> #include <boost/asio.hpp> #include <boost/intrusive/list.hpp> #include <boost/smart_ptr/intrusive_ref_counter.hpp> #include <boost/context/protected_fixedsize_stack.hpp> #include <spawn/spawn.hpp> #include "common/async/shared_mutex.h" #include "common/errno.h" #include "common/strtol.h" #include "rgw_asio_client.h" #include "rgw_asio_frontend.h" #ifdef WITH_RADOSGW_BEAST_OPENSSL #include <boost/asio/ssl.hpp> #endif #include "common/split.h" #include "services/svc_config_key.h" #include "services/svc_zone.h" #include "rgw_zone.h" #include "rgw_asio_frontend_timer.h" #include "rgw_dmclock_async_scheduler.h" #define dout_subsys ceph_subsys_rgw namespace { using tcp = boost::asio::ip::tcp; namespace http = boost::beast::http; #ifdef WITH_RADOSGW_BEAST_OPENSSL namespace ssl = boost::asio::ssl; #endif struct Connection; // use explicit executor types instead of the type-erased boost::asio::executor using executor_type = boost::asio::io_context::executor_type; using tcp_socket = boost::asio::basic_stream_socket<tcp, executor_type>; using tcp_stream = boost::beast::basic_stream<tcp, executor_type>; using timeout_timer = rgw::basic_timeout_timer<ceph::coarse_mono_clock, executor_type, Connection>; static constexpr size_t parse_buffer_size = 65536; using parse_buffer = boost::beast::flat_static_buffer<parse_buffer_size>; // use mmap/mprotect to allocate 512k coroutine stacks auto make_stack_allocator() { return boost::context::protected_fixedsize_stack{512*1024}; } using namespace std; template <typename Stream> class StreamIO : public rgw::asio::ClientIO { CephContext* const cct; Stream& stream; timeout_timer& timeout; yield_context yield; parse_buffer& buffer; boost::system::error_code fatal_ec; public: StreamIO(CephContext *cct, Stream& stream, timeout_timer& timeout, rgw::asio::parser_type& parser, yield_context yield, parse_buffer& buffer, bool is_ssl, const tcp::endpoint& local_endpoint, const tcp::endpoint& remote_endpoint) : ClientIO(parser, is_ssl, local_endpoint, remote_endpoint), cct(cct), stream(stream), timeout(timeout), yield(yield), buffer(buffer) {} boost::system::error_code get_fatal_error_code() const { return fatal_ec; } size_t write_data(const char* buf, size_t len) override { boost::system::error_code ec; timeout.start(); auto bytes = boost::asio::async_write(stream, boost::asio::buffer(buf, len), yield[ec]); timeout.cancel(); if (ec) { ldout(cct, 4) << "write_data failed: " << ec.message() << dendl; if (ec == boost::asio::error::broken_pipe) { boost::system::error_code ec_ignored; stream.lowest_layer().shutdown(tcp_socket::shutdown_both, ec_ignored); } if (!fatal_ec) { fatal_ec = ec; } throw rgw::io::Exception(ec.value(), std::system_category()); } return bytes; } size_t recv_body(char* buf, size_t max) override { auto& message = parser.get(); auto& body_remaining = message.body(); body_remaining.data = buf; body_remaining.size = max; while (body_remaining.size && !parser.is_done()) { boost::system::error_code ec; timeout.start(); http::async_read_some(stream, buffer, parser, yield[ec]); timeout.cancel(); if (ec == http::error::need_buffer) { break; } if (ec) { ldout(cct, 4) << "failed to read body: " << ec.message() << dendl; if (!fatal_ec) { fatal_ec = ec; } throw rgw::io::Exception(ec.value(), std::system_category()); } } return max - body_remaining.size; } }; // output the http version as a string, ie 'HTTP/1.1' struct http_version { unsigned major_ver; unsigned minor_ver; explicit http_version(unsigned version) : major_ver(version / 10), minor_ver(version % 10) {} }; std::ostream& operator<<(std::ostream& out, const http_version& v) { return out << "HTTP/" << v.major_ver << '.' << v.minor_ver; } // log an http header value or '-' if it's missing struct log_header { const http::fields& fields; http::field field; std::string_view quote; log_header(const http::fields& fields, http::field field, std::string_view quote = "") : fields(fields), field(field), quote(quote) {} }; std::ostream& operator<<(std::ostream& out, const log_header& h) { auto p = h.fields.find(h.field); if (p == h.fields.end()) { return out << '-'; } return out << h.quote << p->value() << h.quote; } // log fractional seconds in milliseconds struct log_ms_remainder { ceph::coarse_real_time t; log_ms_remainder(ceph::coarse_real_time t) : t(t) {} }; std::ostream& operator<<(std::ostream& out, const log_ms_remainder& m) { using namespace std::chrono; return out << std::setfill('0') << std::setw(3) << duration_cast<milliseconds>(m.t.time_since_epoch()).count() % 1000; } // log time in apache format: day/month/year:hour:minute:second zone struct log_apache_time { ceph::coarse_real_time t; log_apache_time(ceph::coarse_real_time t) : t(t) {} }; std::ostream& operator<<(std::ostream& out, const log_apache_time& a) { const auto t = ceph::coarse_real_clock::to_time_t(a.t); const auto local = std::localtime(&t); return out << std::put_time(local, "%d/%b/%Y:%T.") << log_ms_remainder{a.t} << std::put_time(local, " %z"); }; using SharedMutex = ceph::async::SharedMutex<boost::asio::io_context::executor_type>; template <typename Stream> void handle_connection(boost::asio::io_context& context, RGWProcessEnv& env, Stream& stream, timeout_timer& timeout, size_t header_limit, parse_buffer& buffer, bool is_ssl, SharedMutex& pause_mutex, rgw::dmclock::Scheduler *scheduler, const std::string& uri_prefix, boost::system::error_code& ec, yield_context yield) { // don't impose a limit on the body, since we read it in pieces static constexpr size_t body_limit = std::numeric_limits<size_t>::max(); auto cct = env.driver->ctx(); // read messages from the stream until eof for (;;) { // configure the parser rgw::asio::parser_type parser; parser.header_limit(header_limit); parser.body_limit(body_limit); timeout.start(); // parse the header http::async_read_header(stream, buffer, parser, yield[ec]); timeout.cancel(); if (ec == boost::asio::error::connection_reset || ec == boost::asio::error::bad_descriptor || ec == boost::asio::error::operation_aborted || #ifdef WITH_RADOSGW_BEAST_OPENSSL ec == ssl::error::stream_truncated || #endif ec == http::error::end_of_stream) { ldout(cct, 20) << "failed to read header: " << ec.message() << dendl; return; } auto& message = parser.get(); if (ec) { ldout(cct, 1) << "failed to read header: " << ec.message() << dendl; http::response<http::empty_body> response; response.result(http::status::bad_request); response.version(message.version() == 10 ? 10 : 11); response.prepare_payload(); timeout.start(); http::async_write(stream, response, yield[ec]); timeout.cancel(); if (ec) { ldout(cct, 5) << "failed to write response: " << ec.message() << dendl; } ldout(cct, 1) << "====== req done http_status=400 ======" << dendl; return; } bool expect_continue = (message[http::field::expect] == "100-continue"); { auto lock = pause_mutex.async_lock_shared(yield[ec]); if (ec == boost::asio::error::operation_aborted) { return; } else if (ec) { ldout(cct, 1) << "failed to lock: " << ec.message() << dendl; return; } // process the request RGWRequest req{env.driver->get_new_req_id()}; auto& socket = stream.lowest_layer(); const auto& remote_endpoint = socket.remote_endpoint(ec); if (ec) { ldout(cct, 1) << "failed to connect client: " << ec.message() << dendl; return; } const auto& local_endpoint = socket.local_endpoint(ec); if (ec) { ldout(cct, 1) << "failed to connect client: " << ec.message() << dendl; return; } StreamIO real_client{cct, stream, timeout, parser, yield, buffer, is_ssl, local_endpoint, remote_endpoint}; auto real_client_io = rgw::io::add_reordering( rgw::io::add_buffering(cct, rgw::io::add_chunking( rgw::io::add_conlen_controlling( &real_client)))); RGWRestfulIO client(cct, &real_client_io); optional_yield y = null_yield; if (cct->_conf->rgw_beast_enable_async) { y = optional_yield{context, yield}; } int http_ret = 0; string user = "-"; const auto started = ceph::coarse_real_clock::now(); ceph::coarse_real_clock::duration latency{}; process_request(env, &req, uri_prefix, &client, y, scheduler, &user, &latency, &http_ret); if (cct->_conf->subsys.should_gather(ceph_subsys_rgw_access, 1)) { // access log line elements begin per Apache Combined Log Format with additions following lsubdout(cct, rgw_access, 1) << "beast: " << std::hex << &req << std::dec << ": " << remote_endpoint.address() << " - " << user << " [" << log_apache_time{started} << "] \"" << message.method_string() << ' ' << message.target() << ' ' << http_version{message.version()} << "\" " << http_ret << ' ' << client.get_bytes_sent() + client.get_bytes_received() << ' ' << log_header{message, http::field::referer, "\""} << ' ' << log_header{message, http::field::user_agent, "\""} << ' ' << log_header{message, http::field::range} << " latency=" << latency << dendl; } // process_request() can't distinguish between connection errors and // http/s3 errors, so check StreamIO for fatal connection errors ec = real_client.get_fatal_error_code(); if (ec) { return; } if (real_client.sent_100_continue()) { expect_continue = false; } } if (!parser.keep_alive()) { return; } // if we failed before reading the entire message, discard any remaining // bytes before reading the next while (!expect_continue && !parser.is_done()) { static std::array<char, 1024> discard_buffer; auto& body = parser.get().body(); body.size = discard_buffer.size(); body.data = discard_buffer.data(); timeout.start(); http::async_read_some(stream, buffer, parser, yield[ec]); timeout.cancel(); if (ec == http::error::need_buffer) { continue; } if (ec == boost::asio::error::connection_reset) { return; } if (ec) { ldout(cct, 5) << "failed to discard unread message: " << ec.message() << dendl; return; } } } } // timeout support requires that connections are reference-counted, because the // timeout_handler can outlive the coroutine struct Connection : boost::intrusive::list_base_hook<>, boost::intrusive_ref_counter<Connection> { tcp_socket socket; parse_buffer buffer; explicit Connection(tcp_socket&& socket) noexcept : socket(std::move(socket)) {} void close(boost::system::error_code& ec) { socket.close(ec); } tcp_socket& get_socket() { return socket; } }; class ConnectionList { using List = boost::intrusive::list<Connection>; List connections; std::mutex mutex; void remove(Connection& c) { std::lock_guard lock{mutex}; if (c.is_linked()) { connections.erase(List::s_iterator_to(c)); } } public: class Guard { ConnectionList *list; Connection *conn; public: Guard(ConnectionList *list, Connection *conn) : list(list), conn(conn) {} ~Guard() { list->remove(*conn); } }; [[nodiscard]] Guard add(Connection& conn) { std::lock_guard lock{mutex}; connections.push_back(conn); return Guard{this, &conn}; } void close(boost::system::error_code& ec) { std::lock_guard lock{mutex}; for (auto& conn : connections) { conn.socket.close(ec); } connections.clear(); } }; namespace dmc = rgw::dmclock; class AsioFrontend { RGWProcessEnv& env; RGWFrontendConfig* conf; boost::asio::io_context context; std::string uri_prefix; ceph::timespan request_timeout = std::chrono::milliseconds(REQUEST_TIMEOUT); size_t header_limit = 16384; #ifdef WITH_RADOSGW_BEAST_OPENSSL boost::optional<ssl::context> ssl_context; int get_config_key_val(string name, const string& type, bufferlist *pbl); int ssl_set_private_key(const string& name, bool is_ssl_cert); int ssl_set_certificate_chain(const string& name); int init_ssl(); #endif SharedMutex pause_mutex; std::unique_ptr<rgw::dmclock::Scheduler> scheduler; struct Listener { tcp::endpoint endpoint; tcp::acceptor acceptor; tcp_socket socket; bool use_ssl = false; bool use_nodelay = false; explicit Listener(boost::asio::io_context& context) : acceptor(context), socket(context) {} }; std::vector<Listener> listeners; ConnectionList connections; // work guard to keep run() threads busy while listeners are paused using Executor = boost::asio::io_context::executor_type; std::optional<boost::asio::executor_work_guard<Executor>> work; std::vector<std::thread> threads; std::atomic<bool> going_down{false}; CephContext* ctx() const { return env.driver->ctx(); } std::optional<dmc::ClientCounters> client_counters; std::unique_ptr<dmc::ClientConfig> client_config; void accept(Listener& listener, boost::system::error_code ec); public: AsioFrontend(RGWProcessEnv& env, RGWFrontendConfig* conf, dmc::SchedulerCtx& sched_ctx) : env(env), conf(conf), pause_mutex(context.get_executor()) { auto sched_t = dmc::get_scheduler_t(ctx()); switch(sched_t){ case dmc::scheduler_t::dmclock: scheduler.reset(new dmc::AsyncScheduler(ctx(), context, std::ref(sched_ctx.get_dmc_client_counters()), sched_ctx.get_dmc_client_config(), *sched_ctx.get_dmc_client_config(), dmc::AtLimit::Reject)); break; case dmc::scheduler_t::none: lderr(ctx()) << "Got invalid scheduler type for beast, defaulting to throttler" << dendl; [[fallthrough]]; case dmc::scheduler_t::throttler: scheduler.reset(new dmc::SimpleThrottler(ctx())); } } int init(); int run(); void stop(); void join(); void pause(); void unpause(); }; unsigned short parse_port(const char *input, boost::system::error_code& ec) { char *end = nullptr; auto port = std::strtoul(input, &end, 10); if (port > std::numeric_limits<unsigned short>::max()) { ec.assign(ERANGE, boost::system::system_category()); } else if (port == 0 && end == input) { ec.assign(EINVAL, boost::system::system_category()); } return port; } tcp::endpoint parse_endpoint(boost::asio::string_view input, unsigned short default_port, boost::system::error_code& ec) { tcp::endpoint endpoint; if (input.empty()) { ec = boost::asio::error::invalid_argument; return endpoint; } if (input[0] == '[') { // ipv6 const size_t addr_begin = 1; const size_t addr_end = input.find(']'); if (addr_end == input.npos) { // no matching ] ec = boost::asio::error::invalid_argument; return endpoint; } if (addr_end + 1 < input.size()) { // :port must must follow [ipv6] if (input[addr_end + 1] != ':') { ec = boost::asio::error::invalid_argument; return endpoint; } else { auto port_str = input.substr(addr_end + 2); endpoint.port(parse_port(port_str.data(), ec)); } } else { endpoint.port(default_port); } auto addr = input.substr(addr_begin, addr_end - addr_begin); endpoint.address(boost::asio::ip::make_address_v6(addr, ec)); } else { // ipv4 auto colon = input.find(':'); if (colon != input.npos) { auto port_str = input.substr(colon + 1); endpoint.port(parse_port(port_str.data(), ec)); if (ec) { return endpoint; } } else { endpoint.port(default_port); } auto addr = input.substr(0, colon); endpoint.address(boost::asio::ip::make_address_v4(addr, ec)); } return endpoint; } static int drop_privileges(CephContext *ctx) { uid_t uid = ctx->get_set_uid(); gid_t gid = ctx->get_set_gid(); std::string uid_string = ctx->get_set_uid_string(); std::string gid_string = ctx->get_set_gid_string(); if (gid && setgid(gid) != 0) { int err = errno; ldout(ctx, -1) << "unable to setgid " << gid << ": " << cpp_strerror(err) << dendl; return -err; } if (uid && setuid(uid) != 0) { int err = errno; ldout(ctx, -1) << "unable to setuid " << uid << ": " << cpp_strerror(err) << dendl; return -err; } if (uid && gid) { ldout(ctx, 0) << "set uid:gid to " << uid << ":" << gid << " (" << uid_string << ":" << gid_string << ")" << dendl; } return 0; } int AsioFrontend::init() { boost::system::error_code ec; auto& config = conf->get_config_map(); if (auto i = config.find("prefix"); i != config.end()) { uri_prefix = i->second; } // Setting global timeout auto timeout = config.find("request_timeout_ms"); if (timeout != config.end()) { auto timeout_number = ceph::parse<uint64_t>(timeout->second); if (timeout_number) { request_timeout = std::chrono::milliseconds(*timeout_number); } else { lderr(ctx()) << "WARNING: invalid value for request_timeout_ms: " << timeout->second << " setting it to the default value: " << REQUEST_TIMEOUT << dendl; } } auto max_header_size = config.find("max_header_size"); if (max_header_size != config.end()) { auto limit = ceph::parse<uint64_t>(max_header_size->second); if (!limit) { lderr(ctx()) << "WARNING: invalid value for max_header_size: " << max_header_size->second << ", using the default value: " << header_limit << dendl; } else if (*limit > parse_buffer_size) { // can't exceed parse buffer size header_limit = parse_buffer_size; lderr(ctx()) << "WARNING: max_header_size " << max_header_size->second << " capped at maximum value " << header_limit << dendl; } else { header_limit = *limit; } } #ifdef WITH_RADOSGW_BEAST_OPENSSL int r = init_ssl(); if (r < 0) { return r; } #endif // parse endpoints auto ports = config.equal_range("port"); for (auto i = ports.first; i != ports.second; ++i) { auto port = parse_port(i->second.c_str(), ec); if (ec) { lderr(ctx()) << "failed to parse port=" << i->second << dendl; return -ec.value(); } listeners.emplace_back(context); listeners.back().endpoint.port(port); listeners.emplace_back(context); listeners.back().endpoint = tcp::endpoint(tcp::v6(), port); } auto endpoints = config.equal_range("endpoint"); for (auto i = endpoints.first; i != endpoints.second; ++i) { auto endpoint = parse_endpoint(i->second, 80, ec); if (ec) { lderr(ctx()) << "failed to parse endpoint=" << i->second << dendl; return -ec.value(); } listeners.emplace_back(context); listeners.back().endpoint = endpoint; } // parse tcp nodelay auto nodelay = config.find("tcp_nodelay"); if (nodelay != config.end()) { for (auto& l : listeners) { l.use_nodelay = (nodelay->second == "1"); } } bool socket_bound = false; // start listeners for (auto& l : listeners) { l.acceptor.open(l.endpoint.protocol(), ec); if (ec) { if (ec == boost::asio::error::address_family_not_supported) { ldout(ctx(), 0) << "WARNING: cannot open socket for endpoint=" << l.endpoint << ", " << ec.message() << dendl; continue; } lderr(ctx()) << "failed to open socket: " << ec.message() << dendl; return -ec.value(); } if (l.endpoint.protocol() == tcp::v6()) { l.acceptor.set_option(boost::asio::ip::v6_only(true), ec); if (ec) { lderr(ctx()) << "failed to set v6_only socket option: " << ec.message() << dendl; return -ec.value(); } } l.acceptor.set_option(tcp::acceptor::reuse_address(true)); l.acceptor.bind(l.endpoint, ec); if (ec) { lderr(ctx()) << "failed to bind address " << l.endpoint << ": " << ec.message() << dendl; return -ec.value(); } auto it = config.find("max_connection_backlog"); auto max_connection_backlog = boost::asio::socket_base::max_listen_connections; if (it != config.end()) { string err; max_connection_backlog = strict_strtol(it->second.c_str(), 10, &err); if (!err.empty()) { ldout(ctx(), 0) << "WARNING: invalid value for max_connection_backlog=" << it->second << dendl; max_connection_backlog = boost::asio::socket_base::max_listen_connections; } } l.acceptor.listen(max_connection_backlog); l.acceptor.async_accept(l.socket, [this, &l] (boost::system::error_code ec) { accept(l, ec); }); ldout(ctx(), 4) << "frontend listening on " << l.endpoint << dendl; socket_bound = true; } if (!socket_bound) { lderr(ctx()) << "Unable to listen at any endpoints" << dendl; return -EINVAL; } return drop_privileges(ctx()); } #ifdef WITH_RADOSGW_BEAST_OPENSSL static string config_val_prefix = "config://"; namespace { class ExpandMetaVar { map<string, string> meta_map; public: ExpandMetaVar(rgw::sal::Zone* zone_svc) { meta_map["realm"] = zone_svc->get_realm_name(); meta_map["realm_id"] = zone_svc->get_realm_id(); meta_map["zonegroup"] = zone_svc->get_zonegroup().get_name(); meta_map["zonegroup_id"] = zone_svc->get_zonegroup().get_id(); meta_map["zone"] = zone_svc->get_name(); meta_map["zone_id"] = zone_svc->get_id(); } string process_str(const string& in); }; string ExpandMetaVar::process_str(const string& in) { if (meta_map.empty()) { return in; } auto pos = in.find('$'); if (pos == std::string::npos) { return in; } string out; decltype(pos) last_pos = 0; while (pos != std::string::npos) { if (pos > last_pos) { out += in.substr(last_pos, pos - last_pos); } string var; const char *valid_chars = "abcdefghijklmnopqrstuvwxyz_"; size_t endpos = 0; if (in[pos+1] == '{') { // ...${foo_bar}... endpos = in.find_first_not_of(valid_chars, pos + 2); if (endpos != std::string::npos && in[endpos] == '}') { var = in.substr(pos + 2, endpos - pos - 2); endpos++; } } else { // ...$foo... endpos = in.find_first_not_of(valid_chars, pos + 1); if (endpos != std::string::npos) var = in.substr(pos + 1, endpos - pos - 1); else var = in.substr(pos + 1); } string var_source = in.substr(pos, endpos - pos); last_pos = endpos; auto iter = meta_map.find(var); if (iter != meta_map.end()) { out += iter->second; } else { out += var_source; } pos = in.find('$', last_pos); } if (last_pos != std::string::npos) { out += in.substr(last_pos); } return out; } } /* anonymous namespace */ int AsioFrontend::get_config_key_val(string name, const string& type, bufferlist *pbl) { if (name.empty()) { lderr(ctx()) << "bad " << type << " config value" << dendl; return -EINVAL; } int r = env.driver->get_config_key_val(name, pbl); if (r < 0) { lderr(ctx()) << type << " was not found: " << name << dendl; return r; } return 0; } int AsioFrontend::ssl_set_private_key(const string& name, bool is_ssl_certificate) { boost::system::error_code ec; if (!boost::algorithm::starts_with(name, config_val_prefix)) { ssl_context->use_private_key_file(name, ssl::context::pem, ec); } else { bufferlist bl; int r = get_config_key_val(name.substr(config_val_prefix.size()), "ssl_private_key", &bl); if (r < 0) { return r; } ssl_context->use_private_key(boost::asio::buffer(bl.c_str(), bl.length()), ssl::context::pem, ec); } if (ec) { if (!is_ssl_certificate) { lderr(ctx()) << "failed to add ssl_private_key=" << name << ": " << ec.message() << dendl; } else { lderr(ctx()) << "failed to use ssl_certificate=" << name << " as a private key: " << ec.message() << dendl; } return -ec.value(); } return 0; } int AsioFrontend::ssl_set_certificate_chain(const string& name) { boost::system::error_code ec; if (!boost::algorithm::starts_with(name, config_val_prefix)) { ssl_context->use_certificate_chain_file(name, ec); } else { bufferlist bl; int r = get_config_key_val(name.substr(config_val_prefix.size()), "ssl_certificate", &bl); if (r < 0) { return r; } ssl_context->use_certificate_chain(boost::asio::buffer(bl.c_str(), bl.length()), ec); } if (ec) { lderr(ctx()) << "failed to use ssl_certificate=" << name << ": " << ec.message() << dendl; return -ec.value(); } return 0; } int AsioFrontend::init_ssl() { boost::system::error_code ec; auto& config = conf->get_config_map(); // ssl configuration std::optional<string> cert = conf->get_val("ssl_certificate"); if (cert) { // only initialize the ssl context if it's going to be used ssl_context = boost::in_place(ssl::context::tls); } std::optional<string> key = conf->get_val("ssl_private_key"); bool have_cert = false; if (key && !cert) { lderr(ctx()) << "no ssl_certificate configured for ssl_private_key" << dendl; return -EINVAL; } std::optional<string> options = conf->get_val("ssl_options"); if (options) { if (!cert) { lderr(ctx()) << "no ssl_certificate configured for ssl_options" << dendl; return -EINVAL; } } else if (cert) { options = "no_sslv2:no_sslv3:no_tlsv1:no_tlsv1_1"; } if (options) { for (auto &option : ceph::split(*options, ":")) { if (option == "default_workarounds") { ssl_context->set_options(ssl::context::default_workarounds); } else if (option == "no_compression") { ssl_context->set_options(ssl::context::no_compression); } else if (option == "no_sslv2") { ssl_context->set_options(ssl::context::no_sslv2); } else if (option == "no_sslv3") { ssl_context->set_options(ssl::context::no_sslv3); } else if (option == "no_tlsv1") { ssl_context->set_options(ssl::context::no_tlsv1); } else if (option == "no_tlsv1_1") { ssl_context->set_options(ssl::context::no_tlsv1_1); } else if (option == "no_tlsv1_2") { ssl_context->set_options(ssl::context::no_tlsv1_2); } else if (option == "single_dh_use") { ssl_context->set_options(ssl::context::single_dh_use); } else { lderr(ctx()) << "ignoring unknown ssl option '" << option << "'" << dendl; } } } std::optional<string> ciphers = conf->get_val("ssl_ciphers"); if (ciphers) { if (!cert) { lderr(ctx()) << "no ssl_certificate configured for ssl_ciphers" << dendl; return -EINVAL; } int r = SSL_CTX_set_cipher_list(ssl_context->native_handle(), ciphers->c_str()); if (r == 0) { lderr(ctx()) << "no cipher could be selected from ssl_ciphers: " << *ciphers << dendl; return -EINVAL; } } auto ports = config.equal_range("ssl_port"); auto endpoints = config.equal_range("ssl_endpoint"); /* * don't try to config certificate if frontend isn't configured for ssl */ if (ports.first == ports.second && endpoints.first == endpoints.second) { return 0; } bool key_is_cert = false; if (cert) { if (!key) { key = cert; key_is_cert = true; } ExpandMetaVar emv(env.driver->get_zone()); cert = emv.process_str(*cert); key = emv.process_str(*key); int r = ssl_set_private_key(*key, key_is_cert); bool have_private_key = (r >= 0); if (r < 0) { if (!key_is_cert) { r = ssl_set_private_key(*cert, true); have_private_key = (r >= 0); } } if (have_private_key) { int r = ssl_set_certificate_chain(*cert); have_cert = (r >= 0); } } // parse ssl endpoints for (auto i = ports.first; i != ports.second; ++i) { if (!have_cert) { lderr(ctx()) << "no ssl_certificate configured for ssl_port" << dendl; return -EINVAL; } auto port = parse_port(i->second.c_str(), ec); if (ec) { lderr(ctx()) << "failed to parse ssl_port=" << i->second << dendl; return -ec.value(); } listeners.emplace_back(context); listeners.back().endpoint.port(port); listeners.back().use_ssl = true; listeners.emplace_back(context); listeners.back().endpoint = tcp::endpoint(tcp::v6(), port); listeners.back().use_ssl = true; } for (auto i = endpoints.first; i != endpoints.second; ++i) { if (!have_cert) { lderr(ctx()) << "no ssl_certificate configured for ssl_endpoint" << dendl; return -EINVAL; } auto endpoint = parse_endpoint(i->second, 443, ec); if (ec) { lderr(ctx()) << "failed to parse ssl_endpoint=" << i->second << dendl; return -ec.value(); } listeners.emplace_back(context); listeners.back().endpoint = endpoint; listeners.back().use_ssl = true; } return 0; } #endif // WITH_RADOSGW_BEAST_OPENSSL void AsioFrontend::accept(Listener& l, boost::system::error_code ec) { if (!l.acceptor.is_open()) { return; } else if (ec == boost::asio::error::operation_aborted) { return; } else if (ec) { ldout(ctx(), 1) << "accept failed: " << ec.message() << dendl; return; } auto stream = std::move(l.socket); stream.set_option(tcp::no_delay(l.use_nodelay), ec); l.acceptor.async_accept(l.socket, [this, &l] (boost::system::error_code ec) { accept(l, ec); }); // spawn a coroutine to handle the connection #ifdef WITH_RADOSGW_BEAST_OPENSSL if (l.use_ssl) { spawn::spawn(context, [this, s=std::move(stream)] (yield_context yield) mutable { auto conn = boost::intrusive_ptr{new Connection(std::move(s))}; auto c = connections.add(*conn); // wrap the tcp stream in an ssl stream boost::asio::ssl::stream<tcp_socket&> stream{conn->socket, *ssl_context}; auto timeout = timeout_timer{context.get_executor(), request_timeout, conn}; // do ssl handshake boost::system::error_code ec; timeout.start(); auto bytes = stream.async_handshake(ssl::stream_base::server, conn->buffer.data(), yield[ec]); timeout.cancel(); if (ec) { ldout(ctx(), 1) << "ssl handshake failed: " << ec.message() << dendl; return; } conn->buffer.consume(bytes); handle_connection(context, env, stream, timeout, header_limit, conn->buffer, true, pause_mutex, scheduler.get(), uri_prefix, ec, yield); if (!ec) { // ssl shutdown (ignoring errors) stream.async_shutdown(yield[ec]); } conn->socket.shutdown(tcp::socket::shutdown_both, ec); }, make_stack_allocator()); } else { #else { #endif // WITH_RADOSGW_BEAST_OPENSSL spawn::spawn(context, [this, s=std::move(stream)] (yield_context yield) mutable { auto conn = boost::intrusive_ptr{new Connection(std::move(s))}; auto c = connections.add(*conn); auto timeout = timeout_timer{context.get_executor(), request_timeout, conn}; boost::system::error_code ec; handle_connection(context, env, conn->socket, timeout, header_limit, conn->buffer, false, pause_mutex, scheduler.get(), uri_prefix, ec, yield); conn->socket.shutdown(tcp_socket::shutdown_both, ec); }, make_stack_allocator()); } } int AsioFrontend::run() { auto cct = ctx(); const int thread_count = cct->_conf->rgw_thread_pool_size; threads.reserve(thread_count); ldout(cct, 4) << "frontend spawning " << thread_count << " threads" << dendl; // the worker threads call io_context::run(), which will return when there's // no work left. hold a work guard to keep these threads going until join() work.emplace(boost::asio::make_work_guard(context)); for (int i = 0; i < thread_count; i++) { threads.emplace_back([this]() noexcept { // request warnings on synchronous librados calls in this thread is_asio_thread = true; // Have uncaught exceptions kill the process and give a // stacktrace, not be swallowed. context.run(); }); } return 0; } void AsioFrontend::stop() { ldout(ctx(), 4) << "frontend initiating shutdown..." << dendl; going_down = true; boost::system::error_code ec; // close all listeners for (auto& listener : listeners) { listener.acceptor.close(ec); } // close all connections connections.close(ec); pause_mutex.cancel(); } void AsioFrontend::join() { if (!going_down) { stop(); } work.reset(); ldout(ctx(), 4) << "frontend joining threads..." << dendl; for (auto& thread : threads) { thread.join(); } ldout(ctx(), 4) << "frontend done" << dendl; } void AsioFrontend::pause() { ldout(ctx(), 4) << "frontend pausing connections..." << dendl; // cancel pending calls to accept(), but don't close the sockets boost::system::error_code ec; for (auto& l : listeners) { l.acceptor.cancel(ec); } // pause and wait for outstanding requests to complete pause_mutex.lock(ec); if (ec) { ldout(ctx(), 1) << "frontend failed to pause: " << ec.message() << dendl; } else { ldout(ctx(), 4) << "frontend paused" << dendl; } } void AsioFrontend::unpause() { // unpause to unblock connections pause_mutex.unlock(); // start accepting connections again for (auto& l : listeners) { l.acceptor.async_accept(l.socket, [this, &l] (boost::system::error_code ec) { accept(l, ec); }); } ldout(ctx(), 4) << "frontend unpaused" << dendl; } } // anonymous namespace class RGWAsioFrontend::Impl : public AsioFrontend { public: Impl(RGWProcessEnv& env, RGWFrontendConfig* conf, rgw::dmclock::SchedulerCtx& sched_ctx) : AsioFrontend(env, conf, sched_ctx) {} }; RGWAsioFrontend::RGWAsioFrontend(RGWProcessEnv& env, RGWFrontendConfig* conf, rgw::dmclock::SchedulerCtx& sched_ctx) : impl(new Impl(env, conf, sched_ctx)) { } RGWAsioFrontend::~RGWAsioFrontend() = default; int RGWAsioFrontend::init() { return impl->init(); } int RGWAsioFrontend::run() { return impl->run(); } void RGWAsioFrontend::stop() { impl->stop(); } void RGWAsioFrontend::join() { impl->join(); } void RGWAsioFrontend::pause_for_new_config() { impl->pause(); } void RGWAsioFrontend::unpause_with_new_config() { impl->unpause(); }
36,436
29.364167
103
cc
null
ceph-main/src/rgw/rgw_asio_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 <memory> #include "rgw_frontend.h" #define REQUEST_TIMEOUT 65000 class RGWAsioFrontend : public RGWFrontend { class Impl; std::unique_ptr<Impl> impl; public: RGWAsioFrontend(RGWProcessEnv& env, RGWFrontendConfig* conf, rgw::dmclock::SchedulerCtx& sched_ctx); ~RGWAsioFrontend() override; int init() override; int run() override; void stop() override; void join() override; void pause_for_new_config() override; void unpause_with_new_config() override; };
611
22.538462
70
h
null
ceph-main/src/rgw/rgw_asio_frontend_timer.h
#pragma once #include <boost/asio/basic_waitable_timer.hpp> #include <boost/intrusive_ptr.hpp> #include "common/ceph_time.h" namespace rgw { // a WaitHandler that closes a stream if the timeout expires template <typename Stream> struct timeout_handler { // this handler may outlive the timer/stream, so we need to hold a reference // to keep the stream alive boost::intrusive_ptr<Stream> stream; explicit timeout_handler(boost::intrusive_ptr<Stream> stream) noexcept : stream(std::move(stream)) {} void operator()(boost::system::error_code ec) { if (!ec) { // wait was not canceled boost::system::error_code ec_ignored; stream->get_socket().cancel(); stream->get_socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec_ignored); } } }; // a timeout timer for stream operations template <typename Clock, typename Executor, typename Stream> class basic_timeout_timer { public: using clock_type = Clock; using duration = typename clock_type::duration; using executor_type = Executor; explicit basic_timeout_timer(const executor_type& ex, duration dur, boost::intrusive_ptr<Stream> stream) : timer(ex), dur(dur), stream(std::move(stream)) {} basic_timeout_timer(const basic_timeout_timer&) = delete; basic_timeout_timer& operator=(const basic_timeout_timer&) = delete; void start() { if (dur.count() > 0) { timer.expires_after(dur); timer.async_wait(timeout_handler{stream}); } } void cancel() { if (dur.count() > 0) { timer.cancel(); } } private: using Timer = boost::asio::basic_waitable_timer<clock_type, boost::asio::wait_traits<clock_type>, executor_type>; Timer timer; duration dur; boost::intrusive_ptr<Stream> stream; }; } // namespace rgw
1,822
26.208955
93
h
null
ceph-main/src/rgw/rgw_auth.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <array> #include <string> #include "rgw_common.h" #include "rgw_auth.h" #include "rgw_quota.h" #include "rgw_user.h" #include "rgw_http_client.h" #include "rgw_keystone.h" #include "rgw_sal.h" #include "rgw_log.h" #include "include/str_list.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; namespace rgw { namespace auth { std::unique_ptr<rgw::auth::Identity> transform_old_authinfo(CephContext* const cct, const rgw_user& auth_id, const int perm_mask, const bool is_admin, const uint32_t type) { /* This class is not intended for public use. Should be removed altogether * with this function after moving all our APIs to the new authentication * infrastructure. */ class DummyIdentityApplier : public rgw::auth::Identity { CephContext* const cct; /* For this particular case it's OK to use rgw_user structure to convey * the identity info as this was the policy for doing that before the * new auth. */ const rgw_user id; const int perm_mask; const bool is_admin; const uint32_t type; public: DummyIdentityApplier(CephContext* const cct, const rgw_user& auth_id, const int perm_mask, const bool is_admin, const uint32_t type) : cct(cct), id(auth_id), perm_mask(perm_mask), is_admin(is_admin), type(type) { } uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override { return rgw_perms_from_aclspec_default_strategy(id, aclspec, dpp); } bool is_admin_of(const rgw_user& acct_id) const override { return is_admin; } bool is_owner_of(const rgw_user& acct_id) const override { return id == acct_id; } bool is_identity(const idset_t& ids) const override { for (auto& p : ids) { if (p.is_wildcard()) { return true; } else if (p.is_tenant() && p.get_tenant() == id.tenant) { return true; } else if (p.is_user() && (p.get_tenant() == id.tenant) && (p.get_id() == id.id)) { return true; } } return false; } uint32_t get_perm_mask() const override { return perm_mask; } uint32_t get_identity_type() const override { return type; } string get_acct_name() const override { return {}; } string get_subuser() const override { return {}; } void to_str(std::ostream& out) const override { out << "RGWDummyIdentityApplier(auth_id=" << id << ", perm_mask=" << perm_mask << ", is_admin=" << is_admin << ")"; } }; return std::unique_ptr<rgw::auth::Identity>( new DummyIdentityApplier(cct, auth_id, perm_mask, is_admin, type)); } std::unique_ptr<rgw::auth::Identity> transform_old_authinfo(const req_state* const s) { return transform_old_authinfo(s->cct, s->user->get_id(), s->perm_mask, /* System user has admin permissions by default - it's supposed to pass * through any security check. */ s->system_request, s->user->get_type()); } } /* namespace auth */ } /* namespace rgw */ uint32_t rgw_perms_from_aclspec_default_strategy( const rgw_user& uid, const rgw::auth::Identity::aclspec_t& aclspec, const DoutPrefixProvider *dpp) { ldpp_dout(dpp, 5) << "Searching permissions for uid=" << uid << dendl; const auto iter = aclspec.find(uid.to_str()); if (std::end(aclspec) != iter) { ldpp_dout(dpp, 5) << "Found permission: " << iter->second << dendl; return iter->second; } ldpp_dout(dpp, 5) << "Permissions for user not found" << dendl; return 0; } static inline const std::string make_spec_item(const std::string& tenant, const std::string& id) { return tenant + ":" + id; } static inline std::pair<bool, rgw::auth::Engine::result_t> strategy_handle_rejected(rgw::auth::Engine::result_t&& engine_result, const rgw::auth::Strategy::Control policy, rgw::auth::Engine::result_t&& strategy_result) { using Control = rgw::auth::Strategy::Control; switch (policy) { case Control::REQUISITE: /* Don't try next. */ return std::make_pair(false, std::move(engine_result)); case Control::SUFFICIENT: /* Don't try next. */ return std::make_pair(false, std::move(engine_result)); case Control::FALLBACK: /* Don't try next. */ return std::make_pair(false, std::move(strategy_result)); default: /* Huh, memory corruption? */ ceph_abort(); } } static inline std::pair<bool, rgw::auth::Engine::result_t> strategy_handle_denied(rgw::auth::Engine::result_t&& engine_result, const rgw::auth::Strategy::Control policy, rgw::auth::Engine::result_t&& strategy_result) { using Control = rgw::auth::Strategy::Control; switch (policy) { case Control::REQUISITE: /* Don't try next. */ return std::make_pair(false, std::move(engine_result)); case Control::SUFFICIENT: /* Just try next. */ return std::make_pair(true, std::move(engine_result)); case Control::FALLBACK: return std::make_pair(true, std::move(strategy_result)); default: /* Huh, memory corruption? */ ceph_abort(); } } static inline std::pair<bool, rgw::auth::Engine::result_t> strategy_handle_granted(rgw::auth::Engine::result_t&& engine_result, const rgw::auth::Strategy::Control policy, rgw::auth::Engine::result_t&& strategy_result) { using Control = rgw::auth::Strategy::Control; switch (policy) { case Control::REQUISITE: /* Try next. */ return std::make_pair(true, std::move(engine_result)); case Control::SUFFICIENT: /* Don't try next. */ return std::make_pair(false, std::move(engine_result)); case Control::FALLBACK: /* Don't try next. */ return std::make_pair(false, std::move(engine_result)); default: /* Huh, memory corruption? */ ceph_abort(); } } rgw::auth::Engine::result_t rgw::auth::Strategy::authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const { result_t strategy_result = result_t::deny(); for (const stack_item_t& kv : auth_stack) { const rgw::auth::Engine& engine = kv.first; const auto& policy = kv.second; ldpp_dout(dpp, 20) << get_name() << ": trying " << engine.get_name() << dendl; result_t engine_result = result_t::deny(); try { engine_result = engine.authenticate(dpp, s, y); } catch (const int err) { engine_result = result_t::deny(err); } bool try_next = true; switch (engine_result.get_status()) { case result_t::Status::REJECTED: { ldpp_dout(dpp, 20) << engine.get_name() << " rejected with reason=" << engine_result.get_reason() << dendl; std::tie(try_next, strategy_result) = \ strategy_handle_rejected(std::move(engine_result), policy, std::move(strategy_result)); break; } case result_t::Status::DENIED: { ldpp_dout(dpp, 20) << engine.get_name() << " denied with reason=" << engine_result.get_reason() << dendl; std::tie(try_next, strategy_result) = \ strategy_handle_denied(std::move(engine_result), policy, std::move(strategy_result)); break; } case result_t::Status::GRANTED: { ldpp_dout(dpp, 20) << engine.get_name() << " granted access" << dendl; std::tie(try_next, strategy_result) = \ strategy_handle_granted(std::move(engine_result), policy, std::move(strategy_result)); break; } default: { ceph_abort(); } } if (! try_next) { break; } } return strategy_result; } int rgw::auth::Strategy::apply(const DoutPrefixProvider *dpp, const rgw::auth::Strategy& auth_strategy, req_state* const s, optional_yield y) noexcept { try { auto result = auth_strategy.authenticate(dpp, s, y); if (result.get_status() != decltype(result)::Status::GRANTED) { /* Access denied is acknowledged by returning a std::unique_ptr with * nullptr inside. */ ldpp_dout(dpp, 5) << "Failed the auth strategy, reason=" << result.get_reason() << dendl; return result.get_reason(); } try { rgw::auth::IdentityApplier::aplptr_t applier = result.get_applier(); rgw::auth::Completer::cmplptr_t completer = result.get_completer(); /* Account used by a given RGWOp is decoupled from identity employed * in the authorization phase (RGWOp::verify_permissions). */ applier->load_acct_info(dpp, s->user->get_info()); s->perm_mask = applier->get_perm_mask(); /* This is the single place where we pass req_state as a pointer * to non-const and thus its modification is allowed. In the time * of writing only RGWTempURLEngine needed that feature. */ applier->modify_request_state(dpp, s); if (completer) { completer->modify_request_state(dpp, s); } s->auth.identity = std::move(applier); s->auth.completer = std::move(completer); return 0; } catch (const int err) { ldpp_dout(dpp, 5) << "applier throwed err=" << err << dendl; return err; } catch (const std::exception& e) { ldpp_dout(dpp, 5) << "applier throwed unexpected err: " << e.what() << dendl; return -EPERM; } } catch (const int err) { ldpp_dout(dpp, 5) << "auth engine throwed err=" << err << dendl; return err; } catch (const std::exception& e) { ldpp_dout(dpp, 5) << "auth engine throwed unexpected err: " << e.what() << dendl; } /* We never should be here. */ return -EPERM; } void rgw::auth::Strategy::add_engine(const Control ctrl_flag, const Engine& engine) noexcept { auth_stack.push_back(std::make_pair(std::cref(engine), ctrl_flag)); } void rgw::auth::WebIdentityApplier::to_str(std::ostream& out) const { out << "rgw::auth::WebIdentityApplier(sub =" << sub << ", user_name=" << user_name << ", provider_id =" << iss << ")"; } string rgw::auth::WebIdentityApplier::get_idp_url() const { string idp_url = this->iss; idp_url = url_remove_prefix(idp_url); return idp_url; } void rgw::auth::WebIdentityApplier::create_account(const DoutPrefixProvider* dpp, const rgw_user& acct_user, const string& display_name, RGWUserInfo& user_info) const /* out */ { std::unique_ptr<rgw::sal::User> user = driver->get_user(acct_user); user->get_info().display_name = display_name; user->get_info().type = TYPE_WEB; user->get_info().max_buckets = cct->_conf.get_val<int64_t>("rgw_user_max_buckets"); rgw_apply_default_bucket_quota(user->get_info().quota.bucket_quota, cct->_conf); rgw_apply_default_user_quota(user->get_info().quota.user_quota, cct->_conf); int ret = user->store_user(dpp, null_yield, true); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to store new user info: user=" << user << " ret=" << ret << dendl; throw ret; } user_info = user->get_info(); } void rgw::auth::WebIdentityApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const { rgw_user federated_user; federated_user.id = this->sub; federated_user.tenant = role_tenant; federated_user.ns = "oidc"; std::unique_ptr<rgw::sal::User> user = driver->get_user(federated_user); //Check in oidc namespace if (user->load_user(dpp, null_yield) >= 0) { /* Succeeded. */ user_info = user->get_info(); return; } user->clear_ns(); //Check for old users which wouldn't have been created in oidc namespace if (user->load_user(dpp, null_yield) >= 0) { /* Succeeded. */ user_info = user->get_info(); return; } //Check if user_id.buckets already exists, may have been from the time, when shadow users didnt exist RGWStorageStats stats; int ret = user->read_stats(dpp, null_yield, &stats); if (ret < 0 && ret != -ENOENT) { ldpp_dout(dpp, 0) << "ERROR: reading stats for the user returned error " << ret << dendl; return; } if (ret == -ENOENT) { /* in case of ENOENT, which means user doesnt have buckets */ //In this case user will be created in oidc namespace ldpp_dout(dpp, 5) << "NOTICE: incoming user has no buckets " << federated_user << dendl; federated_user.ns = "oidc"; } else { //User already has buckets associated, hence wont be created in oidc namespace. ldpp_dout(dpp, 5) << "NOTICE: incoming user already has buckets associated " << federated_user << ", won't be created in oidc namespace"<< dendl; federated_user.ns = ""; } ldpp_dout(dpp, 0) << "NOTICE: couldn't map oidc federated user " << federated_user << dendl; create_account(dpp, federated_user, this->user_name, user_info); } void rgw::auth::WebIdentityApplier::modify_request_state(const DoutPrefixProvider *dpp, req_state* s) const { s->info.args.append("sub", this->sub); s->info.args.append("aud", this->aud); s->info.args.append("provider_id", this->iss); s->info.args.append("client_id", this->client_id); string condition; string idp_url = get_idp_url(); for (auto& claim : token_claims) { if (claim.first == "aud") { condition.clear(); condition = idp_url + ":app_id"; s->env.emplace(condition, claim.second); } condition.clear(); condition = idp_url + ":" + claim.first; s->env.emplace(condition, claim.second); } if (principal_tags) { constexpr size_t KEY_SIZE = 128, VAL_SIZE = 256; std::set<std::pair<string, string>> p_tags = principal_tags.get(); for (auto& it : p_tags) { string key = it.first; string val = it.second; if (key.find("aws:") == 0 || val.find("aws:") == 0) { ldpp_dout(dpp, 0) << "ERROR: Tag/Value can't start with aws:, hence skipping it" << dendl; continue; } if (key.size() > KEY_SIZE || val.size() > VAL_SIZE) { ldpp_dout(dpp, 0) << "ERROR: Invalid tag/value size, hence skipping it" << dendl; continue; } std::string p_key = "aws:PrincipalTag/"; p_key.append(key); s->principal_tags.emplace_back(std::make_pair(p_key, val)); ldpp_dout(dpp, 10) << "Principal Tag Key: " << p_key << " Value: " << val << dendl; std::string e_key = "aws:RequestTag/"; e_key.append(key); s->env.emplace(e_key, val); ldpp_dout(dpp, 10) << "RGW Env Tag Key: " << e_key << " Value: " << val << dendl; s->env.emplace("aws:TagKeys", key); ldpp_dout(dpp, 10) << "aws:TagKeys: " << key << dendl; if (s->principal_tags.size() == 50) { ldpp_dout(dpp, 0) << "ERROR: Number of tag/value pairs exceeding 50, hence skipping the rest" << dendl; break; } } } if (role_tags) { for (auto& it : role_tags.get()) { std::string p_key = "aws:PrincipalTag/"; p_key.append(it.first); s->principal_tags.emplace_back(std::make_pair(p_key, it.second)); ldpp_dout(dpp, 10) << "Principal Tag Key: " << p_key << " Value: " << it.second << dendl; std::string e_key = "iam:ResourceTag/"; e_key.append(it.first); s->env.emplace(e_key, it.second); ldpp_dout(dpp, 10) << "RGW Env Tag Key: " << e_key << " Value: " << it.second << dendl; } } } bool rgw::auth::WebIdentityApplier::is_identity(const idset_t& ids) const { if (ids.size() > 1) { return false; } for (auto id : ids) { string idp_url = get_idp_url(); if (id.is_oidc_provider() && id.get_idp_url() == idp_url) { return true; } } return false; } const std::string rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER; const std::string rgw::auth::RemoteApplier::AuthInfo::NO_ACCESS_KEY; /* rgw::auth::RemoteAuthApplier */ uint32_t rgw::auth::RemoteApplier::get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const { uint32_t perm = 0; /* For backward compatibility with ACLOwner. */ perm |= rgw_perms_from_aclspec_default_strategy(info.acct_user, aclspec, dpp); /* We also need to cover cases where rgw_keystone_implicit_tenants * was enabled. */ if (info.acct_user.tenant.empty()) { const rgw_user tenanted_acct_user(info.acct_user.id, info.acct_user.id); perm |= rgw_perms_from_aclspec_default_strategy(tenanted_acct_user, aclspec, dpp); } /* Now it's a time for invoking additional strategy that was supplied by * a specific auth engine. */ if (extra_acl_strategy) { perm |= extra_acl_strategy(aclspec); } ldpp_dout(dpp, 20) << "from ACL got perm=" << perm << dendl; return perm; } bool rgw::auth::RemoteApplier::is_admin_of(const rgw_user& uid) const { return info.is_admin; } bool rgw::auth::RemoteApplier::is_owner_of(const rgw_user& uid) const { if (info.acct_user.tenant.empty()) { const rgw_user tenanted_acct_user(info.acct_user.id, info.acct_user.id); if (tenanted_acct_user == uid) { return true; } } return info.acct_user == uid; } bool rgw::auth::RemoteApplier::is_identity(const idset_t& ids) const { for (auto& id : ids) { if (id.is_wildcard()) { return true; // We also need to cover cases where rgw_keystone_implicit_tenants // was enabled. */ } else if (id.is_tenant() && (info.acct_user.tenant.empty() ? info.acct_user.id : info.acct_user.tenant) == id.get_tenant()) { return true; } else if (id.is_user() && info.acct_user.id == id.get_id() && (info.acct_user.tenant.empty() ? info.acct_user.id : info.acct_user.tenant) == id.get_tenant()) { return true; } } return false; } void rgw::auth::RemoteApplier::to_str(std::ostream& out) const { out << "rgw::auth::RemoteApplier(acct_user=" << info.acct_user << ", acct_name=" << info.acct_name << ", perm_mask=" << info.perm_mask << ", is_admin=" << info.is_admin << ")"; } void rgw::auth::ImplicitTenants::recompute_value(const ConfigProxy& c) { std::string s = c.get_val<std::string>("rgw_keystone_implicit_tenants"); int v = 0; if (boost::iequals(s, "both") || boost::iequals(s, "true") || boost::iequals(s, "1")) { v = IMPLICIT_TENANTS_S3|IMPLICIT_TENANTS_SWIFT; } else if (boost::iequals(s, "0") || boost::iequals(s, "none") || boost::iequals(s, "false")) { v = 0; } else if (boost::iequals(s, "s3")) { v = IMPLICIT_TENANTS_S3; } else if (boost::iequals(s, "swift")) { v = IMPLICIT_TENANTS_SWIFT; } else { /* "" (and anything else) */ v = IMPLICIT_TENANTS_BAD; // assert(0); } saved = v; } const char **rgw::auth::ImplicitTenants::get_tracked_conf_keys() const { static const char *keys[] = { "rgw_keystone_implicit_tenants", nullptr }; return keys; } void rgw::auth::ImplicitTenants::handle_conf_change(const ConfigProxy& c, const std::set <std::string> &changed) { if (changed.count("rgw_keystone_implicit_tenants")) { recompute_value(c); } } void rgw::auth::RemoteApplier::create_account(const DoutPrefixProvider* dpp, const rgw_user& acct_user, bool implicit_tenant, RGWUserInfo& user_info) const /* out */ { rgw_user new_acct_user = acct_user; /* An upper layer may enforce creating new accounts within their own * tenants. */ if (new_acct_user.tenant.empty() && implicit_tenant) { new_acct_user.tenant = new_acct_user.id; } std::unique_ptr<rgw::sal::User> user = driver->get_user(new_acct_user); user->get_info().display_name = info.acct_name; if (info.acct_type) { //ldap/keystone for s3 users user->get_info().type = info.acct_type; } user->get_info().max_buckets = cct->_conf.get_val<int64_t>("rgw_user_max_buckets"); rgw_apply_default_bucket_quota(user->get_info().quota.bucket_quota, cct->_conf); rgw_apply_default_user_quota(user->get_info().quota.user_quota, cct->_conf); user_info = user->get_info(); int ret = user->store_user(dpp, null_yield, true); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: failed to store new user info: user=" << user << " ret=" << ret << dendl; throw ret; } } void rgw::auth::RemoteApplier::write_ops_log_entry(rgw_log_entry& entry) const { entry.access_key_id = info.access_key_id; entry.subuser = info.subuser; } /* TODO(rzarzynski): we need to handle display_name changes. */ void rgw::auth::RemoteApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const /* out */ { /* It's supposed that RGWRemoteAuthApplier tries to load account info * that belongs to the authenticated identity. Another policy may be * applied by using a RGWThirdPartyAccountAuthApplier decorator. */ const rgw_user& acct_user = info.acct_user; auto implicit_value = implicit_tenant_context.get_value(); bool implicit_tenant = implicit_value.implicit_tenants_for_(implicit_tenant_bit); bool split_mode = implicit_value.is_split_mode(); std::unique_ptr<rgw::sal::User> user; /* Normally, empty "tenant" field of acct_user means the authenticated * identity has the legacy, global tenant. However, due to inclusion * of multi-tenancy, we got some special compatibility kludge for remote * backends like Keystone. * If the global tenant is the requested one, we try the same tenant as * the user name first. If that RGWUserInfo exists, we use it. This way, * migrated OpenStack users can get their namespaced containers and nobody's * the wiser. * If that fails, we look up in the requested (possibly empty) tenant. * If that fails too, we create the account within the global or separated * namespace depending on rgw_keystone_implicit_tenants. * For compatibility with previous versions of ceph, it is possible * to enable implicit_tenants for only s3 or only swift. * in this mode ("split_mode"), we must constrain the id lookups to * only use the identifier space that would be used if the id were * to be created. */ if (split_mode && !implicit_tenant) ; /* suppress lookup for id used by "other" protocol */ else if (acct_user.tenant.empty()) { const rgw_user tenanted_uid(acct_user.id, acct_user.id); user = driver->get_user(tenanted_uid); if (user->load_user(dpp, null_yield) >= 0) { /* Succeeded. */ user_info = user->get_info(); return; } } user = driver->get_user(acct_user); if (split_mode && implicit_tenant) ; /* suppress lookup for id used by "other" protocol */ else if (user->load_user(dpp, null_yield) >= 0) { /* Succeeded. */ user_info = user->get_info(); return; } ldpp_dout(dpp, 0) << "NOTICE: couldn't map swift user " << acct_user << dendl; create_account(dpp, acct_user, implicit_tenant, user_info); /* Succeeded if we are here (create_account() hasn't throwed). */ } /* rgw::auth::LocalApplier */ /* static declaration */ const std::string rgw::auth::LocalApplier::NO_SUBUSER; const std::string rgw::auth::LocalApplier::NO_ACCESS_KEY; uint32_t rgw::auth::LocalApplier::get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const { return rgw_perms_from_aclspec_default_strategy(user_info.user_id, aclspec, dpp); } bool rgw::auth::LocalApplier::is_admin_of(const rgw_user& uid) const { return user_info.admin || user_info.system; } bool rgw::auth::LocalApplier::is_owner_of(const rgw_user& uid) const { return uid == user_info.user_id; } bool rgw::auth::LocalApplier::is_identity(const idset_t& ids) const { for (auto& id : ids) { if (id.is_wildcard()) { return true; } else if (id.is_tenant() && id.get_tenant() == user_info.user_id.tenant) { return true; } else if (id.is_user() && (id.get_tenant() == user_info.user_id.tenant)) { if (id.get_id() == user_info.user_id.id) { return true; } std::string wildcard_subuser = user_info.user_id.id; wildcard_subuser.append(":*"); if (wildcard_subuser == id.get_id()) { return true; } else if (subuser != NO_SUBUSER) { std::string user = user_info.user_id.id; user.append(":"); user.append(subuser); if (user == id.get_id()) { return true; } } } } return false; } void rgw::auth::LocalApplier::to_str(std::ostream& out) const { out << "rgw::auth::LocalApplier(acct_user=" << user_info.user_id << ", acct_name=" << user_info.display_name << ", subuser=" << subuser << ", perm_mask=" << get_perm_mask() << ", is_admin=" << static_cast<bool>(user_info.admin) << ")"; } uint32_t rgw::auth::LocalApplier::get_perm_mask(const std::string& subuser_name, const RGWUserInfo &uinfo) const { if (! subuser_name.empty() && subuser_name != NO_SUBUSER) { const auto iter = uinfo.subusers.find(subuser_name); if (iter != std::end(uinfo.subusers)) { return iter->second.perm_mask; } else { /* Subuser specified but not found. */ return RGW_PERM_NONE; } } else { /* Due to backward compatibility. */ return RGW_PERM_FULL_CONTROL; } } void rgw::auth::LocalApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const /* out */ { /* Load the account that belongs to the authenticated identity. An extra call * to RADOS may be safely skipped in this case. */ user_info = this->user_info; } void rgw::auth::LocalApplier::write_ops_log_entry(rgw_log_entry& entry) const { entry.access_key_id = access_key_id; entry.subuser = subuser; } void rgw::auth::RoleApplier::to_str(std::ostream& out) const { out << "rgw::auth::RoleApplier(role name =" << role.name; for (auto& policy: role.role_policies) { out << ", role policy =" << policy; } out << ", token policy =" << token_attrs.token_policy; out << ")"; } bool rgw::auth::RoleApplier::is_identity(const idset_t& ids) const { for (auto& p : ids) { if (p.is_wildcard()) { return true; } else if (p.is_role()) { string name = p.get_id(); string tenant = p.get_tenant(); if (name == role.name && tenant == role.tenant) { return true; } } else if (p.is_assumed_role()) { string tenant = p.get_tenant(); string role_session = role.name + "/" + token_attrs.role_session_name; //role/role-session if (role.tenant == tenant && role_session == p.get_role_session()) { return true; } } else { string id = p.get_id(); string tenant = p.get_tenant(); string oidc_id; if (token_attrs.user_id.ns.empty()) { oidc_id = token_attrs.user_id.id; } else { oidc_id = token_attrs.user_id.ns + "$" + token_attrs.user_id.id; } if (oidc_id == id && token_attrs.user_id.tenant == tenant) { return true; } } } return false; } void rgw::auth::RoleApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const /* out */ { /* Load the user id */ user_info.user_id = this->token_attrs.user_id; } void rgw::auth::RoleApplier::modify_request_state(const DoutPrefixProvider *dpp, req_state* s) const { for (auto it: role.role_policies) { try { bufferlist bl = bufferlist::static_from_string(it); const rgw::IAM::Policy p(s->cct, role.tenant, bl, false); s->iam_user_policies.push_back(std::move(p)); } catch (rgw::IAM::PolicyParseException& e) { //Control shouldn't reach here as the policy has already been //verified earlier ldpp_dout(dpp, 20) << "failed to parse role policy: " << e.what() << dendl; } } if (!this->token_attrs.token_policy.empty()) { try { string policy = this->token_attrs.token_policy; bufferlist bl = bufferlist::static_from_string(policy); const rgw::IAM::Policy p(s->cct, role.tenant, bl, false); s->session_policies.push_back(std::move(p)); } catch (rgw::IAM::PolicyParseException& e) { //Control shouldn't reach here as the policy has already been //verified earlier ldpp_dout(dpp, 20) << "failed to parse token policy: " << e.what() << dendl; } } string condition = "aws:userid"; string value = role.id + ":" + token_attrs.role_session_name; s->env.emplace(condition, value); s->env.emplace("aws:TokenIssueTime", token_attrs.token_issued_at); for (auto& m : token_attrs.principal_tags) { s->env.emplace(m.first, m.second); ldpp_dout(dpp, 10) << "Principal Tag Key: " << m.first << " Value: " << m.second << dendl; std::size_t pos = m.first.find('/'); string key = m.first.substr(pos + 1); s->env.emplace("aws:TagKeys", key); ldpp_dout(dpp, 10) << "aws:TagKeys: " << key << dendl; } s->token_claims.emplace_back("sts"); s->token_claims.emplace_back("role_name:" + role.tenant + "$" + role.name); s->token_claims.emplace_back("role_session:" + token_attrs.role_session_name); for (auto& it : token_attrs.token_claims) { s->token_claims.emplace_back(it); } } rgw::auth::Engine::result_t rgw::auth::AnonymousEngine::authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const { if (! is_applicable(s)) { return result_t::deny(-EPERM); } else { RGWUserInfo user_info; rgw_get_anon_user(user_info); auto apl = \ apl_factory->create_apl_local(cct, s, user_info, rgw::auth::LocalApplier::NO_SUBUSER, std::nullopt, rgw::auth::LocalApplier::NO_ACCESS_KEY); return result_t::grant(std::move(apl)); } }
30,728
31.865241
149
cc
null
ceph-main/src/rgw/rgw_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 <functional> #include <optional> #include <ostream> #include <type_traits> #include <system_error> #include <utility> #include "rgw_common.h" #include "rgw_web_idp.h" #define RGW_USER_ANON_ID "anonymous" class RGWCtl; struct rgw_log_entry; struct req_state; namespace rgw { namespace auth { using Exception = std::system_error; /* Load information about identity that will be used by RGWOp to authorize * any operation that comes from an authenticated user. */ class Identity { public: typedef std::map<std::string, int> aclspec_t; using idset_t = boost::container::flat_set<Principal>; virtual ~Identity() = default; /* Translate the ACL provided in @aclspec into concrete permission set that * can be used during the authorization phase (RGWOp::verify_permission). * On error throws rgw::auth::Exception storing the reason. * * NOTE: an implementation is responsible for giving the real semantic to * the items in @aclspec. That is, their meaning may depend on particular * applier that is being used. */ virtual uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const = 0; /* Verify whether a given identity *can be treated as* an admin of rgw_user * (account in Swift's terminology) specified in @uid. On error throws * rgw::auth::Exception storing the reason. */ virtual bool is_admin_of(const rgw_user& uid) const = 0; /* Verify whether a given identity *is* the owner of the rgw_user (account * in the Swift's terminology) specified in @uid. On internal error throws * rgw::auth::Exception storing the reason. */ virtual bool is_owner_of(const rgw_user& uid) const = 0; /* Return the permission mask that is used to narrow down the set of * operations allowed for a given identity. This method reflects the idea * of subuser tied to RGWUserInfo. On error throws rgw::auth::Exception * with the reason. */ virtual uint32_t get_perm_mask() const = 0; virtual bool is_anonymous() const { /* If the identity owns the anonymous account (rgw_user), it's considered * the anonymous identity. On error throws rgw::auth::Exception storing * the reason. */ return is_owner_of(rgw_user(RGW_USER_ANON_ID)); } virtual void to_str(std::ostream& out) const = 0; /* Verify whether a given identity corresponds to an identity in the provided set */ virtual bool is_identity(const idset_t& ids) const = 0; /* Identity Type: RGW/ LDAP/ Keystone */ virtual uint32_t get_identity_type() const = 0; /* Name of Account */ virtual std::string get_acct_name() const = 0; /* Subuser of Account */ virtual std::string get_subuser() const = 0; virtual std::string get_role_tenant() const { return ""; } /* write any auth-specific fields that are safe to expose in the ops log */ virtual void write_ops_log_entry(rgw_log_entry& entry) const {}; }; inline std::ostream& operator<<(std::ostream& out, const rgw::auth::Identity& id) { id.to_str(out); return out; } std::unique_ptr<rgw::auth::Identity> transform_old_authinfo(CephContext* const cct, const rgw_user& auth_id, const int perm_mask, const bool is_admin, const uint32_t type); std::unique_ptr<Identity> transform_old_authinfo(const req_state* const s); /* Interface for classes applying changes to request state/RADOS store * imposed by a particular rgw::auth::Engine. * * In contrast to rgw::auth::Engine, implementations of this interface * are allowed to handle req_state or RGWUserCtl in the read-write manner. * * It's expected that most (if not all) of implementations will also * conform to rgw::auth::Identity interface to provide authorization * policy (ACLs, account's ownership and entitlement). */ class IdentityApplier : public Identity { public: typedef std::unique_ptr<IdentityApplier> aplptr_t; virtual ~IdentityApplier() {}; /* Fill provided RGWUserInfo with information about the account that * RGWOp will operate on. Errors are handled solely through exceptions. * * XXX: be aware that the "account" term refers to rgw_user. The naming * is legacy. */ virtual void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const = 0; /* out */ /* Apply any changes to request state. This method will be most useful for * TempURL of Swift API. */ virtual void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) const {} /* in/out */ }; /* Interface class for completing the two-step authentication process. * Completer provides the second step - the complete() method that should * be called after Engine::authenticate() but before *committing* results * of an RGWOp (or sending a response in the case of non-mutating ops). * * The motivation driving the interface is to address those authentication * schemas that require message integrity verification *without* in-memory * data buffering. Typical examples are AWS Auth v4 and the auth mechanism * of browser uploads facilities both in S3 and Swift APIs (see RGWPostObj). * The workflow of request from the authentication point-of-view does look * like following one: * A. authenticate (Engine::authenticate), * B. authorize (see RGWOp::verify_permissions), * C. execute-prepare (init potential data modifications), * D. authenticate-complete - (Completer::complete), * E. execute-commit - commit the modifications from point C. */ class Completer { public: /* It's expected that Completers would tend to implement many interfaces * and be used not only in req_state::auth::completer. Ref counting their * instances would be helpful. */ typedef std::shared_ptr<Completer> cmplptr_t; virtual ~Completer() = default; /* Complete the authentication process. Return boolean indicating whether * the completion succeeded. On error throws rgw::auth::Exception storing * the reason. */ virtual bool complete() = 0; /* Apply any changes to request state. The initial use case was injecting * the AWSv4 filter over rgw::io::RestfulClient in req_state. */ virtual void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) = 0; /* in/out */ }; /* Interface class for authentication backends (auth engines) in RadosGW. * * An engine is supposed only to authenticate (not authorize!) requests * basing on their req_state and - if access has been granted - provide * an upper layer with: * - rgw::auth::IdentityApplier to commit all changes to the request state as * well as to the RADOS store (creating an account, synchronizing * user-related information with external databases and so on). * - rgw::auth::Completer (optionally) to finish the authentication * of the request. Typical use case is verifying message integrity * in AWS Auth v4 and browser uploads (RGWPostObj). * * Both of them are supposed to be wrapped in Engine::AuthResult. * * The authentication process consists of two steps: * - Engine::authenticate() which should be called before *initiating* * any modifications to RADOS store that are related to an operation * a client wants to perform (RGWOp::execute). * - Completer::complete() supposed to be called, if completer has been * returned, after the authenticate() step but before *committing* * those modifications or sending a response (RGWOp::complete). * * An engine outlives both Applier and Completer. It's intended to live * since RadosGW's initialization and handle multiple requests till * a reconfiguration. * * Auth engine MUST NOT make any changes to req_state nor RADOS store. * This is solely an Applier's responsibility! * * Separation between authentication and global state modification has * been introduced because many auth engines are orthogonal to appliers * and thus they can be decoupled. Additional motivation is to clearly * distinguish all portions of code modifying data structures. */ class Engine { public: virtual ~Engine() = default; class AuthResult { struct rejection_mark_t {}; bool is_rejected = false; int reason = 0; std::pair<IdentityApplier::aplptr_t, Completer::cmplptr_t> result_pair; explicit AuthResult(const int reason) : reason(reason) { } AuthResult(rejection_mark_t&&, const int reason) : is_rejected(true), reason(reason) { } /* Allow only the reasonable combintations - returning just Completer * without accompanying IdentityApplier is strictly prohibited! */ explicit AuthResult(IdentityApplier::aplptr_t&& applier) : result_pair(std::move(applier), nullptr) { } AuthResult(IdentityApplier::aplptr_t&& applier, Completer::cmplptr_t&& completer) : result_pair(std::move(applier), std::move(completer)) { } public: enum class Status { /* Engine doesn't grant the access but also doesn't reject it. */ DENIED, /* Engine successfully authenicated requester. */ GRANTED, /* Engine strictly indicates that a request should be rejected * without trying any further engine. */ REJECTED }; Status get_status() const { if (is_rejected) { return Status::REJECTED; } else if (! result_pair.first) { return Status::DENIED; } else { return Status::GRANTED; } } int get_reason() const { return reason; } IdentityApplier::aplptr_t get_applier() { return std::move(result_pair.first); } Completer::cmplptr_t&& get_completer() { return std::move(result_pair.second); } static AuthResult reject(const int reason = -EACCES) { return AuthResult(rejection_mark_t(), reason); } static AuthResult deny(const int reason = -EACCES) { return AuthResult(reason); } static AuthResult grant(IdentityApplier::aplptr_t&& applier) { return AuthResult(std::move(applier)); } static AuthResult grant(IdentityApplier::aplptr_t&& applier, Completer::cmplptr_t&& completer) { return AuthResult(std::move(applier), std::move(completer)); } }; using result_t = AuthResult; /* Get name of the auth engine. */ virtual const char* get_name() const noexcept = 0; /* Throwing method for identity verification. When the check is positive * an implementation should return Engine::result_t containing: * - a non-null pointer to an object conforming the Applier interface. * Otherwise, the authentication is treated as failed. * - a (potentially null) pointer to an object conforming the Completer * interface. * * On error throws rgw::auth::Exception containing the reason. */ virtual result_t authenticate(const DoutPrefixProvider* dpp, const req_state* s, optional_yield y) const = 0; }; /* Interface for extracting a token basing from data carried by req_state. */ class TokenExtractor { public: virtual ~TokenExtractor() = default; virtual std::string get_token(const req_state* s) const = 0; }; /* Abstract class for stacking sub-engines to expose them as a single * Engine. It is responsible for ordering its sub-engines and managing * fall-backs between them. Derivatee is supposed to encapsulate engine * instances and add them using the add_engine() method in the order it * wants to be tried during the call to authenticate(). * * Each new Strategy should be exposed to StrategyRegistry for handling * the dynamic reconfiguration. */ class Strategy : public Engine { public: /* Specifiers controlling what happens when an associated engine fails. * The names and semantic has been borrowed mostly from libpam. */ enum class Control { /* Failure of an engine injected with the REQUISITE specifier aborts * the strategy's authentication process immediately. No other engine * will be tried. */ REQUISITE, /* Success of an engine injected with the SUFFICIENT specifier ends * strategy's authentication process successfully. However, denying * doesn't abort it -- there will be fall-back to following engine * if the one that failed wasn't the last one. */ SUFFICIENT, /* Like SUFFICIENT with the exception that on failure the reason code * is not overridden. Instead, it's taken directly from the last tried * non-FALLBACK engine. If there was no previous non-FALLBACK engine * in a Strategy, then the result_t::deny(reason = -EACCES) is used. */ FALLBACK, }; Engine::result_t authenticate(const DoutPrefixProvider* dpp, const req_state* s, optional_yield y) const override final; bool is_empty() const { return auth_stack.empty(); } static int apply(const DoutPrefixProvider* dpp, const Strategy& auth_strategy, req_state* s, optional_yield y) noexcept; private: /* Using the reference wrapper here to explicitly point out we are not * interested in storing nulls while preserving the dynamic polymorphism. */ using stack_item_t = std::pair<std::reference_wrapper<const Engine>, Control>; std::vector<stack_item_t> auth_stack; protected: void add_engine(Control ctrl_flag, const Engine& engine) noexcept; }; /* A class aggregating the knowledge about all Strategies in RadosGW. It is * responsible for handling the dynamic reconfiguration on e.g. realm update. * The definition is in rgw/rgw_auth_registry.h, * * Each new Strategy should be exposed to it. */ class StrategyRegistry; class WebIdentityApplier : public IdentityApplier { std::string sub; std::string iss; std::string aud; std::string client_id; std::string user_name; protected: CephContext* const cct; rgw::sal::Driver* driver; std::string role_session; std::string role_tenant; std::unordered_multimap<std::string, std::string> token_claims; boost::optional<std::multimap<std::string,std::string>> role_tags; boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags; std::string get_idp_url() const; void create_account(const DoutPrefixProvider* dpp, const rgw_user& acct_user, const std::string& display_name, RGWUserInfo& user_info) const; /* out */ public: WebIdentityApplier( CephContext* const cct, rgw::sal::Driver* driver, const std::string& role_session, const std::string& role_tenant, const std::unordered_multimap<std::string, std::string>& token_claims, boost::optional<std::multimap<std::string,std::string>> role_tags, boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags) : cct(cct), driver(driver), role_session(role_session), role_tenant(role_tenant), token_claims(token_claims), role_tags(role_tags), principal_tags(principal_tags) { const auto& sub = token_claims.find("sub"); if(sub != token_claims.end()) { this->sub = sub->second; } const auto& iss = token_claims.find("iss"); if(iss != token_claims.end()) { this->iss = iss->second; } const auto& aud = token_claims.find("aud"); if(aud != token_claims.end()) { this->aud = aud->second; } const auto& client_id = token_claims.find("client_id"); if(client_id != token_claims.end()) { this->client_id = client_id->second; } else { const auto& azp = token_claims.find("azp"); if (azp != token_claims.end()) { this->client_id = azp->second; } } const auto& user_name = token_claims.find("username"); if(user_name != token_claims.end()) { this->user_name = user_name->second; } else { const auto& given_username = token_claims.find("given_username"); if (given_username != token_claims.end()) { this->user_name = given_username->second; } } } void modify_request_state(const DoutPrefixProvider *dpp, req_state* s) const override; uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override { return RGW_PERM_NONE; } bool is_admin_of(const rgw_user& uid) const override { return false; } bool is_owner_of(const rgw_user& uid) const override { if (uid.id == this->sub && uid.tenant == role_tenant && uid.ns == "oidc") { return true; } return false; } uint32_t get_perm_mask() const override { return RGW_PERM_NONE; } void to_str(std::ostream& out) const override; bool is_identity(const idset_t& ids) const override; void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; uint32_t get_identity_type() const override { return TYPE_WEB; } std::string get_acct_name() const override { return this->user_name; } std::string get_subuser() const override { return {}; } struct Factory { virtual ~Factory() {} virtual aplptr_t create_apl_web_identity( CephContext* cct, const req_state* s, const std::string& role_session, const std::string& role_tenant, const std::unordered_multimap<std::string, std::string>& token, boost::optional<std::multimap<std::string, std::string>>, boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags) const = 0; }; }; class ImplicitTenants: public md_config_obs_t { public: enum implicit_tenant_flag_bits {IMPLICIT_TENANTS_SWIFT=1, IMPLICIT_TENANTS_S3=2, IMPLICIT_TENANTS_BAD = -1, }; private: int saved; void recompute_value(const ConfigProxy& ); class ImplicitTenantValue { friend class ImplicitTenants; int v; ImplicitTenantValue(int v) : v(v) {}; public: bool inline is_split_mode() { assert(v != IMPLICIT_TENANTS_BAD); return v == IMPLICIT_TENANTS_SWIFT || v == IMPLICIT_TENANTS_S3; } bool inline implicit_tenants_for_(const implicit_tenant_flag_bits bit) { assert(v != IMPLICIT_TENANTS_BAD); return static_cast<bool>(v&bit); } }; public: ImplicitTenants(const ConfigProxy& c) { recompute_value(c);} ImplicitTenantValue get_value() const { return ImplicitTenantValue(saved); } private: const char** get_tracked_conf_keys() const override; void handle_conf_change(const ConfigProxy& conf, const std::set <std::string> &changed) override; }; std::tuple<bool,bool> implicit_tenants_enabled_for_swift(CephContext * const cct); std::tuple<bool,bool> implicit_tenants_enabled_for_s3(CephContext * const cct); /* rgw::auth::RemoteApplier targets those authentication engines which don't * need to ask the RADOS store while performing the auth process. Instead, * they obtain credentials from an external source like Keystone or LDAP. * * As the authenticated user may not have an account yet, RGWRemoteAuthApplier * must be able to create it basing on data passed by an auth engine. Those * data will be used to fill RGWUserInfo structure. */ class RemoteApplier : public IdentityApplier { public: class AuthInfo { friend class RemoteApplier; protected: const rgw_user acct_user; const std::string acct_name; const uint32_t perm_mask; const bool is_admin; const uint32_t acct_type; const std::string access_key_id; const std::string subuser; public: enum class acct_privilege_t { IS_ADMIN_ACCT, IS_PLAIN_ACCT }; static const std::string NO_SUBUSER; static const std::string NO_ACCESS_KEY; AuthInfo(const rgw_user& acct_user, const std::string& acct_name, const uint32_t perm_mask, const acct_privilege_t level, const std::string access_key_id, const std::string subuser, const uint32_t acct_type=TYPE_NONE) : acct_user(acct_user), acct_name(acct_name), perm_mask(perm_mask), is_admin(acct_privilege_t::IS_ADMIN_ACCT == level), acct_type(acct_type), access_key_id(access_key_id), subuser(subuser) { } }; using aclspec_t = rgw::auth::Identity::aclspec_t; typedef std::function<uint32_t(const aclspec_t&)> acl_strategy_t; protected: CephContext* const cct; /* Read-write is intensional here due to RGWUserInfo creation process. */ rgw::sal::Driver* driver; /* Supplemental strategy for extracting permissions from ACLs. Its results * will be combined (ORed) with a default strategy that is responsible for * handling backward compatibility. */ const acl_strategy_t extra_acl_strategy; const AuthInfo info; const rgw::auth::ImplicitTenants& implicit_tenant_context; const rgw::auth::ImplicitTenants::implicit_tenant_flag_bits implicit_tenant_bit; virtual void create_account(const DoutPrefixProvider* dpp, const rgw_user& acct_user, bool implicit_tenant, RGWUserInfo& user_info) const; /* out */ public: RemoteApplier(CephContext* const cct, rgw::sal::Driver* driver, acl_strategy_t&& extra_acl_strategy, const AuthInfo& info, const rgw::auth::ImplicitTenants& implicit_tenant_context, rgw::auth::ImplicitTenants::implicit_tenant_flag_bits implicit_tenant_bit) : cct(cct), driver(driver), extra_acl_strategy(std::move(extra_acl_strategy)), info(info), implicit_tenant_context(implicit_tenant_context), implicit_tenant_bit(implicit_tenant_bit) { } uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override; bool is_admin_of(const rgw_user& uid) const override; bool is_owner_of(const rgw_user& uid) const override; bool is_identity(const idset_t& ids) const override; uint32_t get_perm_mask() const override { return info.perm_mask; } void to_str(std::ostream& out) const override; void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */ void write_ops_log_entry(rgw_log_entry& entry) const override; uint32_t get_identity_type() const override { return info.acct_type; } std::string get_acct_name() const override { return info.acct_name; } std::string get_subuser() const override { return {}; } struct Factory { virtual ~Factory() {} /* Providing r-value reference here is required intensionally. Callee is * thus disallowed to handle std::function in a way that could inhibit * the move behaviour (like forgetting about std::moving a l-value). */ virtual aplptr_t create_apl_remote(CephContext* cct, const req_state* s, acl_strategy_t&& extra_acl_strategy, const AuthInfo &info) const = 0; }; }; /* rgw::auth::LocalApplier targets those auth engines that base on the data * enclosed in the RGWUserInfo control structure. As a side effect of doing * the authentication process, they must have it loaded. Leveraging this is * a way to avoid unnecessary calls to underlying RADOS store. */ class LocalApplier : public IdentityApplier { using aclspec_t = rgw::auth::Identity::aclspec_t; protected: const RGWUserInfo user_info; const std::string subuser; uint32_t perm_mask; const std::string access_key_id; uint32_t get_perm_mask(const std::string& subuser_name, const RGWUserInfo &uinfo) const; public: static const std::string NO_SUBUSER; static const std::string NO_ACCESS_KEY; LocalApplier(CephContext* const cct, const RGWUserInfo& user_info, std::string subuser, const std::optional<uint32_t>& perm_mask, const std::string access_key_id) : user_info(user_info), subuser(std::move(subuser)), perm_mask(perm_mask.value_or(RGW_PERM_INVALID)), access_key_id(access_key_id) { } uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override; bool is_admin_of(const rgw_user& uid) const override; bool is_owner_of(const rgw_user& uid) const override; bool is_identity(const idset_t& ids) const override; uint32_t get_perm_mask() const override { if (this->perm_mask == RGW_PERM_INVALID) { return get_perm_mask(subuser, user_info); } else { return this->perm_mask; } } void to_str(std::ostream& out) const override; void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */ uint32_t get_identity_type() const override { return TYPE_RGW; } std::string get_acct_name() const override { return {}; } std::string get_subuser() const override { return subuser; } void write_ops_log_entry(rgw_log_entry& entry) const override; struct Factory { virtual ~Factory() {} virtual aplptr_t create_apl_local(CephContext* cct, const req_state* s, const RGWUserInfo& user_info, const std::string& subuser, const std::optional<uint32_t>& perm_mask, const std::string& access_key_id) const = 0; }; }; class RoleApplier : public IdentityApplier { public: struct Role { std::string id; std::string name; std::string tenant; std::vector<std::string> role_policies; }; struct TokenAttrs { rgw_user user_id; std::string token_policy; std::string role_session_name; std::vector<std::string> token_claims; std::string token_issued_at; std::vector<std::pair<std::string, std::string>> principal_tags; }; protected: Role role; TokenAttrs token_attrs; public: RoleApplier(CephContext* const cct, const Role& role, const TokenAttrs& token_attrs) : role(role), token_attrs(token_attrs) {} uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override { return 0; } bool is_admin_of(const rgw_user& uid) const override { return false; } bool is_owner_of(const rgw_user& uid) const override { return (this->token_attrs.user_id.id == uid.id && this->token_attrs.user_id.tenant == uid.tenant && this->token_attrs.user_id.ns == uid.ns); } bool is_identity(const idset_t& ids) const override; uint32_t get_perm_mask() const override { return RGW_PERM_NONE; } void to_str(std::ostream& out) const override; void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */ uint32_t get_identity_type() const override { return TYPE_ROLE; } std::string get_acct_name() const override { return {}; } std::string get_subuser() const override { return {}; } void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) const override; std::string get_role_tenant() const override { return role.tenant; } struct Factory { virtual ~Factory() {} virtual aplptr_t create_apl_role( CephContext* cct, const req_state* s, const rgw::auth::RoleApplier::Role& role, const rgw::auth::RoleApplier::TokenAttrs& token_attrs) const = 0; }; }; /* The anonymous abstract engine. */ class AnonymousEngine : public Engine { CephContext* const cct; const rgw::auth::LocalApplier::Factory* const apl_factory; public: AnonymousEngine(CephContext* const cct, const rgw::auth::LocalApplier::Factory* const apl_factory) : cct(cct), apl_factory(apl_factory) { } const char* get_name() const noexcept override { return "rgw::auth::AnonymousEngine"; } Engine::result_t authenticate(const DoutPrefixProvider* dpp, const req_state* s, optional_yield y) const override final; protected: virtual bool is_applicable(const req_state*) const noexcept { return true; } }; } /* namespace auth */ } /* namespace rgw */ uint32_t rgw_perms_from_aclspec_default_strategy( const rgw_user& uid, const rgw::auth::Identity::aclspec_t& aclspec, const DoutPrefixProvider *dpp);
28,787
35.348485
144
h
null
ceph-main/src/rgw/rgw_auth_filters.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 <type_traits> #include <boost/logic/tribool.hpp> #include <boost/optional.hpp> #include "rgw_service.h" #include "rgw_common.h" #include "rgw_auth.h" #include "rgw_user.h" namespace rgw { namespace auth { /* Abstract decorator over any implementation of rgw::auth::IdentityApplier * which could be provided both as a pointer-to-object or the object itself. */ template <typename DecorateeT> class DecoratedApplier : public rgw::auth::IdentityApplier { typedef typename std::remove_pointer<DecorateeT>::type DerefedDecorateeT; static_assert(std::is_base_of<rgw::auth::IdentityApplier, DerefedDecorateeT>::value, "DecorateeT must be a subclass of rgw::auth::IdentityApplier"); DecorateeT decoratee; /* There is an indirection layer over accessing decoratee to share the same * code base between dynamic and static decorators. The difference is about * what we store internally: pointer to a decorated object versus the whole * object itself. Googling for "SFINAE" can help to understand the code. */ template <typename T = void, typename std::enable_if< std::is_pointer<DecorateeT>::value, T>::type* = nullptr> DerefedDecorateeT& get_decoratee() { return *decoratee; } template <typename T = void, typename std::enable_if< ! std::is_pointer<DecorateeT>::value, T>::type* = nullptr> DerefedDecorateeT& get_decoratee() { return decoratee; } template <typename T = void, typename std::enable_if< std::is_pointer<DecorateeT>::value, T>::type* = nullptr> const DerefedDecorateeT& get_decoratee() const { return *decoratee; } template <typename T = void, typename std::enable_if< ! std::is_pointer<DecorateeT>::value, T>::type* = nullptr> const DerefedDecorateeT& get_decoratee() const { return decoratee; } public: explicit DecoratedApplier(DecorateeT&& decoratee) : decoratee(std::forward<DecorateeT>(decoratee)) { } uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override { return get_decoratee().get_perms_from_aclspec(dpp, aclspec); } bool is_admin_of(const rgw_user& uid) const override { return get_decoratee().is_admin_of(uid); } bool is_owner_of(const rgw_user& uid) const override { return get_decoratee().is_owner_of(uid); } bool is_anonymous() const override { return get_decoratee().is_anonymous(); } uint32_t get_perm_mask() const override { return get_decoratee().get_perm_mask(); } uint32_t get_identity_type() const override { return get_decoratee().get_identity_type(); } std::string get_acct_name() const override { return get_decoratee().get_acct_name(); } std::string get_subuser() const override { return get_decoratee().get_subuser(); } bool is_identity( const boost::container::flat_set<Principal>& ids) const override { return get_decoratee().is_identity(ids); } void to_str(std::ostream& out) const override { get_decoratee().to_str(out); } std::string get_role_tenant() const override { /* in/out */ return get_decoratee().get_role_tenant(); } void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override { /* out */ return get_decoratee().load_acct_info(dpp, user_info); } void modify_request_state(const DoutPrefixProvider* dpp, req_state * s) const override { /* in/out */ return get_decoratee().modify_request_state(dpp, s); } void write_ops_log_entry(rgw_log_entry& entry) const override { return get_decoratee().write_ops_log_entry(entry); } }; template <typename T> class ThirdPartyAccountApplier : public DecoratedApplier<T> { rgw::sal::Driver* driver; const rgw_user acct_user_override; public: /* A value representing situations where there is no requested account * override. In other words, acct_user_override will be equal to this * constant where the request isn't a cross-tenant one. */ static const rgw_user UNKNOWN_ACCT; template <typename U> ThirdPartyAccountApplier(rgw::sal::Driver* driver, const rgw_user &acct_user_override, U&& decoratee) : DecoratedApplier<T>(std::move(decoratee)), driver(driver), acct_user_override(acct_user_override) { } void to_str(std::ostream& out) const override; void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */ }; /* static declaration: UNKNOWN_ACCT will be an empty rgw_user that is a result * of the default construction. */ template <typename T> const rgw_user ThirdPartyAccountApplier<T>::UNKNOWN_ACCT; template <typename T> void ThirdPartyAccountApplier<T>::to_str(std::ostream& out) const { out << "rgw::auth::ThirdPartyAccountApplier(" + acct_user_override.to_str() + ")" << " -> "; DecoratedApplier<T>::to_str(out); } template <typename T> void ThirdPartyAccountApplier<T>::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const { if (UNKNOWN_ACCT == acct_user_override) { /* There is no override specified by the upper layer. This means that we'll * load the account owned by the authenticated identity (aka auth_user). */ DecoratedApplier<T>::load_acct_info(dpp, user_info); } else if (DecoratedApplier<T>::is_owner_of(acct_user_override)) { /* The override has been specified but the account belongs to the authenticated * identity. We may safely forward the call to a next stage. */ DecoratedApplier<T>::load_acct_info(dpp, user_info); } else if (this->is_anonymous()) { /* If the user was authed by the anonymous engine then scope the ANON user * to the correct tenant */ if (acct_user_override.tenant.empty()) user_info.user_id = rgw_user(acct_user_override.id, RGW_USER_ANON_ID); else user_info.user_id = rgw_user(acct_user_override.tenant, RGW_USER_ANON_ID); } else { /* Compatibility mechanism for multi-tenancy. For more details refer to * load_acct_info method of rgw::auth::RemoteApplier. */ std::unique_ptr<rgw::sal::User> user; if (acct_user_override.tenant.empty()) { const rgw_user tenanted_uid(acct_user_override.id, acct_user_override.id); user = driver->get_user(tenanted_uid); if (user->load_user(dpp, null_yield) >= 0) { user_info = user->get_info(); /* Succeeded. */ return; } } user = driver->get_user(acct_user_override); const int ret = user->load_user(dpp, null_yield); if (ret < 0) { /* We aren't trying to recover from ENOENT here. It's supposed that creating * someone else's account isn't a thing we want to support in this filter. */ if (ret == -ENOENT) { throw -EACCES; } else { throw ret; } } user_info = user->get_info(); } } template <typename T> static inline ThirdPartyAccountApplier<T> add_3rdparty(rgw::sal::Driver* driver, const rgw_user &acct_user_override, T&& t) { return ThirdPartyAccountApplier<T>(driver, acct_user_override, std::forward<T>(t)); } template <typename T> class SysReqApplier : public DecoratedApplier<T> { CephContext* const cct; rgw::sal::Driver* driver; const RGWHTTPArgs& args; mutable boost::tribool is_system; public: template <typename U> SysReqApplier(CephContext* const cct, rgw::sal::Driver* driver, const req_state* const s, U&& decoratee) : DecoratedApplier<T>(std::forward<T>(decoratee)), cct(cct), driver(driver), args(s->info.args), is_system(boost::logic::indeterminate) { } void to_str(std::ostream& out) const override; void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */ void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) const override; /* in/out */ }; template <typename T> void SysReqApplier<T>::to_str(std::ostream& out) const { out << "rgw::auth::SysReqApplier" << " -> "; DecoratedApplier<T>::to_str(out); } template <typename T> void SysReqApplier<T>::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const { DecoratedApplier<T>::load_acct_info(dpp, user_info); is_system = user_info.system; if (is_system) { //ldpp_dout(dpp, 20) << "system request" << dendl; rgw_user effective_uid(args.sys_get(RGW_SYS_PARAM_PREFIX "uid")); if (! effective_uid.empty()) { /* We aren't writing directly to user_info for consistency and security * reasons. rgw_get_user_info_by_uid doesn't trigger the operator=() but * calls ::decode instead. */ std::unique_ptr<rgw::sal::User> user = driver->get_user(effective_uid); if (user->load_user(dpp, null_yield) < 0) { //ldpp_dout(dpp, 0) << "User lookup failed!" << dendl; throw -EACCES; } user_info = user->get_info(); } } } template <typename T> void SysReqApplier<T>::modify_request_state(const DoutPrefixProvider* dpp, req_state* const s) const { if (boost::logic::indeterminate(is_system)) { RGWUserInfo unused_info; load_acct_info(dpp, unused_info); } if (is_system) { s->info.args.set_system(); s->system_request = true; } DecoratedApplier<T>::modify_request_state(dpp, s); } template <typename T> static inline SysReqApplier<T> add_sysreq(CephContext* const cct, rgw::sal::Driver* driver, const req_state* const s, T&& t) { return SysReqApplier<T>(cct, driver, s, std::forward<T>(t)); } } /* namespace auth */ } /* namespace rgw */
9,946
31.828383
109
h
null
ceph-main/src/rgw/rgw_auth_keystone.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <string> #include <vector> #include <errno.h> #include <fnmatch.h> #include "rgw_b64.h" #include "common/errno.h" #include "common/ceph_json.h" #include "include/types.h" #include "include/str_list.h" #include "rgw_common.h" #include "rgw_keystone.h" #include "rgw_auth_keystone.h" #include "rgw_rest_s3.h" #include "rgw_auth_s3.h" #include "common/ceph_crypto.h" #include "common/Cond.h" #define dout_subsys ceph_subsys_rgw using namespace std; namespace rgw { namespace auth { namespace keystone { bool TokenEngine::is_applicable(const std::string& token) const noexcept { return ! token.empty() && ! cct->_conf->rgw_keystone_url.empty(); } boost::optional<TokenEngine::token_envelope_t> TokenEngine::get_from_keystone(const DoutPrefixProvider* dpp, const std::string& token, bool allow_expired) const { /* Unfortunately, we can't use the short form of "using" here. It's because * we're aliasing a class' member, not namespace. */ using RGWValidateKeystoneToken = \ rgw::keystone::Service::RGWValidateKeystoneToken; /* The container for plain response obtained from Keystone. It will be * parsed token_envelope_t::parse method. */ ceph::bufferlist token_body_bl; RGWValidateKeystoneToken validate(cct, "GET", "", &token_body_bl); std::string url = config.get_endpoint_url(); if (url.empty()) { throw -EINVAL; } const auto keystone_version = config.get_api_version(); if (keystone_version == rgw::keystone::ApiVersion::VER_2) { url.append("v2.0/tokens/" + token); } else if (keystone_version == rgw::keystone::ApiVersion::VER_3) { url.append("v3/auth/tokens"); if (allow_expired) { url.append("?allow_expired=1"); } validate.append_header("X-Subject-Token", token); } std::string admin_token; if (rgw::keystone::Service::get_admin_token(dpp, cct, token_cache, config, admin_token) < 0) { throw -EINVAL; } validate.append_header("X-Auth-Token", admin_token); validate.set_send_length(0); validate.set_url(url); int ret = validate.process(null_yield); if (ret < 0) { throw ret; } /* NULL terminate for debug output. */ token_body_bl.append(static_cast<char>(0)); /* Detect Keystone rejection earlier than during the token parsing. * Although failure at the parsing phase doesn't impose a threat, * this allows to return proper error code (EACCESS instead of EINVAL * or similar) and thus improves logging. */ if (validate.get_http_status() == /* Most likely: wrong admin credentials or admin token. */ RGWValidateKeystoneToken::HTTP_STATUS_UNAUTHORIZED || validate.get_http_status() == /* Most likely: non-existent token supplied by the client. */ RGWValidateKeystoneToken::HTTP_STATUS_NOTFOUND) { ldpp_dout(dpp, 5) << "Failed keystone auth from " << url << " with " << validate.get_http_status() << dendl; return boost::none; } ldpp_dout(dpp, 20) << "received response status=" << validate.get_http_status() << ", body=" << token_body_bl.c_str() << dendl; TokenEngine::token_envelope_t token_body; ret = token_body.parse(dpp, cct, token, token_body_bl, config.get_api_version()); if (ret < 0) { throw ret; } return token_body; } TokenEngine::auth_info_t TokenEngine::get_creds_info(const TokenEngine::token_envelope_t& token ) const noexcept { using acct_privilege_t = rgw::auth::RemoteApplier::AuthInfo::acct_privilege_t; /* Check whether the user has an admin status. */ acct_privilege_t level = acct_privilege_t::IS_PLAIN_ACCT; for (const auto& role : token.roles) { if (role.is_admin && !role.is_reader) { level = acct_privilege_t::IS_ADMIN_ACCT; break; } } return auth_info_t { /* Suggested account name for the authenticated user. */ rgw_user(token.get_project_id()), /* User's display name (aka real name). */ token.get_project_name(), /* Keystone doesn't support RGW's subuser concept, so we cannot cut down * the access rights through the perm_mask. At least at this layer. */ RGW_PERM_FULL_CONTROL, level, rgw::auth::RemoteApplier::AuthInfo::NO_ACCESS_KEY, rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER, TYPE_KEYSTONE }; } static inline const std::string make_spec_item(const std::string& tenant, const std::string& id) { return tenant + ":" + id; } TokenEngine::acl_strategy_t TokenEngine::get_acl_strategy(const TokenEngine::token_envelope_t& token) const { /* The primary identity is constructed upon UUIDs. */ const auto& tenant_uuid = token.get_project_id(); const auto& user_uuid = token.get_user_id(); /* For Keystone v2 an alias may be also used. */ const auto& tenant_name = token.get_project_name(); const auto& user_name = token.get_user_name(); /* Construct all possible combinations including Swift's wildcards. */ const std::array<std::string, 6> allowed_items = { make_spec_item(tenant_uuid, user_uuid), make_spec_item(tenant_name, user_name), /* Wildcards. */ make_spec_item(tenant_uuid, "*"), make_spec_item(tenant_name, "*"), make_spec_item("*", user_uuid), make_spec_item("*", user_name), }; /* Lambda will obtain a copy of (not a reference to!) allowed_items. */ return [allowed_items, token_roles=token.roles](const rgw::auth::Identity::aclspec_t& aclspec) { uint32_t perm = 0; for (const auto& allowed_item : allowed_items) { const auto iter = aclspec.find(allowed_item); if (std::end(aclspec) != iter) { perm |= iter->second; } } for (const auto& r : token_roles) { if (r.is_reader) { if (r.is_admin) { /* system scope reader persona */ /* * Because system reader defeats permissions, * we don't even look at the aclspec. */ perm |= RGW_OP_TYPE_READ; } } } return perm; }; } TokenEngine::result_t TokenEngine::authenticate(const DoutPrefixProvider* dpp, const std::string& token, const std::string& service_token, const req_state* const s) const { bool allow_expired = false; boost::optional<TokenEngine::token_envelope_t> t; /* This will be initialized on the first call to this method. In C++11 it's * also thread-safe. */ static const struct RolesCacher { explicit RolesCacher(CephContext* const cct) { get_str_vec(cct->_conf->rgw_keystone_accepted_roles, plain); get_str_vec(cct->_conf->rgw_keystone_accepted_admin_roles, admin); get_str_vec(cct->_conf->rgw_keystone_accepted_reader_roles, reader); /* Let's suppose that having an admin role implies also a regular one. */ plain.insert(std::end(plain), std::begin(admin), std::end(admin)); } std::vector<std::string> plain; std::vector<std::string> admin; std::vector<std::string> reader; } roles(cct); static const struct ServiceTokenRolesCacher { explicit ServiceTokenRolesCacher(CephContext* const cct) { get_str_vec(cct->_conf->rgw_keystone_service_token_accepted_roles, plain); } std::vector<std::string> plain; } service_token_roles(cct); if (! is_applicable(token)) { return result_t::deny(); } /* Token ID is a legacy of supporting the service-side validation * of PKI/PKIz token type which are already-removed-in-OpenStack. * The idea was to bury in cache only a short hash instead of few * kilobytes. RadosGW doesn't do the local validation anymore. */ const auto& token_id = rgw_get_token_id(token); ldpp_dout(dpp, 20) << "token_id=" << token_id << dendl; /* Check cache first. */ t = token_cache.find(token_id); if (t) { ldpp_dout(dpp, 20) << "cached token.project.id=" << t->get_project_id() << dendl; auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(*t), get_creds_info(*t)); return result_t::grant(std::move(apl)); } /* We have a service token and a token so we verify the service * token and if it's invalid the request is invalid. If it's valid * we allow an expired token to be used when doing lookup in Keystone. * We never get to this if the token is in the cache. */ if (g_conf()->rgw_keystone_service_token_enabled && ! service_token.empty()) { boost::optional<TokenEngine::token_envelope_t> st; const auto& service_token_id = rgw_get_token_id(service_token); ldpp_dout(dpp, 20) << "service_token_id=" << service_token_id << dendl; /* Check cache for service token first. */ st = token_cache.find_service(service_token_id); if (st) { ldpp_dout(dpp, 20) << "cached service_token.project.id=" << st->get_project_id() << dendl; /* We found the service token in the cache so we allow using an expired * token for this request. */ allow_expired = true; ldpp_dout(dpp, 20) << "allowing expired tokens because service_token_id=" << service_token_id << " was found in cache" << dendl; } else { /* Service token was not found in cache. Go to Keystone for validating * the token. The allow_expired here must always be false. */ ceph_assert(allow_expired == false); st = get_from_keystone(dpp, service_token, allow_expired); if (! st) { return result_t::deny(-EACCES); } /* Verify expiration of service token. */ if (st->expired()) { ldpp_dout(dpp, 0) << "got expired service token: " << st->get_project_name() << ":" << st->get_user_name() << " expired " << st->get_expires() << dendl; return result_t::deny(-EPERM); } /* Check for necessary roles for service token. */ for (const auto& role : service_token_roles.plain) { if (st->has_role(role) == true) { /* Service token is valid so we allow using an expired token for * this request. */ ldpp_dout(dpp, 20) << "allowing expired tokens because service_token_id=" << service_token_id << " is valid, role: " << role << dendl; allow_expired = true; token_cache.add_service(service_token_id, *st); break; } } if (!allow_expired) { ldpp_dout(dpp, 0) << "service token user does not hold a matching role; required roles: " << g_conf()->rgw_keystone_service_token_accepted_roles << dendl; return result_t::deny(-EPERM); } } } /* Token not in cache. Go to the Keystone for validation. This happens even * for the legacy PKI/PKIz token types. That's it, after the PKI/PKIz * RadosGW-side validation has been removed, we always ask Keystone. */ t = get_from_keystone(dpp, token, allow_expired); if (! t) { return result_t::deny(-EACCES); } t->update_roles(roles.admin, roles.reader); /* Verify expiration. */ if (t->expired()) { if (allow_expired) { ldpp_dout(dpp, 20) << "allowing expired token: " << t->get_project_name() << ":" << t->get_user_name() << " expired: " << t->get_expires() << " because of valid service token" << dendl; } else { ldpp_dout(dpp, 0) << "got expired token: " << t->get_project_name() << ":" << t->get_user_name() << " expired: " << t->get_expires() << dendl; return result_t::deny(-EPERM); } } /* Check for necessary roles. */ for (const auto& role : roles.plain) { if (t->has_role(role) == true) { /* If this token was an allowed expired token because we got a * service token we need to update the expiration before we cache it. */ if (allow_expired) { time_t now = ceph_clock_now().sec(); time_t new_expires = now + g_conf()->rgw_keystone_expired_token_cache_expiration; ldpp_dout(dpp, 20) << "updating expiration of allowed expired token" << " from old " << t->get_expires() << " to now " << now << " + " << g_conf()->rgw_keystone_expired_token_cache_expiration << " secs = " << new_expires << dendl; t->set_expires(new_expires); } ldpp_dout(dpp, 0) << "validated token: " << t->get_project_name() << ":" << t->get_user_name() << " expires: " << t->get_expires() << dendl; token_cache.add(token_id, *t); auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(*t), get_creds_info(*t)); return result_t::grant(std::move(apl)); } } ldpp_dout(dpp, 0) << "user does not hold a matching role; required roles: " << g_conf()->rgw_keystone_accepted_roles << dendl; return result_t::deny(-EPERM); } /* * Try to validate S3 auth against keystone s3token interface */ std::pair<boost::optional<rgw::keystone::TokenEnvelope>, int> EC2Engine::get_from_keystone(const DoutPrefixProvider* dpp, const std::string_view& access_key_id, const std::string& string_to_sign, const std::string_view& signature) const { /* prepare keystone url */ std::string keystone_url = config.get_endpoint_url(); if (keystone_url.empty()) { throw -EINVAL; } const auto api_version = config.get_api_version(); if (api_version == rgw::keystone::ApiVersion::VER_3) { keystone_url.append("v3/s3tokens"); } else { keystone_url.append("v2.0/s3tokens"); } /* get authentication token for Keystone. */ std::string admin_token; int ret = rgw::keystone::Service::get_admin_token(dpp, cct, token_cache, config, admin_token); if (ret < 0) { ldpp_dout(dpp, 2) << "s3 keystone: cannot get token for keystone access" << dendl; throw ret; } using RGWValidateKeystoneToken = rgw::keystone::Service::RGWValidateKeystoneToken; /* The container for plain response obtained from Keystone. It will be * parsed token_envelope_t::parse method. */ ceph::bufferlist token_body_bl; RGWValidateKeystoneToken validate(cct, "POST", keystone_url, &token_body_bl); /* set required headers for keystone request */ validate.append_header("X-Auth-Token", admin_token); validate.append_header("Content-Type", "application/json"); /* check if we want to verify keystone's ssl certs */ validate.set_verify_ssl(cct->_conf->rgw_keystone_verify_ssl); /* create json credentials request body */ JSONFormatter credentials(false); credentials.open_object_section(""); credentials.open_object_section("credentials"); credentials.dump_string("access", sview2cstr(access_key_id).data()); credentials.dump_string("token", rgw::to_base64(string_to_sign)); credentials.dump_string("signature", sview2cstr(signature).data()); credentials.close_section(); credentials.close_section(); std::stringstream os; credentials.flush(os); validate.set_post_data(os.str()); validate.set_send_length(os.str().length()); /* send request */ ret = validate.process(null_yield); if (ret < 0) { ldpp_dout(dpp, 2) << "s3 keystone: token validation ERROR: " << token_body_bl.c_str() << dendl; throw ret; } /* if the supplied signature is wrong, we will get 401 from Keystone */ if (validate.get_http_status() == decltype(validate)::HTTP_STATUS_UNAUTHORIZED) { return std::make_pair(boost::none, -ERR_SIGNATURE_NO_MATCH); } else if (validate.get_http_status() == decltype(validate)::HTTP_STATUS_NOTFOUND) { return std::make_pair(boost::none, -ERR_INVALID_ACCESS_KEY); } /* now parse response */ rgw::keystone::TokenEnvelope token_envelope; ret = token_envelope.parse(dpp, cct, std::string(), token_body_bl, api_version); if (ret < 0) { ldpp_dout(dpp, 2) << "s3 keystone: token parsing failed, ret=0" << ret << dendl; throw ret; } return std::make_pair(std::move(token_envelope), 0); } std::pair<boost::optional<std::string>, int> EC2Engine::get_secret_from_keystone(const DoutPrefixProvider* dpp, const std::string& user_id, const std::string_view& access_key_id) const { /* Fetch from /users/{USER_ID}/credentials/OS-EC2/{ACCESS_KEY_ID} */ /* Should return json with response key "credential" which contains entry "secret"*/ /* prepare keystone url */ std::string keystone_url = config.get_endpoint_url(); if (keystone_url.empty()) { return make_pair(boost::none, -EINVAL); } const auto api_version = config.get_api_version(); if (api_version == rgw::keystone::ApiVersion::VER_3) { keystone_url.append("v3/"); } else { keystone_url.append("v2.0/"); } keystone_url.append("users/"); keystone_url.append(user_id); keystone_url.append("/credentials/OS-EC2/"); keystone_url.append(std::string(access_key_id)); /* get authentication token for Keystone. */ std::string admin_token; int ret = rgw::keystone::Service::get_admin_token(dpp, cct, token_cache, config, admin_token); if (ret < 0) { ldpp_dout(dpp, 2) << "s3 keystone: cannot get token for keystone access" << dendl; return make_pair(boost::none, ret); } using RGWGetAccessSecret = rgw::keystone::Service::RGWKeystoneHTTPTransceiver; /* The container for plain response obtained from Keystone.*/ ceph::bufferlist token_body_bl; RGWGetAccessSecret secret(cct, "GET", keystone_url, &token_body_bl); /* set required headers for keystone request */ secret.append_header("X-Auth-Token", admin_token); /* check if we want to verify keystone's ssl certs */ secret.set_verify_ssl(cct->_conf->rgw_keystone_verify_ssl); /* send request */ ret = secret.process(null_yield); if (ret < 0) { ldpp_dout(dpp, 2) << "s3 keystone: secret fetching error: " << token_body_bl.c_str() << dendl; return make_pair(boost::none, ret); } /* if the supplied signature is wrong, we will get 401 from Keystone */ if (secret.get_http_status() == decltype(secret)::HTTP_STATUS_NOTFOUND) { return make_pair(boost::none, -EINVAL); } /* now parse response */ JSONParser parser; if (! parser.parse(token_body_bl.c_str(), token_body_bl.length())) { ldpp_dout(dpp, 0) << "Keystone credential parse error: malformed json" << dendl; return make_pair(boost::none, -EINVAL); } JSONObjIter credential_iter = parser.find_first("credential"); std::string secret_string; try { if (!credential_iter.end()) { JSONDecoder::decode_json("secret", secret_string, *credential_iter, true); } else { ldpp_dout(dpp, 0) << "Keystone credential not present in return from server" << dendl; return make_pair(boost::none, -EINVAL); } } catch (const JSONDecoder::err& err) { ldpp_dout(dpp, 0) << "Keystone credential parse error: " << err.what() << dendl; return make_pair(boost::none, -EINVAL); } return make_pair(secret_string, 0); } /* * Try to get a token for S3 authentication, using a secret cache if available */ auto EC2Engine::get_access_token(const DoutPrefixProvider* dpp, const std::string_view& access_key_id, const std::string& string_to_sign, const std::string_view& signature, const signature_factory_t& signature_factory) const -> access_token_result { using server_signature_t = VersionAbstractor::server_signature_t; boost::optional<rgw::keystone::TokenEnvelope> token; boost::optional<std::string> secret; int failure_reason; /* Get a token from the cache if one has already been stored */ boost::optional<boost::tuple<rgw::keystone::TokenEnvelope, std::string>> t = secret_cache.find(std::string(access_key_id)); /* Check that credentials can correctly be used to sign data */ if (t) { std::string sig(signature); server_signature_t server_signature = signature_factory(cct, t->get<1>(), string_to_sign); if (sig.compare(server_signature) == 0) { return {t->get<0>(), t->get<1>(), 0}; } else { ldpp_dout(dpp, 0) << "Secret string does not correctly sign payload, cache miss" << dendl; } } else { ldpp_dout(dpp, 0) << "No stored secret string, cache miss" << dendl; } /* No cached token, token expired, or secret invalid: fall back to keystone */ std::tie(token, failure_reason) = get_from_keystone(dpp, access_key_id, string_to_sign, signature); if (token) { /* Fetch secret from keystone for the access_key_id */ std::tie(secret, failure_reason) = get_secret_from_keystone(dpp, token->get_user_id(), access_key_id); if (secret) { /* Add token, secret pair to cache, and set timeout */ secret_cache.add(std::string(access_key_id), *token, *secret); } } return {token, secret, failure_reason}; } EC2Engine::acl_strategy_t EC2Engine::get_acl_strategy(const EC2Engine::token_envelope_t&) const { /* This is based on the assumption that the default acl strategy in * get_perms_from_aclspec, will take care. Extra acl spec is not required. */ return nullptr; } EC2Engine::auth_info_t EC2Engine::get_creds_info(const EC2Engine::token_envelope_t& token, const std::vector<std::string>& admin_roles, const std::string& access_key_id ) const noexcept { using acct_privilege_t = \ rgw::auth::RemoteApplier::AuthInfo::acct_privilege_t; /* Check whether the user has an admin status. */ acct_privilege_t level = acct_privilege_t::IS_PLAIN_ACCT; for (const auto& admin_role : admin_roles) { if (token.has_role(admin_role)) { level = acct_privilege_t::IS_ADMIN_ACCT; break; } } return auth_info_t { /* Suggested account name for the authenticated user. */ rgw_user(token.get_project_id()), /* User's display name (aka real name). */ token.get_project_name(), /* Keystone doesn't support RGW's subuser concept, so we cannot cut down * the access rights through the perm_mask. At least at this layer. */ RGW_PERM_FULL_CONTROL, level, access_key_id, rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER, TYPE_KEYSTONE }; } rgw::auth::Engine::result_t EC2Engine::authenticate( const DoutPrefixProvider* dpp, const std::string_view& access_key_id, const std::string_view& signature, const std::string_view& session_token, const string_to_sign_t& string_to_sign, const signature_factory_t& signature_factory, const completer_factory_t& completer_factory, /* Passthorugh only! */ const req_state* s, optional_yield y) const { /* This will be initialized on the first call to this method. In C++11 it's * also thread-safe. */ static const struct RolesCacher { explicit RolesCacher(CephContext* const cct) { get_str_vec(cct->_conf->rgw_keystone_accepted_roles, plain); get_str_vec(cct->_conf->rgw_keystone_accepted_admin_roles, admin); /* Let's suppose that having an admin role implies also a regular one. */ plain.insert(std::end(plain), std::begin(admin), std::end(admin)); } std::vector<std::string> plain; std::vector<std::string> admin; } accepted_roles(cct); auto [t, secret_key, failure_reason] = get_access_token(dpp, access_key_id, string_to_sign, signature, signature_factory); if (! t) { return result_t::deny(failure_reason); } /* Verify expiration. */ if (t->expired()) { ldpp_dout(dpp, 0) << "got expired token: " << t->get_project_name() << ":" << t->get_user_name() << " expired: " << t->get_expires() << dendl; return result_t::deny(); } /* check if we have a valid role */ bool found = false; for (const auto& role : accepted_roles.plain) { if (t->has_role(role) == true) { found = true; break; } } if (! found) { ldpp_dout(dpp, 5) << "s3 keystone: user does not hold a matching role;" " required roles: " << cct->_conf->rgw_keystone_accepted_roles << dendl; return result_t::deny(); } else { /* everything seems fine, continue with this user */ ldpp_dout(dpp, 5) << "s3 keystone: validated token: " << t->get_project_name() << ":" << t->get_user_name() << " expires: " << t->get_expires() << dendl; auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(*t), get_creds_info(*t, accepted_roles.admin, std::string(access_key_id))); return result_t::grant(std::move(apl), completer_factory(secret_key)); } } bool SecretCache::find(const std::string& token_id, SecretCache::token_envelope_t& token, std::string &secret) { std::lock_guard<std::mutex> l(lock); map<std::string, secret_entry>::iterator iter = secrets.find(token_id); if (iter == secrets.end()) { return false; } secret_entry& entry = iter->second; secrets_lru.erase(entry.lru_iter); const utime_t now = ceph_clock_now(); if (entry.token.expired() || now > entry.expires) { secrets.erase(iter); return false; } token = entry.token; secret = entry.secret; secrets_lru.push_front(token_id); entry.lru_iter = secrets_lru.begin(); return true; } void SecretCache::add(const std::string& token_id, const SecretCache::token_envelope_t& token, const std::string& secret) { std::lock_guard<std::mutex> l(lock); map<string, secret_entry>::iterator iter = secrets.find(token_id); if (iter != secrets.end()) { secret_entry& e = iter->second; secrets_lru.erase(e.lru_iter); } const utime_t now = ceph_clock_now(); secrets_lru.push_front(token_id); secret_entry& entry = secrets[token_id]; entry.token = token; entry.secret = secret; entry.expires = now + s3_token_expiry_length; entry.lru_iter = secrets_lru.begin(); while (secrets_lru.size() > max) { list<string>::reverse_iterator riter = secrets_lru.rbegin(); iter = secrets.find(*riter); assert(iter != secrets.end()); secrets.erase(iter); secrets_lru.pop_back(); } } }; /* namespace keystone */ }; /* namespace auth */ }; /* namespace rgw */
27,011
33.944373
125
cc
null
ceph-main/src/rgw/rgw_auth_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 <string_view> #include <utility> #include <boost/optional.hpp> #include "rgw_auth.h" #include "rgw_rest_s3.h" #include "rgw_common.h" #include "rgw_keystone.h" namespace rgw { namespace auth { namespace keystone { /* Dedicated namespace for Keystone-related auth engines. We need it because * Keystone offers three different authentication mechanisms (token, EC2 and * regular user/pass). RadosGW actually does support the first two. */ class TokenEngine : public rgw::auth::Engine { CephContext* const cct; using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t; using auth_info_t = rgw::auth::RemoteApplier::AuthInfo; using result_t = rgw::auth::Engine::result_t; using token_envelope_t = rgw::keystone::TokenEnvelope; const rgw::auth::TokenExtractor* const auth_token_extractor; const rgw::auth::TokenExtractor* const service_token_extractor; const rgw::auth::RemoteApplier::Factory* const apl_factory; rgw::keystone::Config& config; rgw::keystone::TokenCache& token_cache; /* Helper methods. */ bool is_applicable(const std::string& token) const noexcept; boost::optional<token_envelope_t> get_from_keystone(const DoutPrefixProvider* dpp, const std::string& token, bool allow_expired) const; acl_strategy_t get_acl_strategy(const token_envelope_t& token) const; auth_info_t get_creds_info(const token_envelope_t& token) const noexcept; result_t authenticate(const DoutPrefixProvider* dpp, const std::string& token, const std::string& service_token, const req_state* s) const; public: TokenEngine(CephContext* const cct, const rgw::auth::TokenExtractor* const auth_token_extractor, const rgw::auth::TokenExtractor* const service_token_extractor, const rgw::auth::RemoteApplier::Factory* const apl_factory, rgw::keystone::Config& config, rgw::keystone::TokenCache& token_cache) : cct(cct), auth_token_extractor(auth_token_extractor), service_token_extractor(service_token_extractor), apl_factory(apl_factory), config(config), token_cache(token_cache) { } const char* get_name() const noexcept override { return "rgw::auth::keystone::TokenEngine"; } result_t authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const override { return authenticate(dpp, auth_token_extractor->get_token(s), service_token_extractor->get_token(s), s); } }; /* class TokenEngine */ class SecretCache { using token_envelope_t = rgw::keystone::TokenEnvelope; struct secret_entry { token_envelope_t token; std::string secret; utime_t expires; std::list<std::string>::iterator lru_iter; }; const boost::intrusive_ptr<CephContext> cct; std::map<std::string, secret_entry> secrets; std::list<std::string> secrets_lru; std::mutex lock; const size_t max; const utime_t s3_token_expiry_length; SecretCache() : cct(g_ceph_context), lock(), max(cct->_conf->rgw_keystone_token_cache_size), s3_token_expiry_length(300, 0) { } ~SecretCache() {} public: SecretCache(const SecretCache&) = delete; void operator=(const SecretCache&) = delete; static SecretCache& get_instance() { /* In C++11 this is thread safe. */ static SecretCache instance; return instance; } bool find(const std::string& token_id, token_envelope_t& token, std::string& secret); boost::optional<boost::tuple<token_envelope_t, std::string>> find(const std::string& token_id) { token_envelope_t token_envlp; std::string secret; if (find(token_id, token_envlp, secret)) { return boost::make_tuple(token_envlp, secret); } return boost::none; } void add(const std::string& token_id, const token_envelope_t& token, const std::string& secret); }; /* class SecretCache */ class EC2Engine : public rgw::auth::s3::AWSEngine { using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t; using auth_info_t = rgw::auth::RemoteApplier::AuthInfo; using result_t = rgw::auth::Engine::result_t; using token_envelope_t = rgw::keystone::TokenEnvelope; const rgw::auth::RemoteApplier::Factory* const apl_factory; rgw::keystone::Config& config; rgw::keystone::TokenCache& token_cache; rgw::auth::keystone::SecretCache& secret_cache; /* Helper methods. */ acl_strategy_t get_acl_strategy(const token_envelope_t& token) const; auth_info_t get_creds_info(const token_envelope_t& token, const std::vector<std::string>& admin_roles, const std::string& access_key_id ) const noexcept; std::pair<boost::optional<token_envelope_t>, int> get_from_keystone(const DoutPrefixProvider* dpp, const std::string_view& access_key_id, const std::string& string_to_sign, const std::string_view& signature) const; struct access_token_result { boost::optional<token_envelope_t> token; boost::optional<std::string> secret_key; int failure_reason = 0; }; access_token_result get_access_token(const DoutPrefixProvider* dpp, const std::string_view& access_key_id, const std::string& string_to_sign, const std::string_view& signature, const signature_factory_t& signature_factory) const; result_t authenticate(const DoutPrefixProvider* dpp, const std::string_view& access_key_id, const std::string_view& signature, const std::string_view& session_token, const string_to_sign_t& string_to_sign, const signature_factory_t& signature_factory, const completer_factory_t& completer_factory, const req_state* s, optional_yield y) const override; std::pair<boost::optional<std::string>, int> get_secret_from_keystone(const DoutPrefixProvider* dpp, const std::string& user_id, const std::string_view& access_key_id) const; public: EC2Engine(CephContext* const cct, const rgw::auth::s3::AWSEngine::VersionAbstractor* const ver_abstractor, const rgw::auth::RemoteApplier::Factory* const apl_factory, rgw::keystone::Config& config, /* The token cache is used ONLY for the retrieving admin token. * Due to the architecture of AWS Auth S3 credentials cannot be * cached at all. */ rgw::keystone::TokenCache& token_cache, rgw::auth::keystone::SecretCache& secret_cache) : AWSEngine(cct, *ver_abstractor), apl_factory(apl_factory), config(config), token_cache(token_cache), secret_cache(secret_cache) { } using AWSEngine::authenticate; const char* get_name() const noexcept override { return "rgw::auth::keystone::EC2Engine"; } }; /* class EC2Engine */ }; /* namespace keystone */ }; /* namespace auth */ }; /* namespace rgw */
7,368
35.661692
117
h
null
ceph-main/src/rgw/rgw_auth_registry.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <functional> #include <memory> #include <ostream> #include <type_traits> #include <utility> #include "rgw_auth.h" #include "rgw_auth_s3.h" #include "rgw_swift_auth.h" #include "rgw_rest_sts.h" namespace rgw { namespace auth { /* A class aggregating the knowledge about all Strategies in RadosGW. It is * responsible for handling the dynamic reconfiguration on e.g. realm update. */ class StrategyRegistry { template <class AbstractorT, bool AllowAnonAccessT = false> using s3_strategy_t = \ rgw::auth::s3::AWSAuthStrategy<AbstractorT, AllowAnonAccessT>; struct s3_main_strategy_t : public Strategy { using s3_main_strategy_plain_t = \ s3_strategy_t<rgw::auth::s3::AWSGeneralAbstractor, true>; using s3_main_strategy_boto2_t = \ s3_strategy_t<rgw::auth::s3::AWSGeneralBoto2Abstractor>; s3_main_strategy_plain_t s3_main_strategy_plain; s3_main_strategy_boto2_t s3_main_strategy_boto2; s3_main_strategy_t(CephContext* const cct, const ImplicitTenants& implicit_tenant_context, rgw::sal::Driver* driver) : s3_main_strategy_plain(cct, implicit_tenant_context, driver), s3_main_strategy_boto2(cct, implicit_tenant_context, driver) { add_engine(Strategy::Control::SUFFICIENT, s3_main_strategy_plain); add_engine(Strategy::Control::FALLBACK, s3_main_strategy_boto2); } const char* get_name() const noexcept override { return "rgw::auth::StrategyRegistry::s3_main_strategy_t"; } } s3_main_strategy; using s3_post_strategy_t = \ s3_strategy_t<rgw::auth::s3::AWSBrowserUploadAbstractor>; s3_post_strategy_t s3_post_strategy; rgw::auth::swift::DefaultStrategy swift_strategy; rgw::auth::sts::DefaultStrategy sts_strategy; public: StrategyRegistry(CephContext* const cct, const ImplicitTenants& implicit_tenant_context, rgw::sal::Driver* driver) : s3_main_strategy(cct, implicit_tenant_context, driver), s3_post_strategy(cct, implicit_tenant_context, driver), swift_strategy(cct, implicit_tenant_context, driver), sts_strategy(cct, implicit_tenant_context, driver) { } const s3_main_strategy_t& get_s3_main() const { return s3_main_strategy; } const s3_post_strategy_t& get_s3_post() const { return s3_post_strategy; } const rgw::auth::swift::DefaultStrategy& get_swift() const { return swift_strategy; } const rgw::auth::sts::DefaultStrategy& get_sts() const { return sts_strategy; } static std::unique_ptr<StrategyRegistry> create(CephContext* const cct, const ImplicitTenants& implicit_tenant_context, rgw::sal::Driver* driver) { return std::make_unique<StrategyRegistry>(cct, implicit_tenant_context, driver); } }; } /* namespace auth */ } /* namespace rgw */ using rgw_auth_registry_t = rgw::auth::StrategyRegistry; using rgw_auth_registry_ptr_t = std::unique_ptr<rgw_auth_registry_t>;
3,080
30.438776
84
h
null
ceph-main/src/rgw/rgw_auth_s3.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <algorithm> #include <map> #include <iterator> #include <string> #include <string_view> #include <vector> #include "common/armor.h" #include "common/utf8.h" #include "rgw_rest_s3.h" #include "rgw_auth_s3.h" #include "rgw_common.h" #include "rgw_client_io.h" #include "rgw_rest.h" #include "rgw_crypt_sanitize.h" #include <boost/container/small_vector.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/trim_all.hpp> #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; static const auto signed_subresources = { "acl", "cors", "delete", "encryption", "lifecycle", "location", "logging", "notification", "partNumber", "policy", "policyStatus", "publicAccessBlock", "requestPayment", "response-cache-control", "response-content-disposition", "response-content-encoding", "response-content-language", "response-content-type", "response-expires", "tagging", "torrent", "uploadId", "uploads", "versionId", "versioning", "versions", "website", "object-lock" }; /* * ?get the canonical amazon-style header for something? */ static std::string get_canon_amz_hdr(const meta_map_t& meta_map) { std::string dest; for (const auto& kv : meta_map) { dest.append(kv.first); dest.append(":"); dest.append(kv.second); dest.append("\n"); } return dest; } /* * ?get the canonical representation of the object's location */ static std::string get_canon_resource(const DoutPrefixProvider *dpp, const char* const request_uri, const std::map<std::string, std::string>& sub_resources) { std::string dest; if (request_uri) { dest.append(request_uri); } bool initial = true; for (const auto& subresource : signed_subresources) { const auto iter = sub_resources.find(subresource); if (iter == std::end(sub_resources)) { continue; } if (initial) { dest.append("?"); initial = false; } else { dest.append("&"); } dest.append(iter->first); if (! iter->second.empty()) { dest.append("="); dest.append(iter->second); } } ldpp_dout(dpp, 10) << "get_canon_resource(): dest=" << dest << dendl; return dest; } /* * get the header authentication information required to * compute a request's signature */ void rgw_create_s3_canonical_header( const DoutPrefixProvider *dpp, const char* const method, const char* const content_md5, const char* const content_type, const char* const date, const meta_map_t& meta_map, const meta_map_t& qs_map, const char* const request_uri, const std::map<std::string, std::string>& sub_resources, std::string& dest_str) { std::string dest; if (method) { dest = method; } dest.append("\n"); if (content_md5) { dest.append(content_md5); } dest.append("\n"); if (content_type) { dest.append(content_type); } dest.append("\n"); if (date) { dest.append(date); } dest.append("\n"); dest.append(get_canon_amz_hdr(meta_map)); dest.append(get_canon_amz_hdr(qs_map)); dest.append(get_canon_resource(dpp, request_uri, sub_resources)); dest_str = dest; } static inline bool is_base64_for_content_md5(unsigned char c) { return (isalnum(c) || isspace(c) || (c == '+') || (c == '/') || (c == '=')); } static inline void get_v2_qs_map(const req_info& info, meta_map_t& qs_map) { const auto& params = const_cast<RGWHTTPArgs&>(info.args).get_params(); for (const auto& elt : params) { std::string k = boost::algorithm::to_lower_copy(elt.first); if (k.find("x-amz-meta-") == /* offset */ 0) { rgw_add_amz_meta_header(qs_map, k, elt.second); } if (k == "x-amz-security-token") { qs_map[k] = elt.second; } } } /* * get the header authentication information required to * compute a request's signature */ bool rgw_create_s3_canonical_header(const DoutPrefixProvider *dpp, const req_info& info, utime_t* const header_time, std::string& dest, const bool qsr) { const char* const content_md5 = info.env->get("HTTP_CONTENT_MD5"); if (content_md5) { for (const char *p = content_md5; *p; p++) { if (!is_base64_for_content_md5(*p)) { ldpp_dout(dpp, 0) << "NOTICE: bad content-md5 provided (not base64)," << " aborting request p=" << *p << " " << (int)*p << dendl; return false; } } } const char *content_type = info.env->get("CONTENT_TYPE"); std::string date; meta_map_t qs_map; if (qsr) { get_v2_qs_map(info, qs_map); // handle qs metadata date = info.args.get("Expires"); } else { const char *str = info.env->get("HTTP_X_AMZ_DATE"); const char *req_date = str; if (str == NULL) { req_date = info.env->get("HTTP_DATE"); if (!req_date) { ldpp_dout(dpp, 0) << "NOTICE: missing date for auth header" << dendl; return false; } date = req_date; } if (header_time) { struct tm t; uint32_t ns = 0; if (!parse_rfc2616(req_date, &t) && !parse_iso8601(req_date, &t, &ns, false)) { ldpp_dout(dpp, 0) << "NOTICE: failed to parse date <" << req_date << "> for auth header" << dendl; return false; } if (t.tm_year < 70) { ldpp_dout(dpp, 0) << "NOTICE: bad date (predates epoch): " << req_date << dendl; return false; } *header_time = utime_t(internal_timegm(&t), 0); *header_time -= t.tm_gmtoff; } } const auto& meta_map = info.x_meta_map; const auto& sub_resources = info.args.get_sub_resources(); std::string request_uri; if (info.effective_uri.empty()) { request_uri = info.request_uri; } else { request_uri = info.effective_uri; } rgw_create_s3_canonical_header(dpp, info.method, content_md5, content_type, date.c_str(), meta_map, qs_map, request_uri.c_str(), sub_resources, dest); return true; } namespace rgw::auth::s3 { bool is_time_skew_ok(time_t t) { auto req_tp = ceph::coarse_real_clock::from_time_t(t); auto cur_tp = ceph::coarse_real_clock::now(); if (std::chrono::abs(cur_tp - req_tp) > RGW_AUTH_GRACE) { dout(10) << "NOTICE: request time skew too big." << dendl; using ceph::operator<<; dout(10) << "req_tp=" << req_tp << ", cur_tp=" << cur_tp << dendl; return false; } return true; } static inline int parse_v4_query_string(const req_info& info, /* in */ std::string_view& credential, /* out */ std::string_view& signedheaders, /* out */ std::string_view& signature, /* out */ std::string_view& date, /* out */ std::string_view& sessiontoken) /* out */ { /* auth ships with req params ... */ /* look for required params */ credential = info.args.get("x-amz-credential"); if (credential.size() == 0) { return -EPERM; } date = info.args.get("x-amz-date"); struct tm date_t; if (!parse_iso8601(sview2cstr(date).data(), &date_t, nullptr, false)) { return -EPERM; } std::string_view expires = info.args.get("x-amz-expires"); if (expires.empty()) { return -EPERM; } /* X-Amz-Expires provides the time period, in seconds, for which the generated presigned URL is valid. The minimum value you can set is 1, and the maximum is 604800 (seven days) */ time_t exp = atoll(expires.data()); if ((exp < 1) || (exp > 7*24*60*60)) { dout(10) << "NOTICE: exp out of range, exp = " << exp << dendl; return -EPERM; } /* handle expiration in epoch time */ uint64_t req_sec = (uint64_t)internal_timegm(&date_t); uint64_t now = ceph_clock_now(); if (now >= req_sec + exp) { dout(10) << "NOTICE: now = " << now << ", req_sec = " << req_sec << ", exp = " << exp << dendl; return -EPERM; } signedheaders = info.args.get("x-amz-signedheaders"); if (signedheaders.size() == 0) { return -EPERM; } signature = info.args.get("x-amz-signature"); if (signature.size() == 0) { return -EPERM; } if (info.args.exists("x-amz-security-token")) { sessiontoken = info.args.get("x-amz-security-token"); if (sessiontoken.size() == 0) { return -EPERM; } } return 0; } static bool get_next_token(const std::string_view& s, size_t& pos, const char* const delims, std::string_view& token) { const size_t start = s.find_first_not_of(delims, pos); if (start == std::string_view::npos) { pos = s.size(); return false; } size_t end = s.find_first_of(delims, start); if (end != std::string_view::npos) pos = end + 1; else { pos = end = s.size(); } token = s.substr(start, end - start); return true; } template<std::size_t ExpectedStrNum> boost::container::small_vector<std::string_view, ExpectedStrNum> get_str_vec(const std::string_view& str, const char* const delims) { boost::container::small_vector<std::string_view, ExpectedStrNum> str_vec; size_t pos = 0; std::string_view token; while (pos < str.size()) { if (get_next_token(str, pos, delims, token)) { if (token.size() > 0) { str_vec.push_back(token); } } } return str_vec; } template<std::size_t ExpectedStrNum> boost::container::small_vector<std::string_view, ExpectedStrNum> get_str_vec(const std::string_view& str) { const char delims[] = ";,= \t"; return get_str_vec<ExpectedStrNum>(str, delims); } static inline int parse_v4_auth_header(const req_info& info, /* in */ std::string_view& credential, /* out */ std::string_view& signedheaders, /* out */ std::string_view& signature, /* out */ std::string_view& date, /* out */ std::string_view& sessiontoken, /* out */ const DoutPrefixProvider *dpp) { std::string_view input(info.env->get("HTTP_AUTHORIZATION", "")); try { input = input.substr(::strlen(AWS4_HMAC_SHA256_STR) + 1); } catch (std::out_of_range&) { /* We should never ever run into this situation as the presence of * AWS4_HMAC_SHA256_STR had been verified earlier. */ ldpp_dout(dpp, 10) << "credentials string is too short" << dendl; return -EINVAL; } std::map<std::string_view, std::string_view> kv; for (const auto& s : get_str_vec<4>(input, ",")) { const auto parsed_pair = parse_key_value(s); if (parsed_pair) { kv[parsed_pair->first] = parsed_pair->second; } else { ldpp_dout(dpp, 10) << "NOTICE: failed to parse auth header (s=" << s << ")" << dendl; return -EINVAL; } } static const std::array<std::string_view, 3> required_keys = { "Credential", "SignedHeaders", "Signature" }; /* Ensure that the presigned required keys are really there. */ for (const auto& k : required_keys) { if (kv.find(k) == std::end(kv)) { ldpp_dout(dpp, 10) << "NOTICE: auth header missing key: " << k << dendl; return -EINVAL; } } credential = kv["Credential"]; signedheaders = kv["SignedHeaders"]; signature = kv["Signature"]; /* sig hex str */ ldpp_dout(dpp, 10) << "v4 signature format = " << signature << dendl; /* ------------------------- handle x-amz-date header */ /* grab date */ const char *d = info.env->get("HTTP_X_AMZ_DATE"); struct tm t; if (unlikely(d == NULL)) { d = info.env->get("HTTP_DATE"); } if (!d || !parse_iso8601(d, &t, NULL, false)) { ldpp_dout(dpp, 10) << "error reading date via http_x_amz_date and http_date" << dendl; return -EACCES; } date = d; if (!is_time_skew_ok(internal_timegm(&t))) { return -ERR_REQUEST_TIME_SKEWED; } auto token = info.env->get_optional("HTTP_X_AMZ_SECURITY_TOKEN"); if (token) { sessiontoken = *token; } return 0; } bool is_non_s3_op(RGWOpType op_type) { if (op_type == RGW_STS_GET_SESSION_TOKEN || op_type == RGW_STS_ASSUME_ROLE || op_type == RGW_STS_ASSUME_ROLE_WEB_IDENTITY || op_type == RGW_OP_CREATE_ROLE || op_type == RGW_OP_DELETE_ROLE || op_type == RGW_OP_GET_ROLE || op_type == RGW_OP_MODIFY_ROLE_TRUST_POLICY || op_type == RGW_OP_LIST_ROLES || op_type == RGW_OP_PUT_ROLE_POLICY || op_type == RGW_OP_GET_ROLE_POLICY || op_type == RGW_OP_LIST_ROLE_POLICIES || op_type == RGW_OP_DELETE_ROLE_POLICY || op_type == RGW_OP_PUT_USER_POLICY || op_type == RGW_OP_GET_USER_POLICY || op_type == RGW_OP_LIST_USER_POLICIES || op_type == RGW_OP_DELETE_USER_POLICY || op_type == RGW_OP_CREATE_OIDC_PROVIDER || op_type == RGW_OP_DELETE_OIDC_PROVIDER || op_type == RGW_OP_GET_OIDC_PROVIDER || op_type == RGW_OP_LIST_OIDC_PROVIDERS || op_type == RGW_OP_PUBSUB_TOPIC_CREATE || op_type == RGW_OP_PUBSUB_TOPICS_LIST || op_type == RGW_OP_PUBSUB_TOPIC_GET || op_type == RGW_OP_PUBSUB_TOPIC_DELETE || op_type == RGW_OP_TAG_ROLE || op_type == RGW_OP_LIST_ROLE_TAGS || op_type == RGW_OP_UNTAG_ROLE || op_type == RGW_OP_UPDATE_ROLE) { return true; } return false; } int parse_v4_credentials(const req_info& info, /* in */ std::string_view& access_key_id, /* out */ std::string_view& credential_scope, /* out */ std::string_view& signedheaders, /* out */ std::string_view& signature, /* out */ std::string_view& date, /* out */ std::string_view& session_token, /* out */ const bool using_qs, /* in */ const DoutPrefixProvider *dpp) { std::string_view credential; int ret; if (using_qs) { ret = parse_v4_query_string(info, credential, signedheaders, signature, date, session_token); } else { ret = parse_v4_auth_header(info, credential, signedheaders, signature, date, session_token, dpp); } if (ret < 0) { return ret; } /* access_key/YYYYMMDD/region/service/aws4_request */ ldpp_dout(dpp, 10) << "v4 credential format = " << credential << dendl; if (std::count(credential.begin(), credential.end(), '/') != 4) { return -EINVAL; } /* credential must end with 'aws4_request' */ if (credential.find("aws4_request") == std::string::npos) { return -EINVAL; } /* grab access key id */ const size_t pos = credential.find("/"); access_key_id = credential.substr(0, pos); ldpp_dout(dpp, 10) << "access key id = " << access_key_id << dendl; /* grab credential scope */ credential_scope = credential.substr(pos + 1); ldpp_dout(dpp, 10) << "credential scope = " << credential_scope << dendl; return 0; } string gen_v4_scope(const ceph::real_time& timestamp, const string& region, const string& service) { auto sec = real_clock::to_time_t(timestamp); struct tm bt; gmtime_r(&sec, &bt); auto year = 1900 + bt.tm_year; auto mon = bt.tm_mon + 1; auto day = bt.tm_mday; return fmt::format(FMT_STRING("{:d}{:02d}{:02d}/{:s}/{:s}/aws4_request"), year, mon, day, region, service); } std::string get_v4_canonical_qs(const req_info& info, const bool using_qs) { const std::string *params = &info.request_params; std::string copy_params; if (params->empty()) { /* Optimize the typical flow. */ return std::string(); } if (params->find_first_of('+') != std::string::npos) { copy_params = *params; boost::replace_all(copy_params, "+", "%20"); params = &copy_params; } /* Handle case when query string exists. Step 3 described in: http://docs. * aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html */ std::map<std::string, std::string> canonical_qs_map; for (const auto& s : get_str_vec<5>(*params, "&")) { std::string_view key, val; const auto parsed_pair = parse_key_value(s); if (parsed_pair) { std::tie(key, val) = *parsed_pair; } else { /* Handling a parameter without any value (even the empty one). That's * it, we've encountered something like "this_param&other_param=val" * which is used by S3 for subresources. */ key = s; } if (using_qs && boost::iequals(key, "X-Amz-Signature")) { /* Preserving the original behaviour of get_v4_canonical_qs() here. */ continue; } // while awsv4 specs ask for all slashes to be encoded, s3 itself is relaxed // in its implementation allowing non-url-encoded slashes to be present in // presigned urls for instance canonical_qs_map[aws4_uri_recode(key, true)] = aws4_uri_recode(val, true); } /* Thanks to the early exist we have the guarantee that canonical_qs_map has * at least one element. */ auto iter = std::begin(canonical_qs_map); std::string canonical_qs; canonical_qs.append(iter->first) .append("=", ::strlen("=")) .append(iter->second); for (iter++; iter != std::end(canonical_qs_map); iter++) { canonical_qs.append("&", ::strlen("&")) .append(iter->first) .append("=", ::strlen("=")) .append(iter->second); } return canonical_qs; } static void add_v4_canonical_params_from_map(const map<string, string>& m, std::map<string, string> *result, bool is_non_s3_op) { for (auto& entry : m) { const auto& key = entry.first; if (key.empty() || (is_non_s3_op && key == "PayloadHash")) { continue; } (*result)[aws4_uri_recode(key, true)] = aws4_uri_recode(entry.second, true); } } std::string gen_v4_canonical_qs(const req_info& info, bool is_non_s3_op) { std::map<std::string, std::string> canonical_qs_map; add_v4_canonical_params_from_map(info.args.get_params(), &canonical_qs_map, is_non_s3_op); add_v4_canonical_params_from_map(info.args.get_sys_params(), &canonical_qs_map, false); if (canonical_qs_map.empty()) { return string(); } /* Thanks to the early exit we have the guarantee that canonical_qs_map has * at least one element. */ auto iter = std::begin(canonical_qs_map); std::string canonical_qs; canonical_qs.append(iter->first) .append("=", ::strlen("=")) .append(iter->second); for (iter++; iter != std::end(canonical_qs_map); iter++) { canonical_qs.append("&", ::strlen("&")) .append(iter->first) .append("=", ::strlen("=")) .append(iter->second); } return canonical_qs; } boost::optional<std::string> get_v4_canonical_headers(const req_info& info, const std::string_view& signedheaders, const bool using_qs, const bool force_boto2_compat) { std::map<std::string_view, std::string> canonical_hdrs_map; for (const auto& token : get_str_vec<5>(signedheaders, ";")) { /* TODO(rzarzynski): we'd like to switch to sstring here but it should * get push_back() and reserve() first. */ std::string token_env = "HTTP_"; token_env.reserve(token.length() + std::strlen("HTTP_") + 1); std::transform(std::begin(token), std::end(token), std::back_inserter(token_env), [](const int c) { return c == '-' ? '_' : c == '_' ? '-' : std::toupper(c); }); if (token_env == "HTTP_CONTENT_LENGTH") { token_env = "CONTENT_LENGTH"; } else if (token_env == "HTTP_CONTENT_TYPE") { token_env = "CONTENT_TYPE"; } const char* const t = info.env->get(token_env.c_str()); if (!t) { dout(10) << "warning env var not available " << token_env.c_str() << dendl; continue; } std::string token_value(t); if (token_env == "HTTP_CONTENT_MD5" && !std::all_of(std::begin(token_value), std::end(token_value), is_base64_for_content_md5)) { dout(0) << "NOTICE: bad content-md5 provided (not base64)" << ", aborting request" << dendl; return boost::none; } if (force_boto2_compat && using_qs && token == "host") { std::string_view port = info.env->get("SERVER_PORT", ""); std::string_view secure_port = info.env->get("SERVER_PORT_SECURE", ""); if (!secure_port.empty()) { if (secure_port != "443") token_value.append(":", std::strlen(":")) .append(secure_port.data(), secure_port.length()); } else if (!port.empty()) { if (port != "80") token_value.append(":", std::strlen(":")) .append(port.data(), port.length()); } } canonical_hdrs_map[token] = rgw_trim_whitespace(token_value); } std::string canonical_hdrs; for (const auto& header : canonical_hdrs_map) { const std::string_view& name = header.first; std::string value = header.second; boost::trim_all<std::string>(value); canonical_hdrs.append(name.data(), name.length()) .append(":", std::strlen(":")) .append(value) .append("\n", std::strlen("\n")); } return canonical_hdrs; } static void handle_header(const string& header, const string& val, std::map<std::string, std::string> *canonical_hdrs_map) { /* TODO(rzarzynski): we'd like to switch to sstring here but it should * get push_back() and reserve() first. */ std::string token; token.reserve(header.length()); if (header == "HTTP_CONTENT_LENGTH") { token = "content-length"; } else if (header == "HTTP_CONTENT_TYPE") { token = "content-type"; } else { auto start = std::begin(header); if (boost::algorithm::starts_with(header, "HTTP_")) { start += 5; /* len("HTTP_") */ } std::transform(start, std::end(header), std::back_inserter(token), [](const int c) { return c == '_' ? '-' : std::tolower(c); }); } (*canonical_hdrs_map)[token] = rgw_trim_whitespace(val); } std::string gen_v4_canonical_headers(const req_info& info, const map<string, string>& extra_headers, string *signed_hdrs) { std::map<std::string, std::string> canonical_hdrs_map; for (auto& entry : info.env->get_map()) { handle_header(entry.first, entry.second, &canonical_hdrs_map); } for (auto& entry : extra_headers) { handle_header(entry.first, entry.second, &canonical_hdrs_map); } std::string canonical_hdrs; signed_hdrs->clear(); for (const auto& header : canonical_hdrs_map) { const auto& name = header.first; std::string value = header.second; boost::trim_all<std::string>(value); if (!signed_hdrs->empty()) { signed_hdrs->append(";"); } signed_hdrs->append(name); canonical_hdrs.append(name.data(), name.length()) .append(":", std::strlen(":")) .append(value) .append("\n", std::strlen("\n")); } return canonical_hdrs; } /* * create canonical request for signature version 4 * * http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html */ sha256_digest_t get_v4_canon_req_hash(CephContext* cct, const std::string_view& http_verb, const std::string& canonical_uri, const std::string& canonical_qs, const std::string& canonical_hdrs, const std::string_view& signed_hdrs, const std::string_view& request_payload_hash, const DoutPrefixProvider *dpp) { ldpp_dout(dpp, 10) << "payload request hash = " << request_payload_hash << dendl; const auto canonical_req = string_join_reserve("\n", http_verb, canonical_uri, canonical_qs, canonical_hdrs, signed_hdrs, request_payload_hash); const auto canonical_req_hash = calc_hash_sha256(canonical_req); using sanitize = rgw::crypt_sanitize::log_content; ldpp_dout(dpp, 10) << "canonical request = " << sanitize{canonical_req} << dendl; ldpp_dout(dpp, 10) << "canonical request hash = " << canonical_req_hash << dendl; return canonical_req_hash; } /* * create string to sign for signature version 4 * * http://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html */ AWSEngine::VersionAbstractor::string_to_sign_t get_v4_string_to_sign(CephContext* const cct, const std::string_view& algorithm, const std::string_view& request_date, const std::string_view& credential_scope, const sha256_digest_t& canonreq_hash, const DoutPrefixProvider *dpp) { const auto hexed_cr_hash = canonreq_hash.to_str(); const std::string_view hexed_cr_hash_str(hexed_cr_hash); const auto string_to_sign = string_join_reserve("\n", algorithm, request_date, credential_scope, hexed_cr_hash_str); ldpp_dout(dpp, 10) << "string to sign = " << rgw::crypt_sanitize::log_content{string_to_sign} << dendl; return string_to_sign; } static inline std::tuple<std::string_view, /* date */ std::string_view, /* region */ std::string_view> /* service */ parse_cred_scope(std::string_view credential_scope) { /* date cred */ size_t pos = credential_scope.find("/"); const auto date_cs = credential_scope.substr(0, pos); credential_scope = credential_scope.substr(pos + 1); /* region cred */ pos = credential_scope.find("/"); const auto region_cs = credential_scope.substr(0, pos); credential_scope = credential_scope.substr(pos + 1); /* service cred */ pos = credential_scope.find("/"); const auto service_cs = credential_scope.substr(0, pos); return std::make_tuple(date_cs, region_cs, service_cs); } static inline std::vector<unsigned char> transform_secret_key(const std::string_view& secret_access_key) { /* TODO(rzarzynski): switch to constexpr when C++14 becomes available. */ static const std::initializer_list<unsigned char> AWS4 { 'A', 'W', 'S', '4' }; /* boost::container::small_vector might be used here if someone wants to * optimize out even more dynamic allocations. */ std::vector<unsigned char> secret_key_utf8; secret_key_utf8.reserve(AWS4.size() + secret_access_key.size()); secret_key_utf8.assign(AWS4); for (const auto c : secret_access_key) { std::array<unsigned char, MAX_UTF8_SZ> buf; const size_t n = encode_utf8(c, buf.data()); secret_key_utf8.insert(std::end(secret_key_utf8), std::begin(buf), std::begin(buf) + n); } return secret_key_utf8; } /* * calculate the SigningKey of AWS auth version 4 */ static sha256_digest_t get_v4_signing_key(CephContext* const cct, const std::string_view& credential_scope, const std::string_view& secret_access_key, const DoutPrefixProvider *dpp) { std::string_view date, region, service; std::tie(date, region, service) = parse_cred_scope(credential_scope); const auto utfed_sec_key = transform_secret_key(secret_access_key); const auto date_k = calc_hmac_sha256(utfed_sec_key, date); const auto region_k = calc_hmac_sha256(date_k, region); const auto service_k = calc_hmac_sha256(region_k, service); /* aws4_request */ const auto signing_key = calc_hmac_sha256(service_k, std::string_view("aws4_request")); ldpp_dout(dpp, 10) << "date_k = " << date_k << dendl; ldpp_dout(dpp, 10) << "region_k = " << region_k << dendl; ldpp_dout(dpp, 10) << "service_k = " << service_k << dendl; ldpp_dout(dpp, 10) << "signing_k = " << signing_key << dendl; return signing_key; } /* * calculate the AWS signature version 4 * * http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html * * srv_signature_t is an alias over Ceph's basic_sstring. We're using * it to keep everything within the stack boundaries instead of doing * dynamic allocations. */ AWSEngine::VersionAbstractor::server_signature_t get_v4_signature(const std::string_view& credential_scope, CephContext* const cct, const std::string_view& secret_key, const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign, const DoutPrefixProvider *dpp) { auto signing_key = get_v4_signing_key(cct, credential_scope, secret_key, dpp); /* The server-side generated digest for comparison. */ const auto digest = calc_hmac_sha256(signing_key, string_to_sign); /* TODO(rzarzynski): I would love to see our sstring having reserve() and * the non-const data() variant like C++17's std::string. */ using srv_signature_t = AWSEngine::VersionAbstractor::server_signature_t; srv_signature_t signature(srv_signature_t::initialized_later(), digest.SIZE * 2); buf_to_hex(digest.v, digest.SIZE, signature.begin()); ldpp_dout(dpp, 10) << "generated signature = " << signature << dendl; return signature; } AWSEngine::VersionAbstractor::server_signature_t get_v2_signature(CephContext* const cct, const std::string& secret_key, const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign) { if (secret_key.empty()) { throw -EINVAL; } const auto digest = calc_hmac_sha1(secret_key, string_to_sign); /* 64 is really enough */; char buf[64]; const int ret = ceph_armor(std::begin(buf), std::begin(buf) + 64, reinterpret_cast<const char *>(digest.v), reinterpret_cast<const char *>(digest.v + digest.SIZE)); if (ret < 0) { ldout(cct, 10) << "ceph_armor failed" << dendl; throw ret; } else { buf[ret] = '\0'; using srv_signature_t = AWSEngine::VersionAbstractor::server_signature_t; return srv_signature_t(buf, ret); } } bool AWSv4ComplMulti::ChunkMeta::is_new_chunk_in_stream(size_t stream_pos) const { return stream_pos >= (data_offset_in_stream + data_length); } size_t AWSv4ComplMulti::ChunkMeta::get_data_size(size_t stream_pos) const { if (stream_pos > (data_offset_in_stream + data_length)) { /* Data in parsing_buf. */ return data_length; } else { return data_offset_in_stream + data_length - stream_pos; } } /* AWSv4 completers begin. */ std::pair<AWSv4ComplMulti::ChunkMeta, size_t /* consumed */> AWSv4ComplMulti::ChunkMeta::create_next(CephContext* const cct, ChunkMeta&& old, const char* const metabuf, const size_t metabuf_len) { std::string_view metastr(metabuf, metabuf_len); const size_t semicolon_pos = metastr.find(";"); if (semicolon_pos == std::string_view::npos) { ldout(cct, 20) << "AWSv4ComplMulti cannot find the ';' separator" << dendl; throw rgw::io::Exception(EINVAL, std::system_category()); } char* data_field_end; /* strtoull ignores the "\r\n" sequence after each non-first chunk. */ const size_t data_length = std::strtoull(metabuf, &data_field_end, 16); if (data_length == 0 && data_field_end == metabuf) { ldout(cct, 20) << "AWSv4ComplMulti: cannot parse the data size" << dendl; throw rgw::io::Exception(EINVAL, std::system_category()); } /* Parse the chunk_signature=... part. */ const auto signature_part = metastr.substr(semicolon_pos + 1); const size_t eq_sign_pos = signature_part.find("="); if (eq_sign_pos == std::string_view::npos) { ldout(cct, 20) << "AWSv4ComplMulti: cannot find the '=' separator" << dendl; throw rgw::io::Exception(EINVAL, std::system_category()); } /* OK, we have at least the beginning of a signature. */ const size_t data_sep_pos = signature_part.find("\r\n"); if (data_sep_pos == std::string_view::npos) { ldout(cct, 20) << "AWSv4ComplMulti: no new line at signature end" << dendl; throw rgw::io::Exception(EINVAL, std::system_category()); } const auto signature = \ signature_part.substr(eq_sign_pos + 1, data_sep_pos - 1 - eq_sign_pos); if (signature.length() != SIG_SIZE) { ldout(cct, 20) << "AWSv4ComplMulti: signature.length() != 64" << dendl; throw rgw::io::Exception(EINVAL, std::system_category()); } const size_t data_starts_in_stream = \ + semicolon_pos + strlen(";") + data_sep_pos + strlen("\r\n") + old.data_offset_in_stream + old.data_length; ldout(cct, 20) << "parsed new chunk; signature=" << signature << ", data_length=" << data_length << ", data_starts_in_stream=" << data_starts_in_stream << dendl; return std::make_pair(ChunkMeta(data_starts_in_stream, data_length, signature), semicolon_pos + 83); } std::string AWSv4ComplMulti::calc_chunk_signature(const std::string& payload_hash) const { const auto string_to_sign = string_join_reserve("\n", AWS4_HMAC_SHA256_PAYLOAD_STR, date, credential_scope, prev_chunk_signature, AWS4_EMPTY_PAYLOAD_HASH, payload_hash); ldout(cct, 20) << "AWSv4ComplMulti: string_to_sign=\n" << string_to_sign << dendl; /* new chunk signature */ const auto sig = calc_hmac_sha256(signing_key, string_to_sign); /* FIXME(rzarzynski): std::string here is really unnecessary. */ return sig.to_str(); } bool AWSv4ComplMulti::is_signature_mismatched() { /* The validity of previous chunk can be verified only after getting meta- * data of the next one. */ const auto payload_hash = calc_hash_sha256_restart_stream(&sha256_hash); const auto calc_signature = calc_chunk_signature(payload_hash); if (chunk_meta.get_signature() != calc_signature) { ldout(cct, 20) << "AWSv4ComplMulti: ERROR: chunk signature mismatch" << dendl; ldout(cct, 20) << "AWSv4ComplMulti: declared signature=" << chunk_meta.get_signature() << dendl; ldout(cct, 20) << "AWSv4ComplMulti: calculated signature=" << calc_signature << dendl; return true; } else { prev_chunk_signature = chunk_meta.get_signature(); return false; } } size_t AWSv4ComplMulti::recv_body(char* const buf, const size_t buf_max) { /* Buffer stores only parsed stream. Raw values reflect the stream * we're getting from a client. */ size_t buf_pos = 0; if (chunk_meta.is_new_chunk_in_stream(stream_pos)) { /* Verify signature of the previous chunk. We aren't doing that for new * one as the procedure requires calculation of payload hash. This code * won't be triggered for the last, zero-length chunk. Instead, is will * be checked in the complete() method. */ if (stream_pos >= ChunkMeta::META_MAX_SIZE && is_signature_mismatched()) { throw rgw::io::Exception(ERR_SIGNATURE_NO_MATCH, std::system_category()); } /* We don't have metadata for this range. This means a new chunk, so we * need to parse a fresh portion of the stream. Let's start. */ size_t to_extract = parsing_buf.capacity() - parsing_buf.size(); do { const size_t orig_size = parsing_buf.size(); parsing_buf.resize(parsing_buf.size() + to_extract); const size_t received = io_base_t::recv_body(parsing_buf.data() + orig_size, to_extract); parsing_buf.resize(parsing_buf.size() - (to_extract - received)); if (received == 0) { break; } stream_pos += received; to_extract -= received; } while (to_extract > 0); size_t consumed; std::tie(chunk_meta, consumed) = \ ChunkMeta::create_next(cct, std::move(chunk_meta), parsing_buf.data(), parsing_buf.size()); /* We can drop the bytes consumed during metadata parsing. The remainder * can be chunk's data plus possibly beginning of next chunks' metadata. */ parsing_buf.erase(std::begin(parsing_buf), std::begin(parsing_buf) + consumed); } size_t stream_pos_was = stream_pos - parsing_buf.size(); size_t to_extract = \ std::min(chunk_meta.get_data_size(stream_pos_was), buf_max); dout(30) << "AWSv4ComplMulti: stream_pos_was=" << stream_pos_was << ", to_extract=" << to_extract << dendl; /* It's quite probable we have a couple of real data bytes stored together * with meta-data in the parsing_buf. We need to extract them and move to * the final buffer. This is a trade-off between frontend's read overhead * and memcpy. */ if (to_extract > 0 && parsing_buf.size() > 0) { const auto data_len = std::min(to_extract, parsing_buf.size()); const auto data_end_iter = std::begin(parsing_buf) + data_len; dout(30) << "AWSv4ComplMulti: to_extract=" << to_extract << ", data_len=" << data_len << dendl; std::copy(std::begin(parsing_buf), data_end_iter, buf); parsing_buf.erase(std::begin(parsing_buf), data_end_iter); calc_hash_sha256_update_stream(sha256_hash, buf, data_len); to_extract -= data_len; buf_pos += data_len; } /* Now we can do the bulk read directly from RestfulClient without any extra * buffering. */ while (to_extract > 0) { const size_t received = io_base_t::recv_body(buf + buf_pos, to_extract); dout(30) << "AWSv4ComplMulti: to_extract=" << to_extract << ", received=" << received << dendl; if (received == 0) { break; } calc_hash_sha256_update_stream(sha256_hash, buf + buf_pos, received); buf_pos += received; stream_pos += received; to_extract -= received; } dout(20) << "AWSv4ComplMulti: filled=" << buf_pos << dendl; return buf_pos; } void AWSv4ComplMulti::modify_request_state(const DoutPrefixProvider* dpp, req_state* const s_rw) { const char* const decoded_length = \ s_rw->info.env->get("HTTP_X_AMZ_DECODED_CONTENT_LENGTH"); if (!decoded_length) { throw -EINVAL; } else { s_rw->length = decoded_length; s_rw->content_length = parse_content_length(decoded_length); if (s_rw->content_length < 0) { ldpp_dout(dpp, 10) << "negative AWSv4's content length, aborting" << dendl; throw -EINVAL; } } /* Install the filter over rgw::io::RestfulClient. */ AWS_AUTHv4_IO(s_rw)->add_filter( std::static_pointer_cast<io_base_t>(shared_from_this())); } bool AWSv4ComplMulti::complete() { /* Now it's time to verify the signature of the last, zero-length chunk. */ if (is_signature_mismatched()) { ldout(cct, 10) << "ERROR: signature of last chunk does not match" << dendl; return false; } else { return true; } } rgw::auth::Completer::cmplptr_t AWSv4ComplMulti::create(const req_state* const s, std::string_view date, std::string_view credential_scope, std::string_view seed_signature, const boost::optional<std::string>& secret_key) { if (!secret_key) { /* Some external authorizers (like Keystone) aren't fully compliant with * AWSv4. They do not provide the secret_key which is necessary to handle * the streamed upload. */ throw -ERR_NOT_IMPLEMENTED; } const auto signing_key = \ rgw::auth::s3::get_v4_signing_key(s->cct, credential_scope, *secret_key, s); return std::make_shared<AWSv4ComplMulti>(s, std::move(date), std::move(credential_scope), std::move(seed_signature), signing_key); } size_t AWSv4ComplSingle::recv_body(char* const buf, const size_t max) { const auto received = io_base_t::recv_body(buf, max); calc_hash_sha256_update_stream(sha256_hash, buf, received); return received; } void AWSv4ComplSingle::modify_request_state(const DoutPrefixProvider* dpp, req_state* const s_rw) { /* Install the filter over rgw::io::RestfulClient. */ AWS_AUTHv4_IO(s_rw)->add_filter( std::static_pointer_cast<io_base_t>(shared_from_this())); } bool AWSv4ComplSingle::complete() { /* The completer is only for the cases where signed payload has been * requested. It won't be used, for instance, during the query string-based * authentication. */ const auto payload_hash = calc_hash_sha256_close_stream(&sha256_hash); /* Validate x-amz-sha256 */ if (payload_hash.compare(expected_request_payload_hash) == 0) { return true; } else { ldout(cct, 10) << "ERROR: x-amz-content-sha256 does not match" << dendl; ldout(cct, 10) << "ERROR: grab_aws4_sha256_hash()=" << payload_hash << dendl; ldout(cct, 10) << "ERROR: expected_request_payload_hash=" << expected_request_payload_hash << dendl; return false; } } AWSv4ComplSingle::AWSv4ComplSingle(const req_state* const s) : io_base_t(nullptr), cct(s->cct), expected_request_payload_hash(get_v4_exp_payload_hash(s->info)), sha256_hash(calc_hash_sha256_open_stream()) { } rgw::auth::Completer::cmplptr_t AWSv4ComplSingle::create(const req_state* const s, const boost::optional<std::string>&) { return std::make_shared<AWSv4ComplSingle>(s); } } // namespace rgw::auth::s3
42,302
31.24314
109
cc
null
ceph-main/src/rgw/rgw_auth_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 <array> #include <memory> #include <string> #include <string_view> #include <tuple> #include <boost/algorithm/string.hpp> #include <boost/container/static_vector.hpp> #include "common/sstring.hh" #include "rgw_common.h" #include "rgw_rest_s3.h" #include "rgw_auth.h" #include "rgw_auth_filters.h" #include "rgw_auth_keystone.h" namespace rgw { namespace auth { namespace s3 { static constexpr auto RGW_AUTH_GRACE = std::chrono::minutes{15}; // returns true if the request time is within RGW_AUTH_GRACE of the current time bool is_time_skew_ok(time_t t); class STSAuthStrategy : public rgw::auth::Strategy, public rgw::auth::RemoteApplier::Factory, public rgw::auth::LocalApplier::Factory, public rgw::auth::RoleApplier::Factory { typedef rgw::auth::IdentityApplier::aplptr_t aplptr_t; rgw::sal::Driver* driver; const rgw::auth::ImplicitTenants& implicit_tenant_context; STSEngine sts_engine; aplptr_t create_apl_remote(CephContext* const cct, const req_state* const s, rgw::auth::RemoteApplier::acl_strategy_t&& acl_alg, const rgw::auth::RemoteApplier::AuthInfo &info) const override { auto apl = rgw::auth::add_sysreq(cct, driver, s, rgw::auth::RemoteApplier(cct, driver, std::move(acl_alg), info, implicit_tenant_context, rgw::auth::ImplicitTenants::IMPLICIT_TENANTS_S3)); 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_sysreq(cct, driver, s, rgw::auth::LocalApplier(cct, user_info, subuser, perm_mask, access_key_id)); return aplptr_t(new decltype(apl)(std::move(apl))); } aplptr_t create_apl_role(CephContext* const cct, const req_state* const s, const rgw::auth::RoleApplier::Role& role, const rgw::auth::RoleApplier::TokenAttrs& token_attrs) const override { auto apl = rgw::auth::add_sysreq(cct, driver, s, rgw::auth::RoleApplier(cct, role, token_attrs)); return aplptr_t(new decltype(apl)(std::move(apl))); } public: STSAuthStrategy(CephContext* const cct, rgw::sal::Driver* driver, const rgw::auth::ImplicitTenants& implicit_tenant_context, AWSEngine::VersionAbstractor* const ver_abstractor) : driver(driver), implicit_tenant_context(implicit_tenant_context), sts_engine(cct, driver, *ver_abstractor, static_cast<rgw::auth::LocalApplier::Factory*>(this), static_cast<rgw::auth::RemoteApplier::Factory*>(this), static_cast<rgw::auth::RoleApplier::Factory*>(this)) { if (cct->_conf->rgw_s3_auth_use_sts) { add_engine(Control::SUFFICIENT, sts_engine); } } const char* get_name() const noexcept override { return "rgw::auth::s3::STSAuthStrategy"; } }; class ExternalAuthStrategy : public rgw::auth::Strategy, public rgw::auth::RemoteApplier::Factory { typedef rgw::auth::IdentityApplier::aplptr_t aplptr_t; rgw::sal::Driver* driver; const rgw::auth::ImplicitTenants& implicit_tenant_context; using keystone_config_t = rgw::keystone::CephCtxConfig; using keystone_cache_t = rgw::keystone::TokenCache; using secret_cache_t = rgw::auth::keystone::SecretCache; using EC2Engine = rgw::auth::keystone::EC2Engine; boost::optional <EC2Engine> keystone_engine; LDAPEngine ldap_engine; aplptr_t create_apl_remote(CephContext* const cct, const req_state* const s, rgw::auth::RemoteApplier::acl_strategy_t&& acl_alg, const rgw::auth::RemoteApplier::AuthInfo &info) const override { auto apl = rgw::auth::add_sysreq(cct, driver, s, rgw::auth::RemoteApplier(cct, driver, std::move(acl_alg), info, implicit_tenant_context, rgw::auth::ImplicitTenants::IMPLICIT_TENANTS_S3)); /* TODO(rzarzynski): replace with static_ptr. */ return aplptr_t(new decltype(apl)(std::move(apl))); } public: ExternalAuthStrategy(CephContext* const cct, rgw::sal::Driver* driver, const rgw::auth::ImplicitTenants& implicit_tenant_context, AWSEngine::VersionAbstractor* const ver_abstractor) : driver(driver), implicit_tenant_context(implicit_tenant_context), ldap_engine(cct, driver, *ver_abstractor, static_cast<rgw::auth::RemoteApplier::Factory*>(this)) { if (cct->_conf->rgw_s3_auth_use_keystone && ! cct->_conf->rgw_keystone_url.empty()) { keystone_engine.emplace(cct, ver_abstractor, static_cast<rgw::auth::RemoteApplier::Factory*>(this), keystone_config_t::get_instance(), keystone_cache_t::get_instance<keystone_config_t>(), secret_cache_t::get_instance()); add_engine(Control::SUFFICIENT, *keystone_engine); } if (ldap_engine.valid()) { add_engine(Control::SUFFICIENT, ldap_engine); } } const char* get_name() const noexcept override { return "rgw::auth::s3::AWSv2ExternalAuthStrategy"; } }; template <class AbstractorT, bool AllowAnonAccessT = false> class AWSAuthStrategy : public rgw::auth::Strategy, public rgw::auth::LocalApplier::Factory { typedef rgw::auth::IdentityApplier::aplptr_t aplptr_t; static_assert(std::is_base_of<rgw::auth::s3::AWSEngine::VersionAbstractor, AbstractorT>::value, "AbstractorT must be a subclass of rgw::auth::s3::VersionAbstractor"); rgw::sal::Driver* driver; AbstractorT ver_abstractor; S3AnonymousEngine anonymous_engine; ExternalAuthStrategy external_engines; STSAuthStrategy sts_engine; LocalEngine local_engine; 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_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))); } public: using engine_map_t = std::map <std::string, std::reference_wrapper<const Engine>>; void add_engines(const std::vector <std::string>& auth_order, engine_map_t eng_map) { auto ctrl_flag = Control::SUFFICIENT; for (const auto &eng : auth_order) { // fallback to the last engine, in case of multiple engines, since ctrl // flag is sufficient for others, error from earlier engine is returned if (&eng == &auth_order.back() && eng_map.size() > 1) { ctrl_flag = Control::FALLBACK; } if (const auto kv = eng_map.find(eng); kv != eng_map.end()) { add_engine(ctrl_flag, kv->second); } } } auto parse_auth_order(CephContext* const cct) { std::vector <std::string> result; const std::set <std::string_view> allowed_auth = { "sts", "external", "local" }; std::vector <std::string> default_order = { "sts", "external", "local" }; // supplied strings may contain a space, so let's bypass that boost::split(result, cct->_conf->rgw_s3_auth_order, boost::is_any_of(", "), boost::token_compress_on); if (std::any_of(result.begin(), result.end(), [allowed_auth](std::string_view s) { return allowed_auth.find(s) == allowed_auth.end();})){ return default_order; } return result; } AWSAuthStrategy(CephContext* const cct, const rgw::auth::ImplicitTenants& implicit_tenant_context, rgw::sal::Driver* driver) : driver(driver), ver_abstractor(cct), anonymous_engine(cct, static_cast<rgw::auth::LocalApplier::Factory*>(this)), external_engines(cct, driver, implicit_tenant_context, &ver_abstractor), sts_engine(cct, driver, implicit_tenant_context, &ver_abstractor), local_engine(cct, driver, ver_abstractor, static_cast<rgw::auth::LocalApplier::Factory*>(this)) { /* The anonymous auth. */ if (AllowAnonAccessT) { add_engine(Control::SUFFICIENT, anonymous_engine); } auto auth_order = parse_auth_order(cct); engine_map_t engine_map; /* STS Auth*/ if (! sts_engine.is_empty()) { engine_map.insert(std::make_pair("sts", std::cref(sts_engine))); } /* The external auth. */ if (! external_engines.is_empty()) { engine_map.insert(std::make_pair("external", std::cref(external_engines))); } /* The local auth. */ if (cct->_conf->rgw_s3_auth_use_rados) { engine_map.insert(std::make_pair("local", std::cref(local_engine))); } add_engines(auth_order, engine_map); } const char* get_name() const noexcept override { return "rgw::auth::s3::AWSAuthStrategy"; } }; class AWSv4ComplMulti : public rgw::auth::Completer, public rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>, public std::enable_shared_from_this<AWSv4ComplMulti> { using io_base_t = rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>; using signing_key_t = sha256_digest_t; CephContext* const cct; const std::string_view date; const std::string_view credential_scope; const signing_key_t signing_key; class ChunkMeta { size_t data_offset_in_stream = 0; size_t data_length = 0; std::string signature; ChunkMeta(const size_t data_starts_in_stream, const size_t data_length, const std::string_view signature) : data_offset_in_stream(data_starts_in_stream), data_length(data_length), signature(std::string(signature)) { } explicit ChunkMeta(const std::string_view& signature) : signature(std::string(signature)) { } public: static constexpr size_t SIG_SIZE = 64; /* Let's suppose the data length fields can't exceed uint64_t. */ static constexpr size_t META_MAX_SIZE = \ sarrlen("\r\nffffffffffffffff;chunk-signature=") + SIG_SIZE + sarrlen("\r\n"); /* The metadata size of for the last, empty chunk. */ static constexpr size_t META_MIN_SIZE = \ sarrlen("0;chunk-signature=") + SIG_SIZE + sarrlen("\r\n"); /* Detect whether a given stream_pos fits in boundaries of a chunk. */ bool is_new_chunk_in_stream(size_t stream_pos) const; /* Get the remaining data size. */ size_t get_data_size(size_t stream_pos) const; const std::string& get_signature() const { return signature; } /* Factory: create an object representing metadata of first, initial chunk * in a stream. */ static ChunkMeta create_first(const std::string_view& seed_signature) { return ChunkMeta(seed_signature); } /* Factory: parse a block of META_MAX_SIZE bytes and creates an object * representing non-first chunk in a stream. As the process is sequential * and depends on the previous chunk, caller must pass it. */ static std::pair<ChunkMeta, size_t> create_next(CephContext* cct, ChunkMeta&& prev, const char* metabuf, size_t metabuf_len); } chunk_meta; size_t stream_pos; boost::container::static_vector<char, ChunkMeta::META_MAX_SIZE> parsing_buf; ceph::crypto::SHA256* sha256_hash; std::string prev_chunk_signature; bool is_signature_mismatched(); std::string calc_chunk_signature(const std::string& payload_hash) const; public: /* We need the constructor to be public because of the std::make_shared that * is employed by the create() method. */ AWSv4ComplMulti(const req_state* const s, std::string_view date, std::string_view credential_scope, std::string_view seed_signature, const signing_key_t& signing_key) : io_base_t(nullptr), cct(s->cct), date(std::move(date)), credential_scope(std::move(credential_scope)), signing_key(signing_key), /* The evolving state. */ chunk_meta(ChunkMeta::create_first(seed_signature)), stream_pos(0), sha256_hash(calc_hash_sha256_open_stream()), prev_chunk_signature(std::move(seed_signature)) { } ~AWSv4ComplMulti() { if (sha256_hash) { calc_hash_sha256_close_stream(&sha256_hash); } } /* rgw::io::DecoratedRestfulClient. */ size_t recv_body(char* buf, size_t max) override; /* rgw::auth::Completer. */ void modify_request_state(const DoutPrefixProvider* dpp, req_state* s_rw) override; bool complete() override; /* Factories. */ static cmplptr_t create(const req_state* s, std::string_view date, std::string_view credential_scope, std::string_view seed_signature, const boost::optional<std::string>& secret_key); }; class AWSv4ComplSingle : public rgw::auth::Completer, public rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>, public std::enable_shared_from_this<AWSv4ComplSingle> { using io_base_t = rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>; CephContext* const cct; const char* const expected_request_payload_hash; ceph::crypto::SHA256* sha256_hash = nullptr; public: /* Defined in rgw_auth_s3.cc because of get_v4_exp_payload_hash(). We need * the constructor to be public because of the std::make_shared employed by * the create() method. */ explicit AWSv4ComplSingle(const req_state* const s); ~AWSv4ComplSingle() { if (sha256_hash) { calc_hash_sha256_close_stream(&sha256_hash); } } /* rgw::io::DecoratedRestfulClient. */ size_t recv_body(char* buf, size_t max) override; /* rgw::auth::Completer. */ void modify_request_state(const DoutPrefixProvider* dpp, req_state* s_rw) override; bool complete() override; /* Factories. */ static cmplptr_t create(const req_state* s, const boost::optional<std::string>&); }; } /* namespace s3 */ } /* namespace auth */ } /* namespace rgw */ void rgw_create_s3_canonical_header( const DoutPrefixProvider *dpp, const char *method, const char *content_md5, const char *content_type, const char *date, const meta_map_t& meta_map, const meta_map_t& qs_map, const char *request_uri, const std::map<std::string, std::string>& sub_resources, std::string& dest_str); bool rgw_create_s3_canonical_header(const DoutPrefixProvider *dpp, const req_info& info, utime_t *header_time, /* out */ std::string& dest, /* out */ bool qsr); static inline std::tuple<bool, std::string, utime_t> rgw_create_s3_canonical_header(const DoutPrefixProvider *dpp, const req_info& info, const bool qsr) { std::string dest; utime_t header_time; const bool ok = rgw_create_s3_canonical_header(dpp, info, &header_time, dest, qsr); return std::make_tuple(ok, dest, header_time); } namespace rgw { namespace auth { namespace s3 { static constexpr char AWS4_HMAC_SHA256_STR[] = "AWS4-HMAC-SHA256"; static constexpr char AWS4_HMAC_SHA256_PAYLOAD_STR[] = "AWS4-HMAC-SHA256-PAYLOAD"; static constexpr char AWS4_EMPTY_PAYLOAD_HASH[] = \ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; static constexpr char AWS4_UNSIGNED_PAYLOAD_HASH[] = "UNSIGNED-PAYLOAD"; static constexpr char AWS4_STREAMING_PAYLOAD_HASH[] = \ "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"; bool is_non_s3_op(RGWOpType op_type); int parse_v4_credentials(const req_info& info, /* in */ std::string_view& access_key_id, /* out */ std::string_view& credential_scope, /* out */ std::string_view& signedheaders, /* out */ std::string_view& signature, /* out */ std::string_view& date, /* out */ std::string_view& session_token, /* out */ const bool using_qs, /* in */ const DoutPrefixProvider *dpp); /* in */ string gen_v4_scope(const ceph::real_time& timestamp, const string& region, const string& service); static inline bool char_needs_aws4_escaping(const char c, bool encode_slash) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { return false; } switch (c) { case '-': case '_': case '.': case '~': return false; } if (c == '/' && !encode_slash) return false; return true; } static inline std::string aws4_uri_encode(const std::string& src, bool encode_slash) { std::string result; for (const std::string::value_type c : src) { if (char_needs_aws4_escaping(c, encode_slash)) { rgw_uri_escape_char(c, result); } else { result.push_back(c); } } return result; } static inline std::string aws4_uri_recode(const std::string_view& src, bool encode_slash) { std::string decoded = url_decode(src); return aws4_uri_encode(decoded, encode_slash); } static inline std::string get_v4_canonical_uri(const req_info& info) { /* The code should normalize according to RFC 3986 but S3 does NOT do path * normalization that SigV4 typically does. This code follows the same * approach that boto library. See auth.py:canonical_uri(...). */ std::string canonical_uri = aws4_uri_recode(info.request_uri_aws4, false); if (canonical_uri.empty()) { canonical_uri = "/"; } else { boost::replace_all(canonical_uri, "+", "%20"); } return canonical_uri; } static inline std::string gen_v4_canonical_uri(const req_info& info) { /* The code should normalize according to RFC 3986 but S3 does NOT do path * normalization that SigV4 typically does. This code follows the same * approach that boto library. See auth.py:canonical_uri(...). */ std::string canonical_uri = aws4_uri_recode(info.request_uri, false); if (canonical_uri.empty()) { canonical_uri = "/"; } else { boost::replace_all(canonical_uri, "+", "%20"); } return canonical_uri; } static inline const string calc_v4_payload_hash(const string& payload) { ceph::crypto::SHA256* sha256_hash = calc_hash_sha256_open_stream(); calc_hash_sha256_update_stream(sha256_hash, payload.c_str(), payload.length()); const auto payload_hash = calc_hash_sha256_close_stream(&sha256_hash); return payload_hash; } static inline const char* get_v4_exp_payload_hash(const req_info& info) { /* In AWSv4 the hash of real, transferred payload IS NOT necessary to form * a Canonical Request, and thus verify a Signature. x-amz-content-sha256 * header lets get the information very early -- before seeing first byte * of HTTP body. As a consequence, we can decouple Signature verification * from payload's fingerprint check. */ const char *expected_request_payload_hash = \ info.env->get("HTTP_X_AMZ_CONTENT_SHA256"); if (!expected_request_payload_hash) { /* An HTTP client MUST send x-amz-content-sha256. The single exception * is the case of using the Query Parameters where "UNSIGNED-PAYLOAD" * literals are used for crafting Canonical Request: * * You don't include a payload hash in the Canonical Request, because * when you create a presigned URL, you don't know the payload content * because the URL is used to upload an arbitrary payload. Instead, you * use a constant string UNSIGNED-PAYLOAD. */ expected_request_payload_hash = AWS4_UNSIGNED_PAYLOAD_HASH; } return expected_request_payload_hash; } static inline bool is_v4_payload_unsigned(const char* const exp_payload_hash) { return boost::equals(exp_payload_hash, AWS4_UNSIGNED_PAYLOAD_HASH); } static inline bool is_v4_payload_empty(const req_state* const s) { /* from rfc2616 - 4.3 Message Body * * "The presence of a message-body in a request is signaled by the inclusion * of a Content-Length or Transfer-Encoding header field in the request's * message-headers." */ return s->content_length == 0 && s->info.env->get("HTTP_TRANSFER_ENCODING") == nullptr; } static inline bool is_v4_payload_streamed(const char* const exp_payload_hash) { return boost::equals(exp_payload_hash, AWS4_STREAMING_PAYLOAD_HASH); } std::string get_v4_canonical_qs(const req_info& info, bool using_qs); std::string gen_v4_canonical_qs(const req_info& info, bool is_non_s3_op); boost::optional<std::string> get_v4_canonical_headers(const req_info& info, const std::string_view& signedheaders, bool using_qs, bool force_boto2_compat); std::string gen_v4_canonical_headers(const req_info& info, const std::map<std::string, std::string>& extra_headers, string *signed_hdrs); extern sha256_digest_t get_v4_canon_req_hash(CephContext* cct, const std::string_view& http_verb, const std::string& canonical_uri, const std::string& canonical_qs, const std::string& canonical_hdrs, const std::string_view& signed_hdrs, const std::string_view& request_payload_hash, const DoutPrefixProvider *dpp); AWSEngine::VersionAbstractor::string_to_sign_t get_v4_string_to_sign(CephContext* cct, const std::string_view& algorithm, const std::string_view& request_date, const std::string_view& credential_scope, const sha256_digest_t& canonreq_hash, const DoutPrefixProvider *dpp); extern AWSEngine::VersionAbstractor::server_signature_t get_v4_signature(const std::string_view& credential_scope, CephContext* const cct, const std::string_view& secret_key, const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign, const DoutPrefixProvider *dpp); extern AWSEngine::VersionAbstractor::server_signature_t get_v2_signature(CephContext*, const std::string& secret_key, const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign); } /* namespace s3 */ } /* namespace auth */ } /* namespace rgw */
23,640
35.539413
101
h
null
ceph-main/src/rgw/rgw_b64.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/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <limits> #include <string> #include <string_view> namespace rgw { /* * A header-only Base64 encoder built on boost::archive. The * formula is based on a class poposed for inclusion in boost in * 2011 by Denis Shevchenko (abandoned), updated slightly * (e.g., uses std::string_view). * * Also, wrap_width added as template argument, based on * feedback from Marcus. */ template<int wrap_width = std::numeric_limits<int>::max()> inline std::string to_base64(std::string_view sview) { using namespace boost::archive::iterators; // output must be =padded modulo 3 auto psize = sview.size(); while ((psize % 3) != 0) { ++psize; } /* RFC 2045 requires linebreaks to be present in the output * sequence every at-most 76 characters (MIME-compliance), * but we could likely omit it. */ typedef insert_linebreaks< base64_from_binary< transform_width< std::string_view::const_iterator ,6,8> > ,wrap_width > b64_iter; std::string outstr(b64_iter(sview.data()), b64_iter(sview.data() + sview.size())); // pad outstr with '=' to a length that is a multiple of 3 for (size_t ix = 0; ix < (psize-sview.size()); ++ix) outstr.push_back('='); return outstr; } inline std::string from_base64(std::string_view sview) { using namespace boost::archive::iterators; if (sview.empty()) return std::string(); /* MIME-compliant input will have line-breaks, so we have to * filter WS */ typedef transform_width< binary_from_base64< remove_whitespace< std::string_view::const_iterator>> ,8,6 > b64_iter; while (sview.back() == '=') sview.remove_suffix(1); std::string outstr(b64_iter(sview.data()), b64_iter(sview.data() + sview.size())); return outstr; } } /* namespace */
2,336
26.494118
70
h
null
ceph-main/src/rgw/rgw_basic_types.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <iostream> #include <sstream> #include <string> #include "cls/user/cls_user_types.h" #include "rgw_basic_types.h" #include "rgw_bucket.h" #include "rgw_xml.h" #include "common/ceph_json.h" #include "common/Formatter.h" #include "cls/user/cls_user_types.h" #include "cls/rgw/cls_rgw_types.h" using std::ostream; using std::string; using std::stringstream; using namespace std; void decode_json_obj(rgw_user& val, JSONObj *obj) { val.from_str(obj->get_data()); } void encode_json(const char *name, const rgw_user& val, Formatter *f) { f->dump_string(name, val.to_str()); } void encode_xml(const char *name, const rgw_user& val, Formatter *f) { encode_xml(name, val.to_str(), f); } rgw_bucket::rgw_bucket(const rgw_user& u, const cls_user_bucket& b) : tenant(u.tenant), name(b.name), marker(b.marker), bucket_id(b.bucket_id), explicit_placement(b.explicit_placement.data_pool, b.explicit_placement.data_extra_pool, b.explicit_placement.index_pool) { } void rgw_bucket::convert(cls_user_bucket *b) const { b->name = name; b->marker = marker; b->bucket_id = bucket_id; b->explicit_placement.data_pool = explicit_placement.data_pool.to_str(); b->explicit_placement.data_extra_pool = explicit_placement.data_extra_pool.to_str(); b->explicit_placement.index_pool = explicit_placement.index_pool.to_str(); } std::string rgw_bucket::get_key(char tenant_delim, char id_delim, size_t reserve) const { const size_t max_len = tenant.size() + sizeof(tenant_delim) + name.size() + sizeof(id_delim) + bucket_id.size() + reserve; std::string key; key.reserve(max_len); if (!tenant.empty() && tenant_delim) { key.append(tenant); key.append(1, tenant_delim); } key.append(name); if (!bucket_id.empty() && id_delim) { key.append(1, id_delim); key.append(bucket_id); } return key; } void rgw_bucket::generate_test_instances(list<rgw_bucket*>& o) { rgw_bucket *b = new rgw_bucket; init_bucket(b, "tenant", "name", "pool", ".index_pool", "marker", "123"); o.push_back(b); o.push_back(new rgw_bucket); } std::string rgw_bucket_shard::get_key(char tenant_delim, char id_delim, char shard_delim, size_t reserve) const { static constexpr size_t shard_len{12}; // ":4294967295\0" auto key = bucket.get_key(tenant_delim, id_delim, reserve + shard_len); if (shard_id >= 0 && shard_delim) { key.append(1, shard_delim); key.append(std::to_string(shard_id)); } return key; } void encode(const rgw_bucket_shard& b, bufferlist& bl, uint64_t f) { encode(b.bucket, bl, f); encode(b.shard_id, bl, f); } void decode(rgw_bucket_shard& b, bufferlist::const_iterator& bl) { decode(b.bucket, bl); decode(b.shard_id, bl); } void encode_json_impl(const char *name, const rgw_zone_id& zid, Formatter *f) { encode_json(name, zid.id, f); } void decode_json_obj(rgw_zone_id& zid, JSONObj *obj) { decode_json_obj(zid.id, obj); } void rgw_user::generate_test_instances(list<rgw_user*>& o) { rgw_user *u = new rgw_user("tenant", "user"); o.push_back(u); o.push_back(new rgw_user); } void rgw_data_placement_target::dump(Formatter *f) const { encode_json("data_pool", data_pool, f); encode_json("data_extra_pool", data_extra_pool, f); encode_json("index_pool", index_pool, f); } void rgw_data_placement_target::decode_json(JSONObj *obj) { JSONDecoder::decode_json("data_pool", data_pool, obj); JSONDecoder::decode_json("data_extra_pool", data_extra_pool, obj); JSONDecoder::decode_json("index_pool", index_pool, obj); } void rgw_bucket::dump(Formatter *f) const { encode_json("name", name, f); encode_json("marker", marker, f); encode_json("bucket_id", bucket_id, f); encode_json("tenant", tenant, f); encode_json("explicit_placement", explicit_placement, f); } void rgw_bucket::decode_json(JSONObj *obj) { JSONDecoder::decode_json("name", name, obj); JSONDecoder::decode_json("marker", marker, obj); JSONDecoder::decode_json("bucket_id", bucket_id, obj); JSONDecoder::decode_json("tenant", tenant, obj); JSONDecoder::decode_json("explicit_placement", explicit_placement, obj); if (explicit_placement.data_pool.empty()) { /* decoding old format */ JSONDecoder::decode_json("pool", explicit_placement.data_pool, obj); JSONDecoder::decode_json("data_extra_pool", explicit_placement.data_extra_pool, obj); JSONDecoder::decode_json("index_pool", explicit_placement.index_pool, obj); } } namespace rgw { namespace auth { ostream& operator <<(ostream& m, const Principal& p) { if (p.is_wildcard()) { return m << "*"; } m << "arn:aws:iam:" << p.get_tenant() << ":"; if (p.is_tenant()) { return m << "root"; } return m << (p.is_user() ? "user/" : "role/") << p.get_id(); } } }
4,934
26.265193
89
cc
null
ceph-main/src/rgw/rgw_basic_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 "rgw_compression_types.h" #include "rgw_pool_types.h" #include "rgw_acl_types.h" #include "rgw_zone_types.h" #include "rgw_user_types.h" #include "rgw_bucket_types.h" #include "rgw_obj_types.h" #include "rgw_obj_manifest.h" #include "common/Formatter.h" class JSONObj; class cls_user_bucket; enum RGWIntentEvent { DEL_OBJ = 0, DEL_DIR = 1, }; /** Store error returns for output at a different point in the program */ struct rgw_err { rgw_err(); void clear(); bool is_clear() const; bool is_err() const; friend std::ostream& operator<<(std::ostream& oss, const rgw_err &err); int http_ret; int ret; std::string err_code; std::string message; }; /* rgw_err */ struct rgw_zone_id { std::string id; rgw_zone_id() {} rgw_zone_id(const std::string& _id) : id(_id) {} rgw_zone_id(std::string&& _id) : id(std::move(_id)) {} void encode(ceph::buffer::list& bl) const { /* backward compatiblity, not using ENCODE_{START,END} macros */ ceph::encode(id, bl); } void decode(ceph::buffer::list::const_iterator& bl) { /* backward compatiblity, not using DECODE_{START,END} macros */ ceph::decode(id, bl); } void clear() { id.clear(); } bool operator==(const std::string& _id) const { return (id == _id); } bool operator==(const rgw_zone_id& zid) const { return (id == zid.id); } bool operator!=(const rgw_zone_id& zid) const { return (id != zid.id); } bool operator<(const rgw_zone_id& zid) const { return (id < zid.id); } bool operator>(const rgw_zone_id& zid) const { return (id > zid.id); } bool empty() const { return id.empty(); } }; WRITE_CLASS_ENCODER(rgw_zone_id) inline std::ostream& operator<<(std::ostream& os, const rgw_zone_id& zid) { os << zid.id; return os; } struct obj_version; struct rgw_placement_rule; struct RGWAccessKey; class RGWUserCaps; extern void encode_json(const char *name, const obj_version& v, Formatter *f); extern void encode_json(const char *name, const RGWUserCaps& val, Formatter *f); extern void encode_json(const char *name, const rgw_pool& pool, Formatter *f); extern void encode_json(const char *name, const rgw_placement_rule& r, Formatter *f); extern void encode_json_impl(const char *name, const rgw_zone_id& zid, ceph::Formatter *f); extern void encode_json_plain(const char *name, const RGWAccessKey& val, Formatter *f); extern void decode_json_obj(obj_version& v, JSONObj *obj); extern void decode_json_obj(rgw_zone_id& zid, JSONObj *obj); extern void decode_json_obj(rgw_pool& pool, JSONObj *obj); extern void decode_json_obj(rgw_placement_rule& v, JSONObj *obj); // Represents an identity. This is more wide-ranging than a // 'User'. Its purposes is to be matched against by an // IdentityApplier. The internal representation will doubtless change as // more types are added. We may want to expose the type enum and make // the member public so people can switch/case on it. namespace rgw { namespace auth { class Principal { enum types { User, Role, Tenant, Wildcard, OidcProvider, AssumedRole }; types t; rgw_user u; std::string idp_url; explicit Principal(types t) : t(t) {} Principal(types t, std::string&& n, std::string i) : t(t), u(std::move(n), std::move(i)) {} Principal(std::string&& idp_url) : t(OidcProvider), idp_url(std::move(idp_url)) {} public: static Principal wildcard() { return Principal(Wildcard); } static Principal user(std::string&& t, std::string&& u) { return Principal(User, std::move(t), std::move(u)); } static Principal role(std::string&& t, std::string&& u) { return Principal(Role, std::move(t), std::move(u)); } static Principal tenant(std::string&& t) { return Principal(Tenant, std::move(t), {}); } static Principal oidc_provider(std::string&& idp_url) { return Principal(std::move(idp_url)); } static Principal assumed_role(std::string&& t, std::string&& u) { return Principal(AssumedRole, std::move(t), std::move(u)); } bool is_wildcard() const { return t == Wildcard; } bool is_user() const { return t == User; } bool is_role() const { return t == Role; } bool is_tenant() const { return t == Tenant; } bool is_oidc_provider() const { return t == OidcProvider; } bool is_assumed_role() const { return t == AssumedRole; } const std::string& get_tenant() const { return u.tenant; } const std::string& get_id() const { return u.id; } const std::string& get_idp_url() const { return idp_url; } const std::string& get_role_session() const { return u.id; } const std::string& get_role() const { return u.id; } bool operator ==(const Principal& o) const { return (t == o.t) && (u == o.u); } bool operator <(const Principal& o) const { return (t < o.t) || ((t == o.t) && (u < o.u)); } }; std::ostream& operator <<(std::ostream& m, const Principal& p); } } class JSONObj; void decode_json_obj(rgw_user& val, JSONObj *obj); void encode_json(const char *name, const rgw_user& val, ceph::Formatter *f); void encode_xml(const char *name, const rgw_user& val, ceph::Formatter *f); inline std::ostream& operator<<(std::ostream& out, const rgw_user &u) { std::string s; u.to_str(s); return out << s; } struct RGWUploadPartInfo { uint32_t num; uint64_t size; uint64_t accounted_size{0}; std::string etag; ceph::real_time modified; RGWObjManifest manifest; RGWCompressionInfo cs_info; // Previous part obj prefixes. Recorded here for later cleanup. std::set<std::string> past_prefixes; RGWUploadPartInfo() : num(0), size(0) {} void encode(bufferlist& bl) const { ENCODE_START(5, 2, bl); encode(num, bl); encode(size, bl); encode(etag, bl); encode(modified, bl); encode(manifest, bl); encode(cs_info, bl); encode(accounted_size, bl); encode(past_prefixes, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(5, 2, 2, bl); decode(num, bl); decode(size, bl); decode(etag, bl); decode(modified, bl); if (struct_v >= 3) decode(manifest, bl); if (struct_v >= 4) { decode(cs_info, bl); decode(accounted_size, bl); } else { accounted_size = size; } if (struct_v >= 5) { decode(past_prefixes, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWUploadPartInfo*>& o); }; WRITE_CLASS_ENCODER(RGWUploadPartInfo)
7,263
23.876712
91
h
null
ceph-main/src/rgw/rgw_bucket.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_bucket.h" #include "common/errno.h" #define dout_subsys ceph_subsys_rgw // stolen from src/cls/version/cls_version.cc #define VERSION_ATTR "ceph.objclass.version" using namespace std; static void set_err_msg(std::string *sink, std::string msg) { if (sink && !msg.empty()) *sink = msg; } void init_bucket(rgw_bucket *b, const char *t, const char *n, const char *dp, const char *ip, const char *m, const char *id) { b->tenant = t; b->name = n; b->marker = m; b->bucket_id = id; b->explicit_placement.data_pool = rgw_pool(dp); b->explicit_placement.index_pool = rgw_pool(ip); } // parse key in format: [tenant/]name:instance[:shard_id] int rgw_bucket_parse_bucket_key(CephContext *cct, const string& key, rgw_bucket *bucket, int *shard_id) { std::string_view name{key}; std::string_view instance; // split tenant/name auto pos = name.find('/'); if (pos != string::npos) { auto tenant = name.substr(0, pos); bucket->tenant.assign(tenant.begin(), tenant.end()); name = name.substr(pos + 1); } else { bucket->tenant.clear(); } // split name:instance pos = name.find(':'); if (pos != string::npos) { instance = name.substr(pos + 1); name = name.substr(0, pos); } bucket->name.assign(name.begin(), name.end()); // split instance:shard pos = instance.find(':'); if (pos == string::npos) { bucket->bucket_id.assign(instance.begin(), instance.end()); if (shard_id) { *shard_id = -1; } return 0; } // parse shard id auto shard = instance.substr(pos + 1); string err; auto id = strict_strtol(shard.data(), 10, &err); if (!err.empty()) { if (cct) { ldout(cct, 0) << "ERROR: failed to parse bucket shard '" << instance.data() << "': " << err << dendl; } return -EINVAL; } if (shard_id) { *shard_id = id; } instance = instance.substr(0, pos); bucket->bucket_id.assign(instance.begin(), instance.end()); return 0; } /* * Note that this is not a reversal of parse_bucket(). That one deals * with the syntax we need in metadata and such. This one deals with * the representation in RADOS pools. We chose '/' because it's not * acceptable in bucket names and thus qualified buckets cannot conflict * with the legacy or S3 buckets. */ std::string rgw_make_bucket_entry_name(const std::string& tenant_name, const std::string& bucket_name) { std::string bucket_entry; if (bucket_name.empty()) { bucket_entry.clear(); } else if (tenant_name.empty()) { bucket_entry = bucket_name; } else { bucket_entry = tenant_name + "/" + bucket_name; } return bucket_entry; } /* * Tenants are separated from buckets in URLs by a colon in S3. * This function is not to be used on Swift URLs, not even for COPY arguments. */ int rgw_parse_url_bucket(const string &bucket, const string& auth_tenant, string &tenant_name, string &bucket_name) { int pos = bucket.find(':'); if (pos >= 0) { /* * N.B.: We allow ":bucket" syntax with explicit empty tenant in order * to refer to the legacy tenant, in case users in new named tenants * want to access old global buckets. */ tenant_name = bucket.substr(0, pos); bucket_name = bucket.substr(pos + 1); if (bucket_name.empty()) { return -ERR_INVALID_BUCKET_NAME; } } else { tenant_name = auth_tenant; bucket_name = bucket; } return 0; } int rgw_chown_bucket_and_objects(rgw::sal::Driver* driver, rgw::sal::Bucket* bucket, rgw::sal::User* new_user, const std::string& marker, std::string *err_msg, const DoutPrefixProvider *dpp, optional_yield y) { /* Chown on the bucket */ int ret = bucket->chown(dpp, *new_user, y); if (ret < 0) { set_err_msg(err_msg, "Failed to change object ownership: " + cpp_strerror(-ret)); } /* Now chown on all the objects in the bucket */ map<string, bool> common_prefixes; rgw::sal::Bucket::ListParams params; rgw::sal::Bucket::ListResults results; params.list_versions = true; params.allow_unordered = true; params.marker = marker; int count = 0; int max_entries = 1000; //Loop through objects and update object acls to point to bucket owner do { results.objs.clear(); ret = bucket->list(dpp, params, max_entries, results, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: list objects failed: " << cpp_strerror(-ret) << dendl; return ret; } params.marker = results.next_marker; count += results.objs.size(); for (const auto& obj : results.objs) { std::unique_ptr<rgw::sal::Object> r_obj = bucket->get_object(obj.key); ret = r_obj->chown(*new_user, dpp, y); if (ret < 0) { ldpp_dout(dpp, 0) << "ERROR: chown failed on " << r_obj << " :" << cpp_strerror(-ret) << dendl; return ret; } } cerr << count << " objects processed in " << bucket << ". Next marker " << params.marker.name << std::endl; } while(results.is_truncated); return ret; }
5,216
26.898396
124
cc
null
ceph-main/src/rgw/rgw_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 <string> #include <memory> #include <variant> #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include "include/types.h" #include "rgw_common.h" #include "rgw_sal.h" extern void init_bucket(rgw_bucket *b, const char *t, const char *n, const char *dp, const char *ip, const char *m, const char *id); extern int rgw_bucket_parse_bucket_key(CephContext *cct, const std::string& key, rgw_bucket* bucket, int *shard_id); extern std::string rgw_make_bucket_entry_name(const std::string& tenant_name, const std::string& bucket_name); [[nodiscard]] int rgw_parse_url_bucket(const std::string& bucket, const std::string& auth_tenant, std::string &tenant_name, std::string &bucket_name); extern int rgw_chown_bucket_and_objects(rgw::sal::Driver* driver, rgw::sal::Bucket* bucket, rgw::sal::User* new_user, const std::string& marker, std::string *err_msg, const DoutPrefixProvider *dpp, optional_yield y);
1,295
34.027027
132
h
null
ceph-main/src/rgw/rgw_bucket_encryption.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp // #include "rgw_bucket_encryption.h" #include "rgw_xml.h" #include "common/ceph_json.h" void ApplyServerSideEncryptionByDefault::decode_xml(XMLObj *obj) { RGWXMLDecoder::decode_xml("KMSMasterKeyID", kmsMasterKeyID, obj, false); RGWXMLDecoder::decode_xml("SSEAlgorithm", sseAlgorithm, obj, false); } void ApplyServerSideEncryptionByDefault::dump_xml(Formatter *f) const { encode_xml("SSEAlgorithm", sseAlgorithm, f); if (kmsMasterKeyID != "") { encode_xml("KMSMasterKeyID", kmsMasterKeyID, f); } } void ServerSideEncryptionConfiguration::decode_xml(XMLObj *obj) { RGWXMLDecoder::decode_xml("ApplyServerSideEncryptionByDefault", applyServerSideEncryptionByDefault, obj, false); RGWXMLDecoder::decode_xml("BucketKeyEnabled", bucketKeyEnabled, obj, false); } void ServerSideEncryptionConfiguration::dump_xml(Formatter *f) const { encode_xml("ApplyServerSideEncryptionByDefault", applyServerSideEncryptionByDefault, f); if (bucketKeyEnabled) { encode_xml("BucketKeyEnabled", true, f); } } void RGWBucketEncryptionConfig::decode_xml(XMLObj *obj) { rule_exist = RGWXMLDecoder::decode_xml("Rule", rule, obj); } void RGWBucketEncryptionConfig::dump_xml(Formatter *f) const { if (rule_exist) { encode_xml("Rule", rule, f); } } void RGWBucketEncryptionConfig::dump(Formatter *f) const { encode_json("rule_exist", has_rule(), f); if (has_rule()) { encode_json("sse_algorithm", sse_algorithm(), f); encode_json("kms_master_key_id", kms_master_key_id(), f); encode_json("bucket_key_enabled", bucket_key_enabled(), f); } }
1,677
32.56
114
cc
null
ceph-main/src/rgw/rgw_bucket_encryption.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/types.h> class XMLObj; class ApplyServerSideEncryptionByDefault { std::string kmsMasterKeyID; std::string sseAlgorithm; public: ApplyServerSideEncryptionByDefault() {}; ApplyServerSideEncryptionByDefault(const std::string &algorithm, const std::string &key_id) : kmsMasterKeyID(key_id), sseAlgorithm(algorithm) {}; const std::string& kms_master_key_id() const { return kmsMasterKeyID; } const std::string& sse_algorithm() const { return sseAlgorithm; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(kmsMasterKeyID, bl); encode(sseAlgorithm, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(kmsMasterKeyID, bl); decode(sseAlgorithm, bl); DECODE_FINISH(bl); } void decode_xml(XMLObj *obj); void dump_xml(Formatter *f) const; }; WRITE_CLASS_ENCODER(ApplyServerSideEncryptionByDefault) class ServerSideEncryptionConfiguration { protected: ApplyServerSideEncryptionByDefault applyServerSideEncryptionByDefault; bool bucketKeyEnabled; public: ServerSideEncryptionConfiguration(): bucketKeyEnabled(false) {}; ServerSideEncryptionConfiguration(const std::string &algorithm, const std::string &keyid="", bool enabled = false) : applyServerSideEncryptionByDefault(algorithm, keyid), bucketKeyEnabled(enabled) {} const std::string& kms_master_key_id() const { return applyServerSideEncryptionByDefault.kms_master_key_id(); } const std::string& sse_algorithm() const { return applyServerSideEncryptionByDefault.sse_algorithm(); } bool bucket_key_enabled() const { return bucketKeyEnabled; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(applyServerSideEncryptionByDefault, bl); encode(bucketKeyEnabled, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(applyServerSideEncryptionByDefault, bl); decode(bucketKeyEnabled, bl); DECODE_FINISH(bl); } void decode_xml(XMLObj *obj); void dump_xml(Formatter *f) const; }; WRITE_CLASS_ENCODER(ServerSideEncryptionConfiguration) class RGWBucketEncryptionConfig { protected: bool rule_exist; ServerSideEncryptionConfiguration rule; public: RGWBucketEncryptionConfig(): rule_exist(false) {} RGWBucketEncryptionConfig(const std::string &algorithm, const std::string &keyid = "", bool enabled = false) : rule_exist(true), rule(algorithm, keyid, enabled) {} const std::string& kms_master_key_id() const { return rule.kms_master_key_id(); } const std::string& sse_algorithm() const { return rule.sse_algorithm(); } bool bucket_key_enabled() const { return rule.bucket_key_enabled(); } bool has_rule() const { return rule_exist; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(rule_exist, bl); if (rule_exist) { encode(rule, bl); } ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(rule_exist, bl); if (rule_exist) { decode(rule, bl); } DECODE_FINISH(bl); } void decode_xml(XMLObj *obj); void dump_xml(Formatter *f) const; void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWBucketEncryptionConfig*>& o); }; WRITE_CLASS_ENCODER(RGWBucketEncryptionConfig)
3,562
23.916084
80
h
null
ceph-main/src/rgw/rgw_bucket_layout.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 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. * */ #include <boost/algorithm/string.hpp> #include "rgw_bucket_layout.h" namespace rgw { // BucketIndexType std::string_view to_string(const BucketIndexType& t) { switch (t) { case BucketIndexType::Normal: return "Normal"; case BucketIndexType::Indexless: return "Indexless"; default: return "Unknown"; } } bool parse(std::string_view str, BucketIndexType& t) { if (boost::iequals(str, "Normal")) { t = BucketIndexType::Normal; return true; } if (boost::iequals(str, "Indexless")) { t = BucketIndexType::Indexless; return true; } return false; } void encode_json_impl(const char *name, const BucketIndexType& t, ceph::Formatter *f) { encode_json(name, to_string(t), f); } void decode_json_obj(BucketIndexType& t, JSONObj *obj) { std::string str; decode_json_obj(str, obj); parse(str, t); } // BucketHashType std::string_view to_string(const BucketHashType& t) { switch (t) { case BucketHashType::Mod: return "Mod"; default: return "Unknown"; } } bool parse(std::string_view str, BucketHashType& t) { if (boost::iequals(str, "Mod")) { t = BucketHashType::Mod; return true; } return false; } void encode_json_impl(const char *name, const BucketHashType& t, ceph::Formatter *f) { encode_json(name, to_string(t), f); } void decode_json_obj(BucketHashType& t, JSONObj *obj) { std::string str; decode_json_obj(str, obj); parse(str, t); } // bucket_index_normal_layout void encode(const bucket_index_normal_layout& l, bufferlist& bl, uint64_t f) { ENCODE_START(1, 1, bl); encode(l.num_shards, bl); encode(l.hash_type, bl); ENCODE_FINISH(bl); } void decode(bucket_index_normal_layout& l, bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(l.num_shards, bl); decode(l.hash_type, bl); DECODE_FINISH(bl); } void encode_json_impl(const char *name, const bucket_index_normal_layout& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("num_shards", l.num_shards, f); encode_json("hash_type", l.hash_type, f); f->close_section(); } void decode_json_obj(bucket_index_normal_layout& l, JSONObj *obj) { JSONDecoder::decode_json("num_shards", l.num_shards, obj); JSONDecoder::decode_json("hash_type", l.hash_type, obj); } // bucket_index_layout void encode(const bucket_index_layout& l, bufferlist& bl, uint64_t f) { ENCODE_START(1, 1, bl); encode(l.type, bl); switch (l.type) { case BucketIndexType::Normal: encode(l.normal, bl); break; case BucketIndexType::Indexless: break; } ENCODE_FINISH(bl); } void decode(bucket_index_layout& l, bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(l.type, bl); switch (l.type) { case BucketIndexType::Normal: decode(l.normal, bl); break; case BucketIndexType::Indexless: break; } DECODE_FINISH(bl); } void encode_json_impl(const char *name, const bucket_index_layout& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("type", l.type, f); encode_json("normal", l.normal, f); f->close_section(); } void decode_json_obj(bucket_index_layout& l, JSONObj *obj) { JSONDecoder::decode_json("type", l.type, obj); JSONDecoder::decode_json("normal", l.normal, obj); } // bucket_index_layout_generation void encode(const bucket_index_layout_generation& l, bufferlist& bl, uint64_t f) { ENCODE_START(1, 1, bl); encode(l.gen, bl); encode(l.layout, bl); ENCODE_FINISH(bl); } void decode(bucket_index_layout_generation& l, bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(l.gen, bl); decode(l.layout, bl); DECODE_FINISH(bl); } void encode_json_impl(const char *name, const bucket_index_layout_generation& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("gen", l.gen, f); encode_json("layout", l.layout, f); f->close_section(); } void decode_json_obj(bucket_index_layout_generation& l, JSONObj *obj) { JSONDecoder::decode_json("gen", l.gen, obj); JSONDecoder::decode_json("layout", l.layout, obj); } // BucketLogType std::string_view to_string(const BucketLogType& t) { switch (t) { case BucketLogType::InIndex: return "InIndex"; default: return "Unknown"; } } bool parse(std::string_view str, BucketLogType& t) { if (boost::iequals(str, "InIndex")) { t = BucketLogType::InIndex; return true; } return false; } void encode_json_impl(const char *name, const BucketLogType& t, ceph::Formatter *f) { encode_json(name, to_string(t), f); } void decode_json_obj(BucketLogType& t, JSONObj *obj) { std::string str; decode_json_obj(str, obj); parse(str, t); } // bucket_index_log_layout void encode(const bucket_index_log_layout& l, bufferlist& bl, uint64_t f) { ENCODE_START(1, 1, bl); encode(l.gen, bl); encode(l.layout, bl); ENCODE_FINISH(bl); } void decode(bucket_index_log_layout& l, bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(l.gen, bl); decode(l.layout, bl); DECODE_FINISH(bl); } void encode_json_impl(const char *name, const bucket_index_log_layout& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("gen", l.gen, f); encode_json("layout", l.layout, f); f->close_section(); } void decode_json_obj(bucket_index_log_layout& l, JSONObj *obj) { JSONDecoder::decode_json("gen", l.gen, obj); JSONDecoder::decode_json("layout", l.layout, obj); } // bucket_log_layout void encode(const bucket_log_layout& l, bufferlist& bl, uint64_t f) { ENCODE_START(1, 1, bl); encode(l.type, bl); switch (l.type) { case BucketLogType::InIndex: encode(l.in_index, bl); break; } ENCODE_FINISH(bl); } void decode(bucket_log_layout& l, bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(l.type, bl); switch (l.type) { case BucketLogType::InIndex: decode(l.in_index, bl); break; } DECODE_FINISH(bl); } void encode_json_impl(const char *name, const bucket_log_layout& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("type", l.type, f); if (l.type == BucketLogType::InIndex) { encode_json("in_index", l.in_index, f); } f->close_section(); } void decode_json_obj(bucket_log_layout& l, JSONObj *obj) { JSONDecoder::decode_json("type", l.type, obj); JSONDecoder::decode_json("in_index", l.in_index, obj); } // bucket_log_layout_generation void encode(const bucket_log_layout_generation& l, bufferlist& bl, uint64_t f) { ENCODE_START(1, 1, bl); encode(l.gen, bl); encode(l.layout, bl); ENCODE_FINISH(bl); } void decode(bucket_log_layout_generation& l, bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(l.gen, bl); decode(l.layout, bl); DECODE_FINISH(bl); } void encode_json_impl(const char *name, const bucket_log_layout_generation& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("gen", l.gen, f); encode_json("layout", l.layout, f); f->close_section(); } void decode_json_obj(bucket_log_layout_generation& l, JSONObj *obj) { JSONDecoder::decode_json("gen", l.gen, obj); JSONDecoder::decode_json("layout", l.layout, obj); } // BucketReshardState std::string_view to_string(const BucketReshardState& s) { switch (s) { case BucketReshardState::None: return "None"; case BucketReshardState::InProgress: return "InProgress"; default: return "Unknown"; } } bool parse(std::string_view str, BucketReshardState& s) { if (boost::iequals(str, "None")) { s = BucketReshardState::None; return true; } if (boost::iequals(str, "InProgress")) { s = BucketReshardState::InProgress; return true; } return false; } void encode_json_impl(const char *name, const BucketReshardState& s, ceph::Formatter *f) { encode_json(name, to_string(s), f); } void decode_json_obj(BucketReshardState& s, JSONObj *obj) { std::string str; decode_json_obj(str, obj); parse(str, s); } // BucketLayout void encode(const BucketLayout& l, bufferlist& bl, uint64_t f) { ENCODE_START(2, 1, bl); encode(l.resharding, bl); encode(l.current_index, bl); encode(l.target_index, bl); encode(l.logs, bl); ENCODE_FINISH(bl); } void decode(BucketLayout& l, bufferlist::const_iterator& bl) { DECODE_START(2, bl); decode(l.resharding, bl); decode(l.current_index, bl); decode(l.target_index, bl); if (struct_v < 2) { l.logs.clear(); // initialize the log layout to match the current index layout if (l.current_index.layout.type == BucketIndexType::Normal) { l.logs.push_back(log_layout_from_index(0, l.current_index)); } } else { decode(l.logs, bl); } DECODE_FINISH(bl); } void encode_json_impl(const char *name, const BucketLayout& l, ceph::Formatter *f) { f->open_object_section(name); encode_json("resharding", l.resharding, f); encode_json("current_index", l.current_index, f); if (l.target_index) { encode_json("target_index", *l.target_index, f); } f->open_array_section("logs"); for (const auto& log : l.logs) { encode_json("log", log, f); } f->close_section(); // logs[] f->close_section(); } void decode_json_obj(BucketLayout& l, JSONObj *obj) { JSONDecoder::decode_json("resharding", l.resharding, obj); JSONDecoder::decode_json("current_index", l.current_index, obj); JSONDecoder::decode_json("target_index", l.target_index, obj); JSONDecoder::decode_json("logs", l.logs, obj); } } // namespace rgw
9,706
24.47769
100
cc
null
ceph-main/src/rgw/rgw_bucket_layout.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. * */ /* 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 <optional> #include <string> #include "include/encoding.h" #include "common/ceph_json.h" namespace rgw { enum class BucketIndexType : uint8_t { Normal, // normal hash-based sharded index layout Indexless, // no bucket index, so listing is unsupported }; std::string_view to_string(const BucketIndexType& t); bool parse(std::string_view str, BucketIndexType& t); void encode_json_impl(const char *name, const BucketIndexType& t, ceph::Formatter *f); void decode_json_obj(BucketIndexType& t, JSONObj *obj); inline std::ostream& operator<<(std::ostream& out, const BucketIndexType& t) { return out << to_string(t); } enum class BucketHashType : uint8_t { Mod, // rjenkins hash of object name, modulo num_shards }; std::string_view to_string(const BucketHashType& t); bool parse(std::string_view str, BucketHashType& t); void encode_json_impl(const char *name, const BucketHashType& t, ceph::Formatter *f); void decode_json_obj(BucketHashType& t, JSONObj *obj); struct bucket_index_normal_layout { uint32_t num_shards = 1; BucketHashType hash_type = BucketHashType::Mod; friend std::ostream& operator<<(std::ostream& out, const bucket_index_normal_layout& l) { out << "num_shards=" << l.num_shards << ", hash_type=" << to_string(l.hash_type); return out; } }; inline bool operator==(const bucket_index_normal_layout& l, const bucket_index_normal_layout& r) { return l.num_shards == r.num_shards && l.hash_type == r.hash_type; } inline bool operator!=(const bucket_index_normal_layout& l, const bucket_index_normal_layout& r) { return !(l == r); } void encode(const bucket_index_normal_layout& l, bufferlist& bl, uint64_t f=0); void decode(bucket_index_normal_layout& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const bucket_index_normal_layout& l, ceph::Formatter *f); void decode_json_obj(bucket_index_normal_layout& l, JSONObj *obj); struct bucket_index_layout { BucketIndexType type = BucketIndexType::Normal; // TODO: variant of layout types? bucket_index_normal_layout normal; friend std::ostream& operator<<(std::ostream& out, const bucket_index_layout& l) { out << "type=" << to_string(l.type) << ", normal=" << l.normal; return out; } }; inline bool operator==(const bucket_index_layout& l, const bucket_index_layout& r) { return l.type == r.type && l.normal == r.normal; } inline bool operator!=(const bucket_index_layout& l, const bucket_index_layout& r) { return !(l == r); } void encode(const bucket_index_layout& l, bufferlist& bl, uint64_t f=0); void decode(bucket_index_layout& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const bucket_index_layout& l, ceph::Formatter *f); void decode_json_obj(bucket_index_layout& l, JSONObj *obj); struct bucket_index_layout_generation { uint64_t gen = 0; bucket_index_layout layout; friend std::ostream& operator<<(std::ostream& out, const bucket_index_layout_generation& g) { out << "gen=" << g.gen; return out; } }; inline bool operator==(const bucket_index_layout_generation& l, const bucket_index_layout_generation& r) { return l.gen == r.gen && l.layout == r.layout; } inline bool operator!=(const bucket_index_layout_generation& l, const bucket_index_layout_generation& r) { return !(l == r); } void encode(const bucket_index_layout_generation& l, bufferlist& bl, uint64_t f=0); void decode(bucket_index_layout_generation& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const bucket_index_layout_generation& l, ceph::Formatter *f); void decode_json_obj(bucket_index_layout_generation& l, JSONObj *obj); enum class BucketLogType : uint8_t { // colocated with bucket index, so the log layout matches the index layout InIndex, }; std::string_view to_string(const BucketLogType& t); bool parse(std::string_view str, BucketLogType& t); void encode_json_impl(const char *name, const BucketLogType& t, ceph::Formatter *f); void decode_json_obj(BucketLogType& t, JSONObj *obj); inline std::ostream& operator<<(std::ostream& out, const BucketLogType &log_type) { switch (log_type) { case BucketLogType::InIndex: return out << "InIndex"; default: return out << "Unknown"; } } struct bucket_index_log_layout { uint64_t gen = 0; bucket_index_normal_layout layout; operator bucket_index_layout_generation() const { bucket_index_layout_generation bilg; bilg.gen = gen; bilg.layout.type = BucketIndexType::Normal; bilg.layout.normal = layout; return bilg; } }; void encode(const bucket_index_log_layout& l, bufferlist& bl, uint64_t f=0); void decode(bucket_index_log_layout& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const bucket_index_log_layout& l, ceph::Formatter *f); void decode_json_obj(bucket_index_log_layout& l, JSONObj *obj); struct bucket_log_layout { BucketLogType type = BucketLogType::InIndex; bucket_index_log_layout in_index; friend std::ostream& operator<<(std::ostream& out, const bucket_log_layout& l) { out << "type=" << to_string(l.type); return out; } }; void encode(const bucket_log_layout& l, bufferlist& bl, uint64_t f=0); void decode(bucket_log_layout& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const bucket_log_layout& l, ceph::Formatter *f); void decode_json_obj(bucket_log_layout& l, JSONObj *obj); struct bucket_log_layout_generation { uint64_t gen = 0; bucket_log_layout layout; friend std::ostream& operator<<(std::ostream& out, const bucket_log_layout_generation& g) { out << "gen=" << g.gen << ", layout=[ " << g.layout << " ]"; return out; } }; void encode(const bucket_log_layout_generation& l, bufferlist& bl, uint64_t f=0); void decode(bucket_log_layout_generation& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const bucket_log_layout_generation& l, ceph::Formatter *f); void decode_json_obj(bucket_log_layout_generation& l, JSONObj *obj); // return a log layout that shares its layout with the index inline bucket_log_layout_generation log_layout_from_index( uint64_t gen, const bucket_index_layout_generation& index) { return {gen, {BucketLogType::InIndex, {index.gen, index.layout.normal}}}; } inline auto matches_gen(uint64_t gen) { return [gen] (const bucket_log_layout_generation& l) { return l.gen == gen; }; } inline bucket_index_layout_generation log_to_index_layout(const bucket_log_layout_generation& log_layout) { ceph_assert(log_layout.layout.type == BucketLogType::InIndex); bucket_index_layout_generation index; index.gen = log_layout.layout.in_index.gen; index.layout.normal = log_layout.layout.in_index.layout; return index; } enum class BucketReshardState : uint8_t { None, InProgress, }; std::string_view to_string(const BucketReshardState& s); bool parse(std::string_view str, BucketReshardState& s); void encode_json_impl(const char *name, const BucketReshardState& s, ceph::Formatter *f); void decode_json_obj(BucketReshardState& s, JSONObj *obj); // describes the layout of bucket index objects struct BucketLayout { BucketReshardState resharding = BucketReshardState::None; // current bucket index layout bucket_index_layout_generation current_index; // target index layout of a resharding operation std::optional<bucket_index_layout_generation> target_index; // history of untrimmed bucket log layout generations, with the current // generation at the back() std::vector<bucket_log_layout_generation> logs; friend std::ostream& operator<<(std::ostream& out, const BucketLayout& l) { std::stringstream ss; if (l.target_index) { ss << *l.target_index; } else { ss << "none"; } out << "resharding=" << to_string(l.resharding) << ", current_index=[" << l.current_index << "], target_index=[" << ss.str() << "], logs.size()=" << l.logs.size(); return out; } }; void encode(const BucketLayout& l, bufferlist& bl, uint64_t f=0); void decode(BucketLayout& l, bufferlist::const_iterator& bl); void encode_json_impl(const char *name, const BucketLayout& l, ceph::Formatter *f); void decode_json_obj(BucketLayout& l, JSONObj *obj); inline uint32_t num_shards(const bucket_index_normal_layout& index) { // old buckets used num_shards=0 to mean 1 return index.num_shards > 0 ? index.num_shards : 1; } inline uint32_t num_shards(const bucket_index_layout& index) { ceph_assert(index.type == BucketIndexType::Normal); return num_shards(index.normal); } inline uint32_t num_shards(const bucket_index_layout_generation& index) { return num_shards(index.layout); } inline uint32_t current_num_shards(const BucketLayout& layout) { return num_shards(layout.current_index); } inline bool is_layout_indexless(const bucket_index_layout_generation& layout) { return layout.layout.type == BucketIndexType::Indexless; } } // namespace rgw
9,694
33.257951
105
h
null
ceph-main/src/rgw/rgw_bucket_sync_cache.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 <boost/smart_ptr/intrusive_ref_counter.hpp> #include "common/intrusive_lru.h" #include "rgw_data_sync.h" namespace rgw::bucket_sync { // per bucket-shard state cached by DataSyncShardCR struct State { // the source bucket shard to sync std::pair<rgw_bucket_shard, std::optional<uint64_t>> key; // current sync obligation being processed by DataSyncSingleEntry std::optional<rgw_data_sync_obligation> obligation; // incremented with each new obligation uint32_t counter = 0; // highest timestamp applied by all sources ceph::real_time progress_timestamp; State(const std::pair<rgw_bucket_shard, std::optional<uint64_t>>& key ) noexcept : key(key) {} State(const rgw_bucket_shard& shard, std::optional<uint64_t> gen) noexcept : key(shard, gen) {} }; struct Entry; struct EntryToKey; class Handle; using lru_config = ceph::common::intrusive_lru_config< std::pair<rgw_bucket_shard, std::optional<uint64_t>>, Entry, EntryToKey>; // a recyclable cache entry struct Entry : State, ceph::common::intrusive_lru_base<lru_config> { using State::State; }; struct EntryToKey { using type = std::pair<rgw_bucket_shard, std::optional<uint64_t>>; const type& operator()(const Entry& e) { return e.key; } }; // use a non-atomic reference count since these aren't shared across threads template <typename T> using thread_unsafe_ref_counter = boost::intrusive_ref_counter< T, boost::thread_unsafe_counter>; // a state cache for entries within a single datalog shard class Cache : public thread_unsafe_ref_counter<Cache> { ceph::common::intrusive_lru<lru_config> cache; protected: // protected ctor to enforce the use of factory function create() explicit Cache(size_t target_size) { cache.set_target_size(target_size); } public: static boost::intrusive_ptr<Cache> create(size_t target_size) { return new Cache(target_size); } // find or create a cache entry for the given key, and return a Handle that // keeps it lru-pinned until destruction Handle get(const rgw_bucket_shard& shard, std::optional<uint64_t> gen); }; // a State handle that keeps the Cache referenced class Handle { boost::intrusive_ptr<Cache> cache; boost::intrusive_ptr<Entry> entry; public: Handle() noexcept = default; ~Handle() = default; Handle(boost::intrusive_ptr<Cache> cache, boost::intrusive_ptr<Entry> entry) noexcept : cache(std::move(cache)), entry(std::move(entry)) {} Handle(Handle&&) = default; Handle(const Handle&) = default; Handle& operator=(Handle&& o) noexcept { // move the entry first so that its cache stays referenced over destruction entry = std::move(o.entry); cache = std::move(o.cache); return *this; } Handle& operator=(const Handle& o) noexcept { // copy the entry first so that its cache stays referenced over destruction entry = o.entry; cache = o.cache; return *this; } explicit operator bool() const noexcept { return static_cast<bool>(entry); } State& operator*() const noexcept { return *entry; } State* operator->() const noexcept { return entry.get(); } }; inline Handle Cache::get(const rgw_bucket_shard& shard, std::optional<uint64_t> gen) { auto result = cache.get_or_create({ shard, gen }); return {this, std::move(result.first)}; } } // namespace rgw::bucket_sync
3,750
31.059829
84
h
null
ceph-main/src/rgw/rgw_bucket_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_user_types.h" #include "rgw_placement_types.h" #include "common/dout.h" #include "common/Formatter.h" struct cls_user_bucket; struct rgw_bucket_key { std::string tenant; std::string name; std::string bucket_id; rgw_bucket_key(const std::string& _tenant, const std::string& _name, const std::string& _bucket_id) : tenant(_tenant), name(_name), bucket_id(_bucket_id) {} rgw_bucket_key(const std::string& _tenant, const std::string& _name) : tenant(_tenant), name(_name) {} }; struct rgw_bucket { std::string tenant; std::string name; std::string marker; std::string bucket_id; rgw_data_placement_target explicit_placement; rgw_bucket() { } // cppcheck-suppress noExplicitConstructor explicit rgw_bucket(const rgw_user& u, const cls_user_bucket& b); rgw_bucket(const std::string& _tenant, const std::string& _name, const std::string& _bucket_id) : tenant(_tenant), name(_name), bucket_id(_bucket_id) {} rgw_bucket(const rgw_bucket_key& bk) : tenant(bk.tenant), name(bk.name), bucket_id(bk.bucket_id) {} rgw_bucket(const rgw_bucket&) = default; rgw_bucket(rgw_bucket&&) = default; bool match(const rgw_bucket& b) const { return (tenant == b.tenant && name == b.name && (bucket_id == b.bucket_id || bucket_id.empty() || b.bucket_id.empty())); } void convert(cls_user_bucket *b) const; void encode(ceph::buffer::list& bl) const { ENCODE_START(10, 10, bl); encode(name, bl); encode(marker, bl); encode(bucket_id, bl); encode(tenant, bl); bool encode_explicit = !explicit_placement.data_pool.empty(); encode(encode_explicit, bl); if (encode_explicit) { encode(explicit_placement.data_pool, bl); encode(explicit_placement.data_extra_pool, bl); encode(explicit_placement.index_pool, bl); } ENCODE_FINISH(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) { decode(explicit_placement.data_pool.name, bl); } if (struct_v >= 2) { decode(marker, bl); if (struct_v <= 3) { uint64_t id; decode(id, bl); char buf[16]; snprintf(buf, sizeof(buf), "%" PRIu64, id); bucket_id = buf; } else { decode(bucket_id, bl); } } if (struct_v < 10) { if (struct_v >= 5) { decode(explicit_placement.index_pool.name, bl); } else { explicit_placement.index_pool = explicit_placement.data_pool; } if (struct_v >= 7) { decode(explicit_placement.data_extra_pool.name, bl); } } if (struct_v >= 8) { decode(tenant, bl); } if (struct_v >= 10) { bool decode_explicit = !explicit_placement.data_pool.empty(); decode(decode_explicit, bl); if (decode_explicit) { decode(explicit_placement.data_pool, bl); decode(explicit_placement.data_extra_pool, bl); decode(explicit_placement.index_pool, bl); } } DECODE_FINISH(bl); } void update_bucket_id(const std::string& new_bucket_id) { bucket_id = new_bucket_id; } // format a key for the bucket/instance. pass delim=0 to skip a field std::string get_key(char tenant_delim = '/', char id_delim = ':', size_t reserve = 0) const; const rgw_pool& get_data_extra_pool() const { return explicit_placement.get_data_extra_pool(); } void dump(ceph::Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<rgw_bucket*>& o); rgw_bucket& operator=(const rgw_bucket&) = default; bool operator<(const rgw_bucket& b) const { if (tenant < b.tenant) { return true; } else if (tenant > b.tenant) { return false; } if (name < b.name) { return true; } else if (name > b.name) { return false; } return (bucket_id < b.bucket_id); } bool operator==(const rgw_bucket& b) const { return (tenant == b.tenant) && (name == b.name) && \ (bucket_id == b.bucket_id); } bool operator!=(const rgw_bucket& b) const { return (tenant != b.tenant) || (name != b.name) || (bucket_id != b.bucket_id); } }; WRITE_CLASS_ENCODER(rgw_bucket) inline std::ostream& operator<<(std::ostream& out, const rgw_bucket &b) { out << b.tenant << ":" << b.name << "[" << b.bucket_id << "])"; return out; } struct rgw_bucket_placement { rgw_placement_rule placement_rule; rgw_bucket bucket; void dump(Formatter *f) const; }; /* rgw_bucket_placement */ struct rgw_bucket_shard { rgw_bucket bucket; int shard_id; rgw_bucket_shard() : shard_id(-1) {} rgw_bucket_shard(const rgw_bucket& _b, int _sid) : bucket(_b), shard_id(_sid) {} std::string get_key(char tenant_delim = '/', char id_delim = ':', char shard_delim = ':', size_t reserve = 0) const; bool operator<(const rgw_bucket_shard& b) const { if (bucket < b.bucket) { return true; } if (b.bucket < bucket) { return false; } return shard_id < b.shard_id; } bool operator==(const rgw_bucket_shard& b) const { return (bucket == b.bucket && shard_id == b.shard_id); } }; /* rgw_bucket_shard */ void encode(const rgw_bucket_shard& b, bufferlist& bl, uint64_t f=0); void decode(rgw_bucket_shard& b, bufferlist::const_iterator& bl); inline std::ostream& operator<<(std::ostream& out, const rgw_bucket_shard& bs) { if (bs.shard_id <= 0) { return out << bs.bucket; } return out << bs.bucket << ":" << bs.shard_id; }
6,688
27.58547
82
h
null
ceph-main/src/rgw/rgw_cache.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_cache.h" #include "rgw_perf_counters.h" #include <errno.h> #define dout_subsys ceph_subsys_rgw using namespace std; int ObjectCache::get(const DoutPrefixProvider *dpp, const string& name, ObjectCacheInfo& info, uint32_t mask, rgw_cache_entry_info *cache_info) { std::shared_lock rl{lock}; std::unique_lock wl{lock, std::defer_lock}; // may be promoted to write lock if (!enabled) { return -ENOENT; } auto iter = cache_map.find(name); if (iter == cache_map.end()) { ldpp_dout(dpp, 10) << "cache get: name=" << name << " : miss" << dendl; if (perfcounter) { perfcounter->inc(l_rgw_cache_miss); } return -ENOENT; } if (expiry.count() && (ceph::coarse_mono_clock::now() - iter->second.info.time_added) > expiry) { ldpp_dout(dpp, 10) << "cache get: name=" << name << " : expiry miss" << dendl; rl.unlock(); wl.lock(); // write lock for expiration // check that wasn't already removed by other thread iter = cache_map.find(name); if (iter != cache_map.end()) { for (auto &kv : iter->second.chained_entries) kv.first->invalidate(kv.second); remove_lru(name, iter->second.lru_iter); cache_map.erase(iter); } if (perfcounter) { perfcounter->inc(l_rgw_cache_miss); } return -ENOENT; } ObjectCacheEntry *entry = &iter->second; if (lru_counter - entry->lru_promotion_ts > lru_window) { ldpp_dout(dpp, 20) << "cache get: touching lru, lru_counter=" << lru_counter << " promotion_ts=" << entry->lru_promotion_ts << dendl; rl.unlock(); wl.lock(); // write lock for touch_lru() /* need to redo this because entry might have dropped off the cache */ iter = cache_map.find(name); if (iter == cache_map.end()) { ldpp_dout(dpp, 10) << "lost race! cache get: name=" << name << " : miss" << dendl; if(perfcounter) perfcounter->inc(l_rgw_cache_miss); return -ENOENT; } entry = &iter->second; /* check again, we might have lost a race here */ if (lru_counter - entry->lru_promotion_ts > lru_window) { touch_lru(dpp, name, *entry, iter->second.lru_iter); } } ObjectCacheInfo& src = iter->second.info; if(src.status == -ENOENT) { ldpp_dout(dpp, 10) << "cache get: name=" << name << " : hit (negative entry)" << dendl; if (perfcounter) perfcounter->inc(l_rgw_cache_hit); return -ENODATA; } if ((src.flags & mask) != mask) { ldpp_dout(dpp, 10) << "cache get: name=" << name << " : type miss (requested=0x" << std::hex << mask << ", cached=0x" << src.flags << std::dec << ")" << dendl; if(perfcounter) perfcounter->inc(l_rgw_cache_miss); return -ENOENT; } ldpp_dout(dpp, 10) << "cache get: name=" << name << " : hit (requested=0x" << std::hex << mask << ", cached=0x" << src.flags << std::dec << ")" << dendl; info = src; if (cache_info) { cache_info->cache_locator = name; cache_info->gen = entry->gen; } if(perfcounter) perfcounter->inc(l_rgw_cache_hit); return 0; } bool ObjectCache::chain_cache_entry(const DoutPrefixProvider *dpp, std::initializer_list<rgw_cache_entry_info*> cache_info_entries, RGWChainedCache::Entry *chained_entry) { std::unique_lock l{lock}; if (!enabled) { return false; } std::vector<ObjectCacheEntry*> entries; entries.reserve(cache_info_entries.size()); /* first verify that all entries are still valid */ for (auto cache_info : cache_info_entries) { ldpp_dout(dpp, 10) << "chain_cache_entry: cache_locator=" << cache_info->cache_locator << dendl; auto iter = cache_map.find(cache_info->cache_locator); if (iter == cache_map.end()) { ldpp_dout(dpp, 20) << "chain_cache_entry: couldn't find cache locator" << dendl; return false; } auto entry = &iter->second; if (entry->gen != cache_info->gen) { ldpp_dout(dpp, 20) << "chain_cache_entry: entry.gen (" << entry->gen << ") != cache_info.gen (" << cache_info->gen << ")" << dendl; return false; } entries.push_back(entry); } chained_entry->cache->chain_cb(chained_entry->key, chained_entry->data); for (auto entry : entries) { entry->chained_entries.push_back(make_pair(chained_entry->cache, chained_entry->key)); } return true; } void ObjectCache::put(const DoutPrefixProvider *dpp, const string& name, ObjectCacheInfo& info, rgw_cache_entry_info *cache_info) { std::unique_lock l{lock}; if (!enabled) { return; } ldpp_dout(dpp, 10) << "cache put: name=" << name << " info.flags=0x" << std::hex << info.flags << std::dec << dendl; auto [iter, inserted] = cache_map.emplace(name, ObjectCacheEntry{}); ObjectCacheEntry& entry = iter->second; entry.info.time_added = ceph::coarse_mono_clock::now(); if (inserted) { entry.lru_iter = lru.end(); } ObjectCacheInfo& target = entry.info; invalidate_lru(entry); entry.chained_entries.clear(); entry.gen++; touch_lru(dpp, name, entry, entry.lru_iter); target.status = info.status; if (info.status < 0) { target.flags = 0; target.xattrs.clear(); target.data.clear(); return; } if (cache_info) { cache_info->cache_locator = name; cache_info->gen = entry.gen; } // put() must include the latest version if we're going to keep caching it target.flags &= ~CACHE_FLAG_OBJV; target.flags |= info.flags; if (info.flags & CACHE_FLAG_META) target.meta = info.meta; else if (!(info.flags & CACHE_FLAG_MODIFY_XATTRS)) target.flags &= ~CACHE_FLAG_META; // non-meta change should reset meta if (info.flags & CACHE_FLAG_XATTRS) { target.xattrs = info.xattrs; map<string, bufferlist>::iterator iter; for (iter = target.xattrs.begin(); iter != target.xattrs.end(); ++iter) { ldpp_dout(dpp, 10) << "updating xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl; } } else if (info.flags & CACHE_FLAG_MODIFY_XATTRS) { map<string, bufferlist>::iterator iter; for (iter = info.rm_xattrs.begin(); iter != info.rm_xattrs.end(); ++iter) { ldpp_dout(dpp, 10) << "removing xattr: name=" << iter->first << dendl; target.xattrs.erase(iter->first); } for (iter = info.xattrs.begin(); iter != info.xattrs.end(); ++iter) { ldpp_dout(dpp, 10) << "appending xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl; target.xattrs[iter->first] = iter->second; } } if (info.flags & CACHE_FLAG_DATA) target.data = info.data; if (info.flags & CACHE_FLAG_OBJV) target.version = info.version; } // WARNING: This function /must not/ be modified to cache a // negative lookup. It must only invalidate. bool ObjectCache::invalidate_remove(const DoutPrefixProvider *dpp, const string& name) { std::unique_lock l{lock}; if (!enabled) { return false; } auto iter = cache_map.find(name); if (iter == cache_map.end()) return false; ldpp_dout(dpp, 10) << "removing " << name << " from cache" << dendl; ObjectCacheEntry& entry = iter->second; for (auto& kv : entry.chained_entries) { kv.first->invalidate(kv.second); } remove_lru(name, iter->second.lru_iter); cache_map.erase(iter); return true; } void ObjectCache::touch_lru(const DoutPrefixProvider *dpp, const string& name, ObjectCacheEntry& entry, std::list<string>::iterator& lru_iter) { while (lru_size > (size_t)cct->_conf->rgw_cache_lru_size) { auto iter = lru.begin(); if ((*iter).compare(name) == 0) { /* * if the entry we're touching happens to be at the lru end, don't remove it, * lru shrinking can wait for next time */ break; } auto map_iter = cache_map.find(*iter); ldout(cct, 10) << "removing entry: name=" << *iter << " from cache LRU" << dendl; if (map_iter != cache_map.end()) { ObjectCacheEntry& entry = map_iter->second; invalidate_lru(entry); cache_map.erase(map_iter); } lru.pop_front(); lru_size--; } if (lru_iter == lru.end()) { lru.push_back(name); lru_size++; lru_iter--; ldpp_dout(dpp, 10) << "adding " << name << " to cache LRU end" << dendl; } else { ldpp_dout(dpp, 10) << "moving " << name << " to cache LRU end" << dendl; lru.erase(lru_iter); lru.push_back(name); lru_iter = lru.end(); --lru_iter; } lru_counter++; entry.lru_promotion_ts = lru_counter; } void ObjectCache::remove_lru(const string& name, std::list<string>::iterator& lru_iter) { if (lru_iter == lru.end()) return; lru.erase(lru_iter); lru_size--; lru_iter = lru.end(); } void ObjectCache::invalidate_lru(ObjectCacheEntry& entry) { for (auto iter = entry.chained_entries.begin(); iter != entry.chained_entries.end(); ++iter) { RGWChainedCache *chained_cache = iter->first; chained_cache->invalidate(iter->second); } } void ObjectCache::set_enabled(bool status) { std::unique_lock l{lock}; enabled = status; if (!enabled) { do_invalidate_all(); } } void ObjectCache::invalidate_all() { std::unique_lock l{lock}; do_invalidate_all(); } void ObjectCache::do_invalidate_all() { cache_map.clear(); lru.clear(); lru_size = 0; lru_counter = 0; lru_window = 0; for (auto& cache : chained_cache) { cache->invalidate_all(); } } void ObjectCache::chain_cache(RGWChainedCache *cache) { std::unique_lock l{lock}; chained_cache.push_back(cache); } void ObjectCache::unchain_cache(RGWChainedCache *cache) { std::unique_lock l{lock}; auto iter = chained_cache.begin(); for (; iter != chained_cache.end(); ++iter) { if (cache == *iter) { chained_cache.erase(iter); cache->unregistered(); return; } } } ObjectCache::~ObjectCache() { for (auto cache : chained_cache) { cache->unregistered(); } } void ObjectMetaInfo::generate_test_instances(list<ObjectMetaInfo*>& o) { ObjectMetaInfo *m = new ObjectMetaInfo; m->size = 1024 * 1024; o.push_back(m); o.push_back(new ObjectMetaInfo); } void ObjectMetaInfo::dump(Formatter *f) const { encode_json("size", size, f); encode_json("mtime", utime_t(mtime), f); } void ObjectCacheInfo::generate_test_instances(list<ObjectCacheInfo*>& o) { using ceph::encode; ObjectCacheInfo *i = new ObjectCacheInfo; i->status = 0; i->flags = CACHE_FLAG_MODIFY_XATTRS; string s = "this is a string"; string s2 = "this is a another string"; bufferlist data, data2; encode(s, data); encode(s2, data2); i->data = data; i->xattrs["x1"] = data; i->xattrs["x2"] = data2; i->rm_xattrs["r2"] = data2; i->rm_xattrs["r3"] = data; i->meta.size = 512 * 1024; o.push_back(i); o.push_back(new ObjectCacheInfo); } void ObjectCacheInfo::dump(Formatter *f) const { encode_json("status", status, f); encode_json("flags", flags, f); encode_json("data", data, f); encode_json_map("xattrs", "name", "value", "length", xattrs, f); encode_json_map("rm_xattrs", "name", "value", "length", rm_xattrs, f); encode_json("meta", meta, f); } void RGWCacheNotifyInfo::generate_test_instances(list<RGWCacheNotifyInfo*>& o) { o.push_back(new RGWCacheNotifyInfo); } void RGWCacheNotifyInfo::dump(Formatter *f) const { encode_json("op", op, f); encode_json("obj", obj, f); encode_json("obj_info", obj_info, f); encode_json("ofs", ofs, f); encode_json("ns", ns, f); }
11,630
26.692857
143
cc
null
ceph-main/src/rgw/rgw_cache.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 <unordered_map> #include "include/types.h" #include "include/utime.h" #include "include/ceph_assert.h" #include "common/ceph_mutex.h" #include "cls/version/cls_version_types.h" #include "rgw_common.h" enum { UPDATE_OBJ, INVALIDATE_OBJ, }; #define CACHE_FLAG_DATA 0x01 #define CACHE_FLAG_XATTRS 0x02 #define CACHE_FLAG_META 0x04 #define CACHE_FLAG_MODIFY_XATTRS 0x08 #define CACHE_FLAG_OBJV 0x10 struct ObjectMetaInfo { uint64_t size; real_time mtime; ObjectMetaInfo() : size(0) {} void encode(bufferlist& bl) const { ENCODE_START(2, 2, bl); encode(size, bl); encode(mtime, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl); decode(size, bl); decode(mtime, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<ObjectMetaInfo*>& o); }; WRITE_CLASS_ENCODER(ObjectMetaInfo) struct ObjectCacheInfo { int status = 0; uint32_t flags = 0; uint64_t epoch = 0; bufferlist data; std::map<std::string, bufferlist> xattrs; std::map<std::string, bufferlist> rm_xattrs; ObjectMetaInfo meta; obj_version version = {}; ceph::coarse_mono_time time_added; ObjectCacheInfo() = default; void encode(bufferlist& bl) const { ENCODE_START(5, 3, bl); encode(status, bl); encode(flags, bl); encode(data, bl); encode(xattrs, bl); encode(meta, bl); encode(rm_xattrs, bl); encode(epoch, bl); encode(version, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(5, 3, 3, bl); decode(status, bl); decode(flags, bl); decode(data, bl); decode(xattrs, bl); decode(meta, bl); if (struct_v >= 2) decode(rm_xattrs, bl); if (struct_v >= 4) decode(epoch, bl); if (struct_v >= 5) decode(version, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<ObjectCacheInfo*>& o); }; WRITE_CLASS_ENCODER(ObjectCacheInfo) struct RGWCacheNotifyInfo { uint32_t op; rgw_raw_obj obj; ObjectCacheInfo obj_info; off_t ofs; std::string ns; RGWCacheNotifyInfo() : op(0), ofs(0) {} void encode(bufferlist& obl) const { ENCODE_START(2, 2, obl); encode(op, obl); encode(obj, obl); encode(obj_info, obl); encode(ofs, obl); encode(ns, obl); ENCODE_FINISH(obl); } void decode(bufferlist::const_iterator& ibl) { DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, ibl); decode(op, ibl); decode(obj, ibl); decode(obj_info, ibl); decode(ofs, ibl); decode(ns, ibl); DECODE_FINISH(ibl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWCacheNotifyInfo*>& o); }; WRITE_CLASS_ENCODER(RGWCacheNotifyInfo) inline std::ostream& operator <<(std::ostream& m, const RGWCacheNotifyInfo& cni) { return m << "[op: " << cni.op << ", obj: " << cni.obj << ", ofs" << cni.ofs << ", ns" << cni.ns << "]"; } class RGWChainedCache { public: virtual ~RGWChainedCache() {} virtual void chain_cb(const std::string& key, void *data) = 0; virtual void invalidate(const std::string& key) = 0; virtual void invalidate_all() = 0; virtual void unregistered() {} struct Entry { RGWChainedCache *cache; const std::string& key; void *data; Entry(RGWChainedCache *_c, const std::string& _k, void *_d) : cache(_c), key(_k), data(_d) {} }; }; struct ObjectCacheEntry { ObjectCacheInfo info; std::list<std::string>::iterator lru_iter; uint64_t lru_promotion_ts; uint64_t gen; std::vector<std::pair<RGWChainedCache *, std::string> > chained_entries; ObjectCacheEntry() : lru_promotion_ts(0), gen(0) {} }; class ObjectCache { std::unordered_map<std::string, ObjectCacheEntry> cache_map; std::list<std::string> lru; unsigned long lru_size; unsigned long lru_counter; unsigned long lru_window; ceph::shared_mutex lock = ceph::make_shared_mutex("ObjectCache"); CephContext *cct; std::vector<RGWChainedCache *> chained_cache; bool enabled; ceph::timespan expiry; void touch_lru(const DoutPrefixProvider *dpp, const std::string& name, ObjectCacheEntry& entry, std::list<std::string>::iterator& lru_iter); void remove_lru(const std::string& name, std::list<std::string>::iterator& lru_iter); void invalidate_lru(ObjectCacheEntry& entry); void do_invalidate_all(); public: ObjectCache() : lru_size(0), lru_counter(0), lru_window(0), cct(NULL), enabled(false) { } ~ObjectCache(); int get(const DoutPrefixProvider *dpp, const std::string& name, ObjectCacheInfo& bl, uint32_t mask, rgw_cache_entry_info *cache_info); std::optional<ObjectCacheInfo> get(const DoutPrefixProvider *dpp, const std::string& name) { std::optional<ObjectCacheInfo> info{std::in_place}; auto r = get(dpp, name, *info, 0, nullptr); return r < 0 ? std::nullopt : info; } template<typename F> void for_each(const F& f) { std::shared_lock l{lock}; if (enabled) { auto now = ceph::coarse_mono_clock::now(); for (const auto& [name, entry] : cache_map) { if (expiry.count() && (now - entry.info.time_added) < expiry) { f(name, entry); } } } } void put(const DoutPrefixProvider *dpp, const std::string& name, ObjectCacheInfo& bl, rgw_cache_entry_info *cache_info); bool invalidate_remove(const DoutPrefixProvider *dpp, const std::string& name); void set_ctx(CephContext *_cct) { cct = _cct; lru_window = cct->_conf->rgw_cache_lru_size / 2; expiry = std::chrono::seconds(cct->_conf.get_val<uint64_t>( "rgw_cache_expiry_interval")); } bool chain_cache_entry(const DoutPrefixProvider *dpp, std::initializer_list<rgw_cache_entry_info*> cache_info_entries, RGWChainedCache::Entry *chained_entry); void set_enabled(bool status); void chain_cache(RGWChainedCache *cache); void unchain_cache(RGWChainedCache *cache); void invalidate_all(); };
6,247
27.017937
136
h
null
ceph-main/src/rgw/rgw_client_io.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "rgw_client_io.h" #include "rgw_crypt.h" #include "rgw_crypt_sanitize.h" #define dout_subsys ceph_subsys_rgw namespace rgw { namespace io { [[nodiscard]] int BasicClient::init(CephContext *cct) { int init_error = init_env(cct); if (init_error != 0) return init_error; if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) { const auto& env_map = get_env().get_map(); for (const auto& iter: env_map) { rgw::crypt_sanitize::env x{iter.first, iter.second}; ldout(cct, 20) << iter.first << "=" << (x) << dendl; } } return init_error; } } /* namespace io */ } /* namespace rgw */
801
21.914286
70
cc
null
ceph-main/src/rgw/rgw_client_io.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 <exception> #include <string> #include <string_view> #include <streambuf> #include <istream> #include <stdlib.h> #include <system_error> #include "include/types.h" #include "rgw_common.h" class RGWRestfulIO; namespace rgw { namespace io { using Exception = std::system_error; /* The minimal and simplest subset of methods that a client of RadosGW can be * interacted with. */ class BasicClient { protected: virtual int init_env(CephContext *cct) = 0; public: virtual ~BasicClient() = default; /* Initialize the BasicClient and inject CephContext. */ int init(CephContext *cct); /* Return the RGWEnv describing the environment that a given request lives in. * The method does not throw exceptions. */ virtual RGWEnv& get_env() noexcept = 0; /* Complete request. * On success returns number of bytes generated for a direct client of RadosGW. * On failure throws rgw::io::Exception containing errno. */ virtual size_t complete_request() = 0; }; /* rgw::io::Client */ class Accounter { public: virtual ~Accounter() = default; /* Enable or disable the accounting of both sent and received data. Changing * the state does not affect the counters. */ virtual void set_account(bool enabled) = 0; /* Return number of bytes sent to a direct client of RadosGW (direct means * eg. a web server instance in the case of using FastCGI front-end) when * the accounting was enabled. */ virtual uint64_t get_bytes_sent() const = 0; /* Return number of bytes received from a direct client of RadosGW (direct * means eg. a web server instance in the case of using FastCGI front-end) * when the accounting was enabled. */ virtual uint64_t get_bytes_received() const = 0; }; /* rgw::io::Accounter */ /* Interface abstracting restful interactions with clients, usually through * the HTTP protocol. The methods participating in the response generation * process should be called in the specific order: * 1. send_100_continue() - at most once, * 2. send_status() - exactly once, * 3. Any of: * a. send_header(), * b. send_content_length() XOR send_chunked_transfer_encoding() * Please note that only one of those two methods must be called at most once. * 4. complete_header() - exactly once, * 5. send_body() * 6. complete_request() - exactly once. * There are no restrictions on flush() - it may be called in any moment. * * Receiving data from a client isn't a subject to any further call order * restrictions besides those imposed by BasicClient. That is, get_env() * and recv_body can be mixed. */ class RestfulClient : public BasicClient { template<typename T> friend class DecoratedRestfulClient; public: /* Generate the 100 Continue message. * On success returns number of bytes generated for a direct client of RadosGW. * On failure throws rgw::io::Exception containing errno. */ virtual size_t send_100_continue() = 0; /* Generate the response's status part taking the HTTP status code as @status * and its name pointed in @status_name. * On success returns number of bytes generated for a direct client of RadosGW. * On failure throws rgw::io::Exception containing errno. */ virtual size_t send_status(int status, const char *status_name) = 0; /* Generate header. On success returns number of bytes generated for a direct * client of RadosGW. On failure throws rgw::io::Exception containing errno. * * std::string_view is being used because of length it internally carries. */ virtual size_t send_header(const std::string_view& name, const std::string_view& value) = 0; /* Inform a client about a content length. Takes number of bytes as @len. * On success returns number of bytes generated for a direct client of RadosGW. * On failure throws rgw::io::Exception containing errno. * * CALL LIMITATIONS: * - The method must be called EXACTLY ONCE. * - The method is interchangeable with send_chunked_transfer_encoding(). */ virtual size_t send_content_length(uint64_t len) = 0; /* Inform a client that the chunked transfer encoding will be used. * On success returns number of bytes generated for a direct client of RadosGW. * On failure throws rgw::io::Exception containing errno. * * CALL LIMITATIONS: * - The method must be called EXACTLY ONCE. * - The method is interchangeable with send_content_length(). */ virtual size_t send_chunked_transfer_encoding() { /* This is a null implementation. We don't send anything here, even the HTTP * header. The intended behaviour should be provided through a decorator or * directly by a given front-end. */ return 0; } /* Generate completion (the CRLF sequence separating headers and body in * the case of HTTP) of headers. On success returns number of generated bytes * for a direct client of RadosGW. On failure throws rgw::io::Exception with * errno. */ virtual size_t complete_header() = 0; /* Receive no more than @max bytes from a request's body and store it in * buffer pointed by @buf. On success returns number of bytes received from * a direct client of RadosGW that has been stored in @buf. On failure throws * rgw::io::Exception containing errno. */ virtual size_t recv_body(char* buf, size_t max) = 0; /* Generate a part of response's body by taking exactly @len bytes from * the buffer pointed by @buf. On success returns number of generated bytes * of response's body. On failure throws rgw::io::Exception. */ virtual size_t send_body(const char* buf, size_t len) = 0; /* Flushes all already generated data to a direct client of RadosGW. * On failure throws rgw::io::Exception containing errno. */ virtual void flush() = 0; } /* rgw::io::RestfulClient */; /* Abstract decorator over any implementation of rgw::io::RestfulClient * which could be provided both as a pointer-to-object or the object itself. */ template <typename DecorateeT> class DecoratedRestfulClient : public RestfulClient { template<typename T> friend class DecoratedRestfulClient; friend RGWRestfulIO; typedef typename std::remove_pointer<DecorateeT>::type DerefedDecorateeT; static_assert(std::is_base_of<RestfulClient, DerefedDecorateeT>::value, "DecorateeT must be a subclass of rgw::io::RestfulClient"); DecorateeT decoratee; /* There is an indirection layer over accessing decoratee to share the same * code base between dynamic and static decorators. The difference is about * what we store internally: pointer to a decorated object versus the whole * object itself. */ template <typename T = void, typename std::enable_if< ! std::is_pointer<DecorateeT>::value, T>::type* = nullptr> DerefedDecorateeT& get_decoratee() { return decoratee; } protected: template <typename T = void, typename std::enable_if< std::is_pointer<DecorateeT>::value, T>::type* = nullptr> DerefedDecorateeT& get_decoratee() { return *decoratee; } /* Dynamic decorators (those storing a pointer instead of the decorated * object itself) can be reconfigured on-the-fly. HOWEVER: there are no * facilities for orchestrating such changes. Callers must take care of * atomicity and thread-safety. */ template <typename T = void, typename std::enable_if< std::is_pointer<DecorateeT>::value, T>::type* = nullptr> void set_decoratee(DerefedDecorateeT& new_dec) { decoratee = &new_dec; } int init_env(CephContext *cct) override { return get_decoratee().init_env(cct); } public: explicit DecoratedRestfulClient(DecorateeT&& decoratee) : decoratee(std::forward<DecorateeT>(decoratee)) { } size_t send_status(const int status, const char* const status_name) override { return get_decoratee().send_status(status, status_name); } size_t send_100_continue() override { return get_decoratee().send_100_continue(); } size_t send_header(const std::string_view& name, const std::string_view& value) override { return get_decoratee().send_header(name, value); } size_t send_content_length(const uint64_t len) override { return get_decoratee().send_content_length(len); } size_t send_chunked_transfer_encoding() override { return get_decoratee().send_chunked_transfer_encoding(); } size_t complete_header() override { return get_decoratee().complete_header(); } size_t recv_body(char* const buf, const size_t max) override { return get_decoratee().recv_body(buf, max); } size_t send_body(const char* const buf, const size_t len) override { return get_decoratee().send_body(buf, len); } void flush() override { return get_decoratee().flush(); } RGWEnv& get_env() noexcept override { return get_decoratee().get_env(); } size_t complete_request() override { return get_decoratee().complete_request(); } } /* rgw::io::DecoratedRestfulClient */; /* Interface that should be provided by a front-end class wanting to use * the low-level buffering offered by i.e. StaticOutputBufferer. */ class BuffererSink { public: virtual ~BuffererSink() = default; /* Send exactly @len bytes from the memory location pointed by @buf. * On success returns @len. On failure throws rgw::io::Exception. */ virtual size_t write_data(const char *buf, size_t len) = 0; }; /* Utility class providing RestfulClient's implementations with facilities * for low-level buffering without relying on dynamic memory allocations. * The buffer is carried entirely on stack. This narrows down applicability * to these situations where buffers are relatively small. This perfectly * fits the needs of composing an HTTP header. Without that a front-end * might need to issue a lot of small IO operations leading to increased * overhead on syscalls and fragmentation of a message if the Nagle's * algorithm won't be able to form a single TCP segment (usually when * running on extremely fast network interfaces like the loopback). */ template <size_t BufferSizeV = 4096> class StaticOutputBufferer : public std::streambuf { static_assert(BufferSizeV >= sizeof(std::streambuf::char_type), "Buffer size must be bigger than a single char_type."); using std::streambuf::int_type; int_type overflow(const int_type c) override { *pptr() = c; pbump(sizeof(std::streambuf::char_type)); if (! sync()) { /* No error, the buffer has been successfully synchronized. */ return c; } else { return std::streambuf::traits_type::eof(); } } int sync() override { const auto len = static_cast<size_t>(std::streambuf::pptr() - std::streambuf::pbase()); std::streambuf::pbump(-len); sink.write_data(std::streambuf::pbase(), len); /* Always return success here. In case of failure write_data() will throw * rgw::io::Exception. */ return 0; } BuffererSink& sink; std::streambuf::char_type buffer[BufferSizeV]; public: explicit StaticOutputBufferer(BuffererSink& sink) : sink(sink) { constexpr size_t len = sizeof(buffer) - sizeof(std::streambuf::char_type); std::streambuf::setp(buffer, buffer + len); } }; } /* namespace io */ } /* namespace rgw */ /* We're doing this nasty thing only because of extensive usage of templates * to implement the static decorator pattern. C++ templates de facto enforce * mixing interfaces with implementation. Additionally, those classes derive * from RGWRestfulIO defined here. I believe that including in the middle of * file is still better than polluting it directly. */ #include "rgw_client_io_filters.h" /* RGWRestfulIO: high level interface to interact with RESTful clients. What * differentiates it from rgw::io::RestfulClient is providing more specific APIs * like rgw::io::Accounter or the AWS Auth v4 stuff implemented by filters * while hiding the pipelined architecture from clients. * * rgw::io::Accounter came in as a part of rgw::io::AccountingFilter. */ class RGWRestfulIO : public rgw::io::AccountingFilter<rgw::io::RestfulClient*> { std::vector<std::shared_ptr<DecoratedRestfulClient>> filters; public: ~RGWRestfulIO() override = default; RGWRestfulIO(CephContext *_cx, rgw::io::RestfulClient* engine) : AccountingFilter<rgw::io::RestfulClient*>(_cx, std::move(engine)) { } void add_filter(std::shared_ptr<DecoratedRestfulClient> new_filter) { new_filter->set_decoratee(this->get_decoratee()); this->set_decoratee(*new_filter); filters.emplace_back(std::move(new_filter)); } }; /* RGWRestfulIO */ /* Type conversions to work around lack of req_state type hierarchy matching * (e.g.) REST backends (may be replaced w/dynamic typed req_state). */ static inline rgw::io::RestfulClient* RESTFUL_IO(req_state* s) { ceph_assert(dynamic_cast<rgw::io::RestfulClient*>(s->cio) != nullptr); return static_cast<rgw::io::RestfulClient*>(s->cio); } static inline rgw::io::Accounter* ACCOUNTING_IO(req_state* s) { auto ptr = dynamic_cast<rgw::io::Accounter*>(s->cio); ceph_assert(ptr != nullptr); return ptr; } static inline RGWRestfulIO* AWS_AUTHv4_IO(const req_state* const s) { ceph_assert(dynamic_cast<RGWRestfulIO*>(s->cio) != nullptr); return static_cast<RGWRestfulIO*>(s->cio); } class RGWClientIOStreamBuf : public std::streambuf { protected: RGWRestfulIO &rio; size_t const window_size; size_t const putback_size; std::vector<char> buffer; public: RGWClientIOStreamBuf(RGWRestfulIO &rio, size_t ws, size_t ps = 1) : rio(rio), window_size(ws), putback_size(ps), buffer(ws + ps) { setg(nullptr, nullptr, nullptr); } std::streambuf::int_type underflow() override { if (gptr() < egptr()) { return traits_type::to_int_type(*gptr()); } char * const base = buffer.data(); char * start; if (nullptr != eback()) { /* We need to skip moving bytes on first underflow. In such case * there is simply no previous data we should preserve for unget() * or something similar. */ std::memmove(base, egptr() - putback_size, putback_size); start = base + putback_size; } else { start = base; } size_t read_len = 0; try { read_len = rio.recv_body(base, window_size); } catch (rgw::io::Exception&) { return traits_type::eof(); } if (0 == read_len) { return traits_type::eof(); } setg(base, start, start + read_len); return traits_type::to_int_type(*gptr()); } }; class RGWClientIOStream : private RGWClientIOStreamBuf, public std::istream { /* Inheritance from RGWClientIOStreamBuf is a kind of shadow, undirect * form of composition here. We cannot do that explicitly because istream * ctor is being called prior to construction of any member of this class. */ public: explicit RGWClientIOStream(RGWRestfulIO &s) : RGWClientIOStreamBuf(s, 1, 2), std::istream(static_cast<RGWClientIOStreamBuf *>(this)) { } };
15,240
33.956422
81
h
null
ceph-main/src/rgw/rgw_client_io_filters.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 <type_traits> #include <boost/optional.hpp> #include "rgw_common.h" #include "rgw_client_io.h" namespace rgw { namespace io { template <typename T> class AccountingFilter : public DecoratedRestfulClient<T>, public Accounter { bool enabled; uint64_t total_sent; uint64_t total_received; CephContext *cct; public: template <typename U> AccountingFilter(CephContext *cct, U&& decoratee) : DecoratedRestfulClient<T>(std::forward<U>(decoratee)), enabled(false), total_sent(0), total_received(0), cct(cct) { } size_t send_status(const int status, const char* const status_name) override { const auto sent = DecoratedRestfulClient<T>::send_status(status, status_name); lsubdout(cct, rgw, 30) << "AccountingFilter::send_status: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t send_100_continue() override { const auto sent = DecoratedRestfulClient<T>::send_100_continue(); lsubdout(cct, rgw, 30) << "AccountingFilter::send_100_continue: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t send_header(const std::string_view& name, const std::string_view& value) override { const auto sent = DecoratedRestfulClient<T>::send_header(name, value); lsubdout(cct, rgw, 30) << "AccountingFilter::send_header: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t send_content_length(const uint64_t len) override { const auto sent = DecoratedRestfulClient<T>::send_content_length(len); lsubdout(cct, rgw, 30) << "AccountingFilter::send_content_length: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t send_chunked_transfer_encoding() override { const auto sent = DecoratedRestfulClient<T>::send_chunked_transfer_encoding(); lsubdout(cct, rgw, 30) << "AccountingFilter::send_chunked_transfer_encoding: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t complete_header() override { const auto sent = DecoratedRestfulClient<T>::complete_header(); lsubdout(cct, rgw, 30) << "AccountingFilter::complete_header: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t recv_body(char* buf, size_t max) override { const auto received = DecoratedRestfulClient<T>::recv_body(buf, max); lsubdout(cct, rgw, 30) << "AccountingFilter::recv_body: e=" << (enabled ? "1" : "0") << ", received=" << received << dendl; if (enabled) { total_received += received; } return received; } size_t send_body(const char* const buf, const size_t len) override { const auto sent = DecoratedRestfulClient<T>::send_body(buf, len); lsubdout(cct, rgw, 30) << "AccountingFilter::send_body: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } size_t complete_request() override { const auto sent = DecoratedRestfulClient<T>::complete_request(); lsubdout(cct, rgw, 30) << "AccountingFilter::complete_request: e=" << (enabled ? "1" : "0") << ", sent=" << sent << ", total=" << total_sent << dendl; if (enabled) { total_sent += sent; } return sent; } uint64_t get_bytes_sent() const override { return total_sent; } uint64_t get_bytes_received() const override { return total_received; } void set_account(bool enabled) override { this->enabled = enabled; lsubdout(cct, rgw, 30) << "AccountingFilter::set_account: e=" << (enabled ? "1" : "0") << dendl; } }; /* Filter for in-memory buffering incoming data and calculating the content * length header if it isn't present. */ template <typename T> class BufferingFilter : public DecoratedRestfulClient<T> { template<typename Td> friend class DecoratedRestfulClient; protected: ceph::bufferlist data; bool has_content_length; bool buffer_data; CephContext *cct; public: template <typename U> BufferingFilter(CephContext *cct, U&& decoratee) : DecoratedRestfulClient<T>(std::forward<U>(decoratee)), has_content_length(false), buffer_data(false), cct(cct) { } size_t send_content_length(const uint64_t len) override; size_t send_chunked_transfer_encoding() override; size_t complete_header() override; size_t send_body(const char* buf, size_t len) override; size_t complete_request() override; }; template <typename T> size_t BufferingFilter<T>::send_body(const char* const buf, const size_t len) { if (buffer_data) { data.append(buf, len); lsubdout(cct, rgw, 30) << "BufferingFilter<T>::send_body: defer count = " << len << dendl; return 0; } return DecoratedRestfulClient<T>::send_body(buf, len); } template <typename T> size_t BufferingFilter<T>::send_content_length(const uint64_t len) { has_content_length = true; return DecoratedRestfulClient<T>::send_content_length(len); } template <typename T> size_t BufferingFilter<T>::send_chunked_transfer_encoding() { has_content_length = true; return DecoratedRestfulClient<T>::send_chunked_transfer_encoding(); } template <typename T> size_t BufferingFilter<T>::complete_header() { if (! has_content_length) { /* We will dump everything in complete_request(). */ buffer_data = true; lsubdout(cct, rgw, 30) << "BufferingFilter<T>::complete_header: has_content_length=" << (has_content_length ? "1" : "0") << dendl; return 0; } return DecoratedRestfulClient<T>::complete_header(); } template <typename T> size_t BufferingFilter<T>::complete_request() { size_t sent = 0; if (! has_content_length) { /* It is not correct to count these bytes here, * because they can only be part of the header. * Therefore force count to 0. */ sent += DecoratedRestfulClient<T>::send_content_length(data.length()); sent += DecoratedRestfulClient<T>::complete_header(); lsubdout(cct, rgw, 30) << "BufferingFilter::complete_request: !has_content_length: IGNORE: sent=" << sent << dendl; sent = 0; } if (buffer_data) { /* We are sending each buffer separately to avoid extra memory shuffling * that would occur on data.c_str() to provide a continuous memory area. */ for (const auto& ptr : data.buffers()) { sent += DecoratedRestfulClient<T>::send_body(ptr.c_str(), ptr.length()); } data.clear(); buffer_data = false; lsubdout(cct, rgw, 30) << "BufferingFilter::complete_request: buffer_data: sent=" << sent << dendl; } return sent + DecoratedRestfulClient<T>::complete_request(); } template <typename T> static inline BufferingFilter<T> add_buffering( CephContext *cct, T&& t) { return BufferingFilter<T>(cct, std::forward<T>(t)); } template <typename T> class ChunkingFilter : public DecoratedRestfulClient<T> { template<typename Td> friend class DecoratedRestfulClient; protected: bool chunking_enabled; public: template <typename U> explicit ChunkingFilter(U&& decoratee) : DecoratedRestfulClient<T>(std::forward<U>(decoratee)), chunking_enabled(false) { } size_t send_chunked_transfer_encoding() override { chunking_enabled = true; return DecoratedRestfulClient<T>::send_header("Transfer-Encoding", "chunked"); } size_t send_body(const char* buf, const size_t len) override { if (! chunking_enabled) { return DecoratedRestfulClient<T>::send_body(buf, len); } else { static constexpr char HEADER_END[] = "\r\n"; /* https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 */ // TODO: we have no support for sending chunked-encoding // extensions/trailing headers. char chunk_size[32]; const auto chunk_size_len = snprintf(chunk_size, sizeof(chunk_size), "%zx\r\n", len); size_t sent = 0; sent += DecoratedRestfulClient<T>::send_body(chunk_size, chunk_size_len); sent += DecoratedRestfulClient<T>::send_body(buf, len); sent += DecoratedRestfulClient<T>::send_body(HEADER_END, sizeof(HEADER_END) - 1); return sent; } } size_t complete_request() override { size_t sent = 0; if (chunking_enabled) { static constexpr char CHUNKED_RESP_END[] = "0\r\n\r\n"; sent += DecoratedRestfulClient<T>::send_body(CHUNKED_RESP_END, sizeof(CHUNKED_RESP_END) - 1); } return sent + DecoratedRestfulClient<T>::complete_request(); } }; template <typename T> static inline ChunkingFilter<T> add_chunking(T&& t) { return ChunkingFilter<T>(std::forward<T>(t)); } /* Class that controls and inhibits the process of sending Content-Length HTTP * header where RFC 7230 requests so. The cases worth our attention are 204 No * Content as well as 304 Not Modified. */ template <typename T> class ConLenControllingFilter : public DecoratedRestfulClient<T> { protected: enum class ContentLengthAction { FORWARD, INHIBIT, UNKNOWN } action; public: template <typename U> explicit ConLenControllingFilter(U&& decoratee) : DecoratedRestfulClient<T>(std::forward<U>(decoratee)), action(ContentLengthAction::UNKNOWN) { } size_t send_status(const int status, const char* const status_name) override { if ((204 == status || 304 == status) && ! g_conf()->rgw_print_prohibited_content_length) { action = ContentLengthAction::INHIBIT; } else { action = ContentLengthAction::FORWARD; } return DecoratedRestfulClient<T>::send_status(status, status_name); } size_t send_content_length(const uint64_t len) override { switch(action) { case ContentLengthAction::FORWARD: return DecoratedRestfulClient<T>::send_content_length(len); case ContentLengthAction::INHIBIT: return 0; case ContentLengthAction::UNKNOWN: default: return -EINVAL; } } }; template <typename T> static inline ConLenControllingFilter<T> add_conlen_controlling(T&& t) { return ConLenControllingFilter<T>(std::forward<T>(t)); } /* Filter that rectifies the wrong behaviour of some clients of the RGWRestfulIO * interface. Should be removed after fixing those clients. */ template <typename T> class ReorderingFilter : public DecoratedRestfulClient<T> { protected: enum class ReorderState { RGW_EARLY_HEADERS, /* Got headers sent before calling send_status. */ RGW_STATUS_SEEN, /* Status has been seen. */ RGW_DATA /* Header has been completed. */ } phase; boost::optional<uint64_t> content_length; std::vector<std::pair<std::string, std::string>> headers; size_t send_header(const std::string_view& name, const std::string_view& value) override { switch (phase) { case ReorderState::RGW_EARLY_HEADERS: case ReorderState::RGW_STATUS_SEEN: headers.emplace_back(std::make_pair(std::string(name.data(), name.size()), std::string(value.data(), value.size()))); return 0; case ReorderState::RGW_DATA: return DecoratedRestfulClient<T>::send_header(name, value); } return -EIO; } public: template <typename U> explicit ReorderingFilter(U&& decoratee) : DecoratedRestfulClient<T>(std::forward<U>(decoratee)), phase(ReorderState::RGW_EARLY_HEADERS) { } size_t send_status(const int status, const char* const status_name) override { phase = ReorderState::RGW_STATUS_SEEN; return DecoratedRestfulClient<T>::send_status(status, status_name); } size_t send_content_length(const uint64_t len) override { if (ReorderState::RGW_EARLY_HEADERS == phase) { /* Oh great, someone tries to send content length before status. */ content_length = len; return 0; } else { return DecoratedRestfulClient<T>::send_content_length(len); } } size_t complete_header() override { size_t sent = 0; /* Change state in order to immediately send everything we get. */ phase = ReorderState::RGW_DATA; /* Sent content length if necessary. */ if (content_length) { sent += DecoratedRestfulClient<T>::send_content_length(*content_length); } /* Header data in buffers are already counted. */ for (const auto& kv : headers) { sent += DecoratedRestfulClient<T>::send_header(kv.first, kv.second); } headers.clear(); return sent + DecoratedRestfulClient<T>::complete_header(); } }; template <typename T> static inline ReorderingFilter<T> add_reordering(T&& t) { return ReorderingFilter<T>(std::forward<T>(t)); } } /* namespace io */ } /* namespace rgw */
13,842
29.424176
88
h
null
ceph-main/src/rgw/rgw_common.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <errno.h> #include <vector> #include <algorithm> #include <string> #include <boost/tokenizer.hpp> #include "json_spirit/json_spirit.h" #include "common/ceph_json.h" #include "common/Formatter.h" #include "rgw_op.h" #include "rgw_common.h" #include "rgw_acl.h" #include "rgw_string.h" #include "rgw_http_errors.h" #include "rgw_arn.h" #include "rgw_data_sync.h" #include "global/global_init.h" #include "common/ceph_crypto.h" #include "common/armor.h" #include "common/errno.h" #include "common/Clock.h" #include "common/convenience.h" #include "common/strtol.h" #include "include/str_list.h" #include "rgw_crypt_sanitize.h" #include "rgw_bucket_sync.h" #include "rgw_sync_policy.h" #include "services/svc_zone.h" #include <sstream> #define dout_context g_ceph_context static constexpr auto dout_subsys = ceph_subsys_rgw; using rgw::ARN; using rgw::IAM::Effect; using rgw::IAM::op_to_perm; using rgw::IAM::Policy; const uint32_t RGWBucketInfo::NUM_SHARDS_BLIND_BUCKET(UINT32_MAX); rgw_http_errors rgw_http_s3_errors({ { 0, {200, "" }}, { STATUS_CREATED, {201, "Created" }}, { STATUS_ACCEPTED, {202, "Accepted" }}, { STATUS_NO_CONTENT, {204, "NoContent" }}, { STATUS_PARTIAL_CONTENT, {206, "" }}, { ERR_PERMANENT_REDIRECT, {301, "PermanentRedirect" }}, { ERR_WEBSITE_REDIRECT, {301, "WebsiteRedirect" }}, { STATUS_REDIRECT, {303, "" }}, { ERR_NOT_MODIFIED, {304, "NotModified" }}, { EINVAL, {400, "InvalidArgument" }}, { ERR_INVALID_REQUEST, {400, "InvalidRequest" }}, { ERR_INVALID_DIGEST, {400, "InvalidDigest" }}, { ERR_BAD_DIGEST, {400, "BadDigest" }}, { ERR_INVALID_LOCATION_CONSTRAINT, {400, "InvalidLocationConstraint" }}, { ERR_ZONEGROUP_DEFAULT_PLACEMENT_MISCONFIGURATION, {400, "ZonegroupDefaultPlacementMisconfiguration" }}, { ERR_INVALID_BUCKET_NAME, {400, "InvalidBucketName" }}, { ERR_INVALID_OBJECT_NAME, {400, "InvalidObjectName" }}, { ERR_UNRESOLVABLE_EMAIL, {400, "UnresolvableGrantByEmailAddress" }}, { ERR_INVALID_PART, {400, "InvalidPart" }}, { ERR_INVALID_PART_ORDER, {400, "InvalidPartOrder" }}, { ERR_REQUEST_TIMEOUT, {400, "RequestTimeout" }}, { ERR_TOO_LARGE, {400, "EntityTooLarge" }}, { ERR_TOO_SMALL, {400, "EntityTooSmall" }}, { ERR_TOO_MANY_BUCKETS, {400, "TooManyBuckets" }}, { ERR_MALFORMED_XML, {400, "MalformedXML" }}, { ERR_AMZ_CONTENT_SHA256_MISMATCH, {400, "XAmzContentSHA256Mismatch" }}, { ERR_MALFORMED_DOC, {400, "MalformedPolicyDocument"}}, { ERR_INVALID_TAG, {400, "InvalidTag"}}, { ERR_MALFORMED_ACL_ERROR, {400, "MalformedACLError" }}, { ERR_INVALID_CORS_RULES_ERROR, {400, "InvalidRequest" }}, { ERR_INVALID_WEBSITE_ROUTING_RULES_ERROR, {400, "InvalidRequest" }}, { ERR_INVALID_ENCRYPTION_ALGORITHM, {400, "InvalidEncryptionAlgorithmError" }}, { ERR_INVALID_RETENTION_PERIOD,{400, "InvalidRetentionPeriod"}}, { ERR_LIMIT_EXCEEDED, {400, "LimitExceeded" }}, { ERR_LENGTH_REQUIRED, {411, "MissingContentLength" }}, { EACCES, {403, "AccessDenied" }}, { EPERM, {403, "AccessDenied" }}, { ERR_SIGNATURE_NO_MATCH, {403, "SignatureDoesNotMatch" }}, { ERR_INVALID_ACCESS_KEY, {403, "InvalidAccessKeyId" }}, { ERR_USER_SUSPENDED, {403, "UserSuspended" }}, { ERR_REQUEST_TIME_SKEWED, {403, "RequestTimeTooSkewed" }}, { ERR_QUOTA_EXCEEDED, {403, "QuotaExceeded" }}, { ERR_MFA_REQUIRED, {403, "AccessDenied" }}, { ENOENT, {404, "NoSuchKey" }}, { ERR_NO_SUCH_BUCKET, {404, "NoSuchBucket" }}, { ERR_NO_SUCH_WEBSITE_CONFIGURATION, {404, "NoSuchWebsiteConfiguration" }}, { ERR_NO_SUCH_UPLOAD, {404, "NoSuchUpload" }}, { ERR_NOT_FOUND, {404, "Not Found"}}, { ERR_NO_SUCH_LC, {404, "NoSuchLifecycleConfiguration"}}, { ERR_NO_SUCH_BUCKET_POLICY, {404, "NoSuchBucketPolicy"}}, { ERR_NO_SUCH_USER, {404, "NoSuchUser"}}, { ERR_NO_ROLE_FOUND, {404, "NoSuchEntity"}}, { ERR_NO_CORS_FOUND, {404, "NoSuchCORSConfiguration"}}, { ERR_NO_SUCH_SUBUSER, {404, "NoSuchSubUser"}}, { ERR_NO_SUCH_ENTITY, {404, "NoSuchEntity"}}, { ERR_NO_SUCH_CORS_CONFIGURATION, {404, "NoSuchCORSConfiguration"}}, { ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION, {404, "ObjectLockConfigurationNotFoundError"}}, { ERR_METHOD_NOT_ALLOWED, {405, "MethodNotAllowed" }}, { ETIMEDOUT, {408, "RequestTimeout" }}, { EEXIST, {409, "BucketAlreadyExists" }}, { ERR_USER_EXIST, {409, "UserAlreadyExists" }}, { ERR_EMAIL_EXIST, {409, "EmailExists" }}, { ERR_KEY_EXIST, {409, "KeyExists"}}, { ERR_TAG_CONFLICT, {409, "OperationAborted"}}, { ERR_POSITION_NOT_EQUAL_TO_LENGTH, {409, "PositionNotEqualToLength"}}, { ERR_OBJECT_NOT_APPENDABLE, {409, "ObjectNotAppendable"}}, { ERR_INVALID_BUCKET_STATE, {409, "InvalidBucketState"}}, { ERR_INVALID_OBJECT_STATE, {403, "InvalidObjectState"}}, { ERR_INVALID_SECRET_KEY, {400, "InvalidSecretKey"}}, { ERR_INVALID_KEY_TYPE, {400, "InvalidKeyType"}}, { ERR_INVALID_CAP, {400, "InvalidCapability"}}, { ERR_INVALID_TENANT_NAME, {400, "InvalidTenantName" }}, { ENOTEMPTY, {409, "BucketNotEmpty" }}, { ERR_PRECONDITION_FAILED, {412, "PreconditionFailed" }}, { ERANGE, {416, "InvalidRange" }}, { ERR_UNPROCESSABLE_ENTITY, {422, "UnprocessableEntity" }}, { ERR_LOCKED, {423, "Locked" }}, { ERR_INTERNAL_ERROR, {500, "InternalError" }}, { ERR_NOT_IMPLEMENTED, {501, "NotImplemented" }}, { ERR_SERVICE_UNAVAILABLE, {503, "ServiceUnavailable"}}, { ERR_RATE_LIMITED, {503, "SlowDown"}}, { ERR_ZERO_IN_URL, {400, "InvalidRequest" }}, { ERR_NO_SUCH_TAG_SET, {404, "NoSuchTagSet"}}, { ERR_NO_SUCH_BUCKET_ENCRYPTION_CONFIGURATION, {404, "ServerSideEncryptionConfigurationNotFoundError"}}, }); rgw_http_errors rgw_http_swift_errors({ { EACCES, {403, "AccessDenied" }}, { EPERM, {401, "AccessDenied" }}, { ENAMETOOLONG, {400, "Metadata name too long" }}, { ERR_USER_SUSPENDED, {401, "UserSuspended" }}, { ERR_INVALID_UTF8, {412, "Invalid UTF8" }}, { ERR_BAD_URL, {412, "Bad URL" }}, { ERR_NOT_SLO_MANIFEST, {400, "Not an SLO manifest" }}, { ERR_QUOTA_EXCEEDED, {413, "QuotaExceeded" }}, { ENOTEMPTY, {409, "There was a conflict when trying " "to complete your request." }}, /* FIXME(rzarzynski): we need to find a way to apply Swift's error handling * procedures also for ERR_ZERO_IN_URL. This make a problem as the validation * is performed very early, even before setting the req_state::proto_flags. */ { ERR_ZERO_IN_URL, {412, "Invalid UTF8 or contains NULL"}}, { ERR_RATE_LIMITED, {498, "Rate Limited"}}, }); rgw_http_errors rgw_http_sts_errors({ { ERR_PACKED_POLICY_TOO_LARGE, {400, "PackedPolicyTooLarge" }}, { ERR_INVALID_IDENTITY_TOKEN, {400, "InvalidIdentityToken" }}, }); rgw_http_errors rgw_http_iam_errors({ { EINVAL, {400, "InvalidInput" }}, { ENOENT, {404, "NoSuchEntity"}}, { ERR_ROLE_EXISTS, {409, "EntityAlreadyExists"}}, { ERR_DELETE_CONFLICT, {409, "DeleteConflict"}}, { EEXIST, {409, "EntityAlreadyExists"}}, { ERR_INTERNAL_ERROR, {500, "ServiceFailure" }}, }); using namespace std; using namespace ceph::crypto; thread_local bool is_asio_thread = false; rgw_err:: rgw_err() { clear(); } void rgw_err:: clear() { http_ret = 200; ret = 0; err_code.clear(); } bool rgw_err:: is_clear() const { return (http_ret == 200); } bool rgw_err:: is_err() const { return !(http_ret >= 200 && http_ret <= 399); } // The requestURI transferred from the frontend can be abs_path or absoluteURI // If it is absoluteURI, we should adjust it to abs_path for the following // S3 authorization and some other processes depending on the requestURI // The absoluteURI can start with "http://", "https://", "ws://" or "wss://" static string get_abs_path(const string& request_uri) { const static string ABS_PREFIXS[] = {"http://", "https://", "ws://", "wss://"}; bool isAbs = false; for (int i = 0; i < 4; ++i) { if (boost::algorithm::starts_with(request_uri, ABS_PREFIXS[i])) { isAbs = true; break; } } if (!isAbs) { // it is not a valid absolute uri return request_uri; } size_t beg_pos = request_uri.find("://") + 3; size_t len = request_uri.size(); beg_pos = request_uri.find('/', beg_pos); if (beg_pos == string::npos) return request_uri; return request_uri.substr(beg_pos, len - beg_pos); } req_info::req_info(CephContext *cct, const class RGWEnv *env) : env(env) { method = env->get("REQUEST_METHOD", ""); script_uri = env->get("SCRIPT_URI", cct->_conf->rgw_script_uri.c_str()); request_uri = env->get("REQUEST_URI", cct->_conf->rgw_request_uri.c_str()); if (request_uri[0] != '/') { request_uri = get_abs_path(request_uri); } auto pos = request_uri.find('?'); if (pos != string::npos) { request_params = request_uri.substr(pos + 1); request_uri = request_uri.substr(0, pos); } else { request_params = env->get("QUERY_STRING", ""); } host = env->get("HTTP_HOST", ""); // strip off any trailing :port from host (added by CrossFTP and maybe others) size_t colon_offset = host.find_last_of(':'); if (colon_offset != string::npos) { bool all_digits = true; for (unsigned i = colon_offset + 1; i < host.size(); ++i) { if (!isdigit(host[i])) { all_digits = false; break; } } if (all_digits) { host.resize(colon_offset); } } } void req_info::rebuild_from(req_info& src) { method = src.method; script_uri = src.script_uri; args = src.args; if (src.effective_uri.empty()) { request_uri = src.request_uri; } else { request_uri = src.effective_uri; } effective_uri.clear(); host = src.host; x_meta_map = src.x_meta_map; x_meta_map.erase("x-amz-date"); } req_state::req_state(CephContext* _cct, const RGWProcessEnv& penv, RGWEnv* e, uint64_t id) : cct(_cct), penv(penv), info(_cct, e), id(id) { enable_ops_log = e->get_enable_ops_log(); enable_usage_log = e->get_enable_usage_log(); defer_to_bucket_acls = e->get_defer_to_bucket_acls(); time = Clock::now(); } req_state::~req_state() { delete formatter; } std::ostream& req_state::gen_prefix(std::ostream& out) const { auto p = out.precision(); return out << "req " << id << ' ' << std::setprecision(3) << std::fixed << time_elapsed() // '0.123s' << std::setprecision(p) << std::defaultfloat << ' '; } bool search_err(rgw_http_errors& errs, int err_no, int& http_ret, string& code) { auto r = errs.find(err_no); if (r != errs.end()) { http_ret = r->second.first; code = r->second.second; return true; } return false; } void set_req_state_err(struct rgw_err& err, /* out */ int err_no, /* in */ const int prot_flags) /* in */ { if (err_no < 0) err_no = -err_no; err.ret = -err_no; if (prot_flags & RGW_REST_SWIFT) { if (search_err(rgw_http_swift_errors, err_no, err.http_ret, err.err_code)) return; } if (prot_flags & RGW_REST_STS) { if (search_err(rgw_http_sts_errors, err_no, err.http_ret, err.err_code)) return; } if (prot_flags & RGW_REST_IAM) { if (search_err(rgw_http_iam_errors, err_no, err.http_ret, err.err_code)) return; } //Default to searching in s3 errors if (search_err(rgw_http_s3_errors, err_no, err.http_ret, err.err_code)) return; dout(0) << "WARNING: set_req_state_err err_no=" << err_no << " resorting to 500" << dendl; err.http_ret = 500; err.err_code = "UnknownError"; } void set_req_state_err(req_state* s, int err_no, const string& err_msg) { if (s) { set_req_state_err(s, err_no); if (s->prot_flags & RGW_REST_SWIFT && !err_msg.empty()) { /* TODO(rzarzynski): there never ever should be a check like this one. * It's here only for the sake of the patch's backportability. Further * commits will move the logic to a per-RGWHandler replacement of * the end_header() function. Alternativaly, we might consider making * that just for the dump(). Please take a look on @cbodley's comments * in PR #10690 (https://github.com/ceph/ceph/pull/10690). */ s->err.err_code = err_msg; } else { s->err.message = err_msg; } } } void set_req_state_err(req_state* s, int err_no) { if (s) { set_req_state_err(s->err, err_no, s->prot_flags); } } void dump(req_state* s) { if (s->format != RGWFormat::HTML) s->formatter->open_object_section("Error"); if (!s->err.err_code.empty()) s->formatter->dump_string("Code", s->err.err_code); s->formatter->dump_string("Message", s->err.message); if (!s->bucket_name.empty()) // TODO: connect to expose_bucket s->formatter->dump_string("BucketName", s->bucket_name); if (!s->trans_id.empty()) // TODO: connect to expose_bucket or another toggle s->formatter->dump_string("RequestId", s->trans_id); s->formatter->dump_string("HostId", s->host_id); if (s->format != RGWFormat::HTML) s->formatter->close_section(); } struct str_len { const char *str; int len; }; #define STR_LEN_ENTRY(s) { s, sizeof(s) - 1 } struct str_len meta_prefixes[] = { STR_LEN_ENTRY("HTTP_X_AMZ"), STR_LEN_ENTRY("HTTP_X_GOOG"), STR_LEN_ENTRY("HTTP_X_DHO"), STR_LEN_ENTRY("HTTP_X_RGW"), STR_LEN_ENTRY("HTTP_X_OBJECT"), STR_LEN_ENTRY("HTTP_X_CONTAINER"), STR_LEN_ENTRY("HTTP_X_ACCOUNT"), {NULL, 0} }; void req_info::init_meta_info(const DoutPrefixProvider *dpp, bool *found_bad_meta) { x_meta_map.clear(); crypt_attribute_map.clear(); for (const auto& kv: env->get_map()) { const char *prefix; const string& header_name = kv.first; const string& val = kv.second; for (int prefix_num = 0; (prefix = meta_prefixes[prefix_num].str) != NULL; prefix_num++) { int len = meta_prefixes[prefix_num].len; const char *p = header_name.c_str(); if (strncmp(p, prefix, len) == 0) { ldpp_dout(dpp, 10) << "meta>> " << p << dendl; const char *name = p+len; /* skip the prefix */ int name_len = header_name.size() - len; if (found_bad_meta && strncmp(name, "_META_", name_len) == 0) *found_bad_meta = true; char name_low[meta_prefixes[0].len + name_len + 1]; snprintf(name_low, meta_prefixes[0].len - 5 + name_len + 1, "%s%s", meta_prefixes[0].str + 5 /* skip HTTP_ */, name); // normalize meta prefix int j; for (j = 0; name_low[j]; j++) { if (name_low[j] == '_') name_low[j] = '-'; else if (name_low[j] == '-') name_low[j] = '_'; else name_low[j] = tolower(name_low[j]); } name_low[j] = 0; auto it = x_meta_map.find(name_low); if (it != x_meta_map.end()) { string old = it->second; boost::algorithm::trim_right(old); old.append(","); old.append(val); x_meta_map[name_low] = old; } else { x_meta_map[name_low] = val; } if (strncmp(name_low, "x-amz-server-side-encryption", 20) == 0) { crypt_attribute_map[name_low] = val; } } } } for (const auto& kv: x_meta_map) { ldpp_dout(dpp, 10) << "x>> " << kv.first << ":" << rgw::crypt_sanitize::x_meta_map{kv.first, kv.second} << dendl; } } std::ostream& operator<<(std::ostream& oss, const rgw_err &err) { oss << "rgw_err(http_ret=" << err.http_ret << ", err_code='" << err.err_code << "') "; return oss; } void rgw_add_amz_meta_header( meta_map_t& x_meta_map, const std::string& k, const std::string& v) { auto it = x_meta_map.find(k); if (it != x_meta_map.end()) { std::string old = it->second; boost::algorithm::trim_right(old); old.append(","); old.append(v); x_meta_map[k] = old; } else { x_meta_map[k] = v; } } bool rgw_set_amz_meta_header( meta_map_t& x_meta_map, const std::string& k, const std::string& v, rgw_set_action_if_set a) { auto it { x_meta_map.find(k) }; bool r { it != x_meta_map.end() }; switch(a) { default: ceph_assert(a == 0); case DISCARD: break; case APPEND: if (r) { std::string old { it->second }; boost::algorithm::trim_right(old); old.append(","); old.append(v); x_meta_map[k] = old; break; } /* fall through */ case OVERWRITE: x_meta_map[k] = v; } return r; } string rgw_string_unquote(const string& s) { if (s[0] != '"' || s.size() < 2) return s; int len; for (len = s.size(); len > 2; --len) { if (s[len - 1] != ' ') break; } if (s[len-1] != '"') return s; return s.substr(1, len - 2); } static bool check_str_end(const char *s) { if (!s) return false; while (*s) { if (!isspace(*s)) return false; s++; } return true; } static bool check_gmt_end(const char *s) { if (!s || !*s) return false; while (isspace(*s)) { ++s; } /* check for correct timezone */ if ((strncmp(s, "GMT", 3) != 0) && (strncmp(s, "UTC", 3) != 0)) { return false; } return true; } static bool parse_rfc850(const char *s, struct tm *t) { // FIPS zeroization audit 20191115: this memset is not security related. memset(t, 0, sizeof(*t)); return check_gmt_end(strptime(s, "%A, %d-%b-%y %H:%M:%S ", t)); } static bool parse_asctime(const char *s, struct tm *t) { // FIPS zeroization audit 20191115: this memset is not security related. memset(t, 0, sizeof(*t)); return check_str_end(strptime(s, "%a %b %d %H:%M:%S %Y", t)); } static bool parse_rfc1123(const char *s, struct tm *t) { // FIPS zeroization audit 20191115: this memset is not security related. memset(t, 0, sizeof(*t)); return check_gmt_end(strptime(s, "%a, %d %b %Y %H:%M:%S ", t)); } static bool parse_rfc1123_alt(const char *s, struct tm *t) { // FIPS zeroization audit 20191115: this memset is not security related. memset(t, 0, sizeof(*t)); return check_str_end(strptime(s, "%a, %d %b %Y %H:%M:%S %z", t)); } bool parse_rfc2616(const char *s, struct tm *t) { return parse_rfc850(s, t) || parse_asctime(s, t) || parse_rfc1123(s, t) || parse_rfc1123_alt(s,t); } bool parse_iso8601(const char *s, struct tm *t, uint32_t *pns, bool extended_format) { // FIPS zeroization audit 20191115: this memset is not security related. memset(t, 0, sizeof(*t)); const char *p; if (!s) s = ""; if (extended_format) { p = strptime(s, "%Y-%m-%dT%T", t); if (!p) { p = strptime(s, "%Y-%m-%d %T", t); } } else { p = strptime(s, "%Y%m%dT%H%M%S", t); } if (!p) { dout(0) << "parse_iso8601 failed" << dendl; return false; } const std::string_view str = rgw_trim_whitespace(std::string_view(p)); int len = str.size(); if (len == 0 || (len == 1 && str[0] == 'Z')) return true; if (str[0] != '.' || str[len - 1] != 'Z') return false; uint32_t ms; std::string_view nsstr = str.substr(1, len - 2); int r = stringtoul(std::string(nsstr), &ms); if (r < 0) return false; if (!pns) { return true; } if (nsstr.size() > 9) { nsstr = nsstr.substr(0, 9); } uint64_t mul_table[] = { 0, 100000000LL, 10000000LL, 1000000LL, 100000LL, 10000LL, 1000LL, 100LL, 10LL, 1 }; *pns = ms * mul_table[nsstr.size()]; return true; } int parse_key_value(string& in_str, const char *delim, string& key, string& val) { if (delim == NULL) return -EINVAL; auto pos = in_str.find(delim); if (pos == string::npos) return -EINVAL; key = rgw_trim_whitespace(in_str.substr(0, pos)); val = rgw_trim_whitespace(in_str.substr(pos + 1)); return 0; } int parse_key_value(string& in_str, string& key, string& val) { return parse_key_value(in_str, "=", key,val); } boost::optional<std::pair<std::string_view, std::string_view>> parse_key_value(const std::string_view& in_str, const std::string_view& delim) { const size_t pos = in_str.find(delim); if (pos == std::string_view::npos) { return boost::none; } const auto key = rgw_trim_whitespace(in_str.substr(0, pos)); const auto val = rgw_trim_whitespace(in_str.substr(pos + 1)); return std::make_pair(key, val); } boost::optional<std::pair<std::string_view, std::string_view>> parse_key_value(const std::string_view& in_str) { return parse_key_value(in_str, "="); } int parse_time(const char *time_str, real_time *time) { struct tm tm; uint32_t ns = 0; if (!parse_rfc2616(time_str, &tm) && !parse_iso8601(time_str, &tm, &ns)) { return -EINVAL; } time_t sec = internal_timegm(&tm); *time = utime_t(sec, ns).to_real_time(); return 0; } #define TIME_BUF_SIZE 128 void rgw_to_iso8601(const real_time& t, char *dest, int buf_size) { utime_t ut(t); char buf[TIME_BUF_SIZE]; struct tm result; time_t epoch = ut.sec(); struct tm *tmp = gmtime_r(&epoch, &result); if (tmp == NULL) return; if (strftime(buf, sizeof(buf), "%Y-%m-%dT%T", tmp) == 0) return; snprintf(dest, buf_size, "%s.%03dZ", buf, (int)(ut.usec() / 1000)); } void rgw_to_iso8601(const real_time& t, string *dest) { char buf[TIME_BUF_SIZE]; rgw_to_iso8601(t, buf, sizeof(buf)); *dest = buf; } string rgw_to_asctime(const utime_t& t) { stringstream s; t.asctime(s); return s.str(); } /* * calculate the sha1 value of a given msg and key */ void calc_hmac_sha1(const char *key, int key_len, const char *msg, int msg_len, char *dest) /* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */ { HMACSHA1 hmac((const unsigned char *)key, key_len); hmac.Update((const unsigned char *)msg, msg_len); hmac.Final((unsigned char *)dest); } /* * calculate the sha256 value of a given msg and key */ void calc_hmac_sha256(const char *key, int key_len, const char *msg, int msg_len, char *dest) { char hash_sha256[CEPH_CRYPTO_HMACSHA256_DIGESTSIZE]; HMACSHA256 hmac((const unsigned char *)key, key_len); hmac.Update((const unsigned char *)msg, msg_len); hmac.Final((unsigned char *)hash_sha256); memcpy(dest, hash_sha256, CEPH_CRYPTO_HMACSHA256_DIGESTSIZE); } using ceph::crypto::SHA256; /* * calculate the sha256 hash value of a given msg */ sha256_digest_t calc_hash_sha256(const std::string_view& msg) { sha256_digest_t hash; SHA256 hasher; hasher.Update(reinterpret_cast<const unsigned char*>(msg.data()), msg.size()); hasher.Final(hash.v); return hash; } SHA256* calc_hash_sha256_open_stream() { return new SHA256; } void calc_hash_sha256_update_stream(SHA256 *hash, const char *msg, int len) { hash->Update((const unsigned char *)msg, len); } string calc_hash_sha256_close_stream(SHA256 **phash) { SHA256 *hash = *phash; if (!hash) { hash = calc_hash_sha256_open_stream(); } char hash_sha256[CEPH_CRYPTO_HMACSHA256_DIGESTSIZE]; hash->Final((unsigned char *)hash_sha256); char hex_str[(CEPH_CRYPTO_SHA256_DIGESTSIZE * 2) + 1]; buf_to_hex((unsigned char *)hash_sha256, CEPH_CRYPTO_SHA256_DIGESTSIZE, hex_str); delete hash; *phash = NULL; return std::string(hex_str); } std::string calc_hash_sha256_restart_stream(SHA256 **phash) { const auto hash = calc_hash_sha256_close_stream(phash); *phash = calc_hash_sha256_open_stream(); return hash; } int NameVal::parse() { auto delim_pos = str.find('='); int ret = 0; if (delim_pos == string::npos) { name = str; val = ""; ret = 1; } else { name = str.substr(0, delim_pos); val = str.substr(delim_pos + 1); } return ret; } int RGWHTTPArgs::parse(const DoutPrefixProvider *dpp) { int pos = 0; bool end = false; if (str.empty()) return 0; if (str[pos] == '?') pos++; while (!end) { int fpos = str.find('&', pos); if (fpos < pos) { end = true; fpos = str.size(); } std::string nameval = url_decode(str.substr(pos, fpos - pos), true); NameVal nv(std::move(nameval)); int ret = nv.parse(); if (ret >= 0) { string& name = nv.get_name(); if (name.find("X-Amz-") != string::npos) { std::for_each(name.begin(), name.end(), [](char &c){ if (c != '-') { c = ::tolower(static_cast<unsigned char>(c)); } }); } string& val = nv.get_val(); ldpp_dout(dpp, 10) << "name: " << name << " val: " << val << dendl; append(name, val); } pos = fpos + 1; } return 0; } void RGWHTTPArgs::remove(const string& name) { auto val_iter = val_map.find(name); if (val_iter != std::end(val_map)) { val_map.erase(val_iter); } auto sys_val_iter = sys_val_map.find(name); if (sys_val_iter != std::end(sys_val_map)) { sys_val_map.erase(sys_val_iter); } auto subres_iter = sub_resources.find(name); if (subres_iter != std::end(sub_resources)) { sub_resources.erase(subres_iter); } } void RGWHTTPArgs::append(const string& name, const string& val) { if (name.compare(0, sizeof(RGW_SYS_PARAM_PREFIX) - 1, RGW_SYS_PARAM_PREFIX) == 0) { sys_val_map[name] = val; } else { val_map[name] = val; } // when sub_resources exclusive by object are added, please remember to update obj_sub_resource in RGWHTTPArgs::exist_obj_excl_sub_resource(). if ((name.compare("acl") == 0) || (name.compare("cors") == 0) || (name.compare("notification") == 0) || (name.compare("location") == 0) || (name.compare("logging") == 0) || (name.compare("usage") == 0) || (name.compare("lifecycle") == 0) || (name.compare("delete") == 0) || (name.compare("uploads") == 0) || (name.compare("partNumber") == 0) || (name.compare("uploadId") == 0) || (name.compare("versionId") == 0) || (name.compare("start-date") == 0) || (name.compare("end-date") == 0) || (name.compare("versions") == 0) || (name.compare("versioning") == 0) || (name.compare("website") == 0) || (name.compare("requestPayment") == 0) || (name.compare("torrent") == 0) || (name.compare("tagging") == 0) || (name.compare("append") == 0) || (name.compare("position") == 0) || (name.compare("policyStatus") == 0) || (name.compare("publicAccessBlock") == 0)) { sub_resources[name] = val; } else if (name[0] == 'r') { // root of all evil if ((name.compare("response-content-type") == 0) || (name.compare("response-content-language") == 0) || (name.compare("response-expires") == 0) || (name.compare("response-cache-control") == 0) || (name.compare("response-content-disposition") == 0) || (name.compare("response-content-encoding") == 0)) { sub_resources[name] = val; has_resp_modifier = true; } } else if ((name.compare("subuser") == 0) || (name.compare("key") == 0) || (name.compare("caps") == 0) || (name.compare("index") == 0) || (name.compare("policy") == 0) || (name.compare("quota") == 0) || (name.compare("list") == 0) || (name.compare("object") == 0) || (name.compare("sync") == 0)) { if (!admin_subresource_added) { sub_resources[name] = ""; admin_subresource_added = true; } } } const string& RGWHTTPArgs::get(const string& name, bool *exists) const { auto iter = val_map.find(name); bool e = (iter != std::end(val_map)); if (exists) *exists = e; if (e) return iter->second; return empty_str; } boost::optional<const std::string&> RGWHTTPArgs::get_optional(const std::string& name) const { bool exists; const std::string& value = get(name, &exists); if (exists) { return value; } else { return boost::none; } } int RGWHTTPArgs::get_bool(const string& name, bool *val, bool *exists) const { map<string, string>::const_iterator iter; iter = val_map.find(name); bool e = (iter != val_map.end()); if (exists) *exists = e; if (e) { const char *s = iter->second.c_str(); if (strcasecmp(s, "false") == 0) { *val = false; } else if (strcasecmp(s, "true") == 0) { *val = true; } else { return -EINVAL; } } return 0; } int RGWHTTPArgs::get_bool(const char *name, bool *val, bool *exists) const { string s(name); return get_bool(s, val, exists); } void RGWHTTPArgs::get_bool(const char *name, bool *val, bool def_val) const { bool exists = false; if ((get_bool(name, val, &exists) < 0) || !exists) { *val = def_val; } } int RGWHTTPArgs::get_int(const char *name, int *val, int def_val) const { bool exists = false; string val_str; val_str = get(name, &exists); if (!exists) { *val = def_val; return 0; } string err; *val = (int)strict_strtol(val_str.c_str(), 10, &err); if (!err.empty()) { *val = def_val; return -EINVAL; } return 0; } string RGWHTTPArgs::sys_get(const string& name, bool * const exists) const { const auto iter = sys_val_map.find(name); const bool e = (iter != sys_val_map.end()); if (exists) { *exists = e; } return e ? iter->second : string(); } bool rgw_transport_is_secure(CephContext *cct, const RGWEnv& env) { const auto& m = env.get_map(); // frontend connected with ssl if (m.count("SERVER_PORT_SECURE")) { return true; } // ignore proxy headers unless explicitly enabled if (!cct->_conf->rgw_trust_forwarded_https) { return false; } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded // Forwarded: by=<identifier>; for=<identifier>; host=<host>; proto=<http|https> auto i = m.find("HTTP_FORWARDED"); if (i != m.end() && i->second.find("proto=https") != std::string::npos) { return true; } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto i = m.find("HTTP_X_FORWARDED_PROTO"); if (i != m.end() && i->second == "https") { return true; } return false; } namespace { struct perm_state_from_req_state : public perm_state_base { req_state * const s; perm_state_from_req_state(req_state * const _s) : perm_state_base(_s->cct, _s->env, _s->auth.identity.get(), _s->bucket.get() ? _s->bucket->get_info() : RGWBucketInfo(), _s->perm_mask, _s->defer_to_bucket_acls, _s->bucket_access_conf), s(_s) {} std::optional<bool> get_request_payer() const override { const char *request_payer = s->info.env->get("HTTP_X_AMZ_REQUEST_PAYER"); if (!request_payer) { bool exists; request_payer = s->info.args.get("x-amz-request-payer", &exists).c_str(); if (!exists) { return false; } } if (strcasecmp(request_payer, "requester") == 0) { return true; } return std::nullopt; } const char *get_referer() const override { return s->info.env->get("HTTP_REFERER"); } }; Effect eval_or_pass(const DoutPrefixProvider* dpp, const boost::optional<Policy>& policy, const rgw::IAM::Environment& env, boost::optional<const rgw::auth::Identity&> id, const uint64_t op, const ARN& resource, boost::optional<rgw::IAM::PolicyPrincipal&> princ_type=boost::none) { if (!policy) return Effect::Pass; else return policy->eval(env, id, op, resource, princ_type); } } Effect eval_identity_or_session_policies(const DoutPrefixProvider* dpp, const vector<Policy>& policies, const rgw::IAM::Environment& env, const uint64_t op, const ARN& arn) { auto policy_res = Effect::Pass, prev_res = Effect::Pass; for (auto& policy : policies) { if (policy_res = eval_or_pass(dpp, policy, env, boost::none, op, arn); policy_res == Effect::Deny) return policy_res; else if (policy_res == Effect::Allow) prev_res = Effect::Allow; else if (policy_res == Effect::Pass && prev_res == Effect::Allow) policy_res = Effect::Allow; } return policy_res; } bool verify_user_permission(const DoutPrefixProvider* dpp, perm_state_base * const s, RGWAccessControlPolicy * const user_acl, const vector<rgw::IAM::Policy>& user_policies, const vector<rgw::IAM::Policy>& session_policies, const rgw::ARN& res, const uint64_t op, bool mandatory_policy) { auto identity_policy_res = eval_identity_or_session_policies(dpp, user_policies, s->env, op, res); if (identity_policy_res == Effect::Deny) { return false; } if (! session_policies.empty()) { auto session_policy_res = eval_identity_or_session_policies(dpp, session_policies, s->env, op, res); if (session_policy_res == Effect::Deny) { return false; } //Intersection of identity policies and session policies if (identity_policy_res == Effect::Allow && session_policy_res == Effect::Allow) { return true; } return false; } if (identity_policy_res == Effect::Allow) { return true; } if (mandatory_policy) { // no policies, and policy is mandatory ldpp_dout(dpp, 20) << "no policies for a policy mandatory op " << op << dendl; return false; } auto perm = op_to_perm(op); return verify_user_permission_no_policy(dpp, s, user_acl, perm); } bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, const int perm) { if (s->identity->get_identity_type() == TYPE_ROLE) return false; /* S3 doesn't support account ACLs. */ if (!user_acl) return true; if ((perm & (int)s->perm_mask) != perm) return false; return user_acl->verify_permission(dpp, *s->identity, perm, perm); } bool verify_user_permission(const DoutPrefixProvider* dpp, req_state * const s, const rgw::ARN& res, const uint64_t op, bool mandatory_policy) { perm_state_from_req_state ps(s); return verify_user_permission(dpp, &ps, s->user_acl.get(), s->iam_user_policies, s->session_policies, res, op, mandatory_policy); } bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, const int perm) { perm_state_from_req_state ps(s); return verify_user_permission_no_policy(dpp, &ps, s->user_acl.get(), perm); } bool verify_requester_payer_permission(struct perm_state_base *s) { if (!s->bucket_info.requester_pays) return true; if (s->identity->is_owner_of(s->bucket_info.owner)) return true; if (s->identity->is_anonymous()) { return false; } auto request_payer = s->get_request_payer(); if (request_payer) { return *request_payer; } return false; } bool verify_bucket_permission(const DoutPrefixProvider* dpp, struct perm_state_base * const s, const rgw_bucket& bucket, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const boost::optional<Policy>& bucket_policy, const vector<Policy>& identity_policies, const vector<Policy>& session_policies, const uint64_t op) { if (!verify_requester_payer_permission(s)) return false; auto identity_policy_res = eval_identity_or_session_policies(dpp, identity_policies, s->env, op, ARN(bucket)); if (identity_policy_res == Effect::Deny) return false; rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other; if (bucket_policy) { ldpp_dout(dpp, 16) << __func__ << ": policy: " << bucket_policy.get() << "resource: " << ARN(bucket) << dendl; } auto r = eval_or_pass(dpp, bucket_policy, s->env, *s->identity, op, ARN(bucket), princ_type); if (r == Effect::Deny) return false; //Take into account session policies, if the identity making a request is a role if (!session_policies.empty()) { auto session_policy_res = eval_identity_or_session_policies(dpp, session_policies, s->env, op, ARN(bucket)); if (session_policy_res == Effect::Deny) { return false; } if (princ_type == rgw::IAM::PolicyPrincipal::Role) { //Intersection of session policy and identity policy plus intersection of session policy and bucket policy if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || (session_policy_res == Effect::Allow && r == Effect::Allow)) return true; } else if (princ_type == rgw::IAM::PolicyPrincipal::Session) { //Intersection of session policy and identity policy plus bucket policy if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || r == Effect::Allow) return true; } else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) return true; } return false; } if (r == Effect::Allow || identity_policy_res == Effect::Allow) // It looks like S3 ACLs only GRANT permissions rather than // denying them, so this should be safe. return true; const auto perm = op_to_perm(op); return verify_bucket_permission_no_policy(dpp, s, user_acl, bucket_acl, perm); } bool verify_bucket_permission(const DoutPrefixProvider* dpp, req_state * const s, const rgw_bucket& bucket, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const boost::optional<Policy>& bucket_policy, const vector<Policy>& user_policies, const vector<Policy>& session_policies, const uint64_t op) { perm_state_from_req_state ps(s); return verify_bucket_permission(dpp, &ps, bucket, user_acl, bucket_acl, bucket_policy, user_policies, session_policies, op); } bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const int perm) { if (!bucket_acl) return false; if ((perm & (int)s->perm_mask) != perm) return false; if (bucket_acl->verify_permission(dpp, *s->identity, perm, perm, s->get_referer(), s->bucket_access_conf && s->bucket_access_conf->ignore_public_acls())) return true; if (!user_acl) return false; return user_acl->verify_permission(dpp, *s->identity, perm, perm); } bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const int perm) { perm_state_from_req_state ps(s); return verify_bucket_permission_no_policy(dpp, &ps, user_acl, bucket_acl, perm); } bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, const int perm) { perm_state_from_req_state ps(s); if (!verify_requester_payer_permission(&ps)) return false; return verify_bucket_permission_no_policy(dpp, &ps, s->user_acl.get(), s->bucket_acl.get(), perm); } bool verify_bucket_permission(const DoutPrefixProvider* dpp, req_state * const s, const uint64_t op) { if (rgw::sal::Bucket::empty(s->bucket)) { // request is missing a bucket name return false; } perm_state_from_req_state ps(s); return verify_bucket_permission(dpp, &ps, s->bucket->get_key(), s->user_acl.get(), s->bucket_acl.get(), s->iam_policy, s->iam_user_policies, s->session_policies, op); } // Authorize anyone permitted by the bucket policy, identity policies, session policies and the bucket owner // unless explicitly denied by the policy. int verify_bucket_owner_or_policy(req_state* const s, const uint64_t op) { auto identity_policy_res = eval_identity_or_session_policies(s, s->iam_user_policies, s->env, op, ARN(s->bucket->get_key())); if (identity_policy_res == Effect::Deny) { return -EACCES; } rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other; auto e = eval_or_pass(s, s->iam_policy, s->env, *s->auth.identity, op, ARN(s->bucket->get_key()), princ_type); if (e == Effect::Deny) { return -EACCES; } if (!s->session_policies.empty()) { auto session_policy_res = eval_identity_or_session_policies(s, s->session_policies, s->env, op, ARN(s->bucket->get_key())); if (session_policy_res == Effect::Deny) { return -EACCES; } if (princ_type == rgw::IAM::PolicyPrincipal::Role) { //Intersection of session policy and identity policy plus intersection of session policy and bucket policy if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || (session_policy_res == Effect::Allow && e == Effect::Allow)) return 0; } else if (princ_type == rgw::IAM::PolicyPrincipal::Session) { //Intersection of session policy and identity policy plus bucket policy if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow) return 0; } else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) return 0; } return -EACCES; } if (e == Effect::Allow || identity_policy_res == Effect::Allow || (e == Effect::Pass && identity_policy_res == Effect::Pass && s->auth.identity->is_owner_of(s->bucket_owner.get_id()))) { return 0; } else { return -EACCES; } } static inline bool check_deferred_bucket_perms(const DoutPrefixProvider* dpp, struct perm_state_base * const s, const rgw_bucket& bucket, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const boost::optional<Policy>& bucket_policy, const vector<Policy>& identity_policies, const vector<Policy>& session_policies, const uint8_t deferred_check, const uint64_t op) { return (s->defer_to_bucket_acls == deferred_check \ && verify_bucket_permission(dpp, s, bucket, user_acl, bucket_acl, bucket_policy, identity_policies, session_policies,op)); } static inline bool check_deferred_bucket_only_acl(const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const uint8_t deferred_check, const int perm) { return (s->defer_to_bucket_acls == deferred_check \ && verify_bucket_permission_no_policy(dpp, s, user_acl, bucket_acl, perm)); } bool verify_object_permission(const DoutPrefixProvider* dpp, struct perm_state_base * const s, const rgw_obj& obj, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, RGWAccessControlPolicy * const object_acl, const boost::optional<Policy>& bucket_policy, const vector<Policy>& identity_policies, const vector<Policy>& session_policies, const uint64_t op) { if (!verify_requester_payer_permission(s)) return false; auto identity_policy_res = eval_identity_or_session_policies(dpp, identity_policies, s->env, op, ARN(obj)); if (identity_policy_res == Effect::Deny) return false; rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other; auto r = eval_or_pass(dpp, bucket_policy, s->env, *s->identity, op, ARN(obj), princ_type); if (r == Effect::Deny) return false; if (!session_policies.empty()) { auto session_policy_res = eval_identity_or_session_policies(dpp, session_policies, s->env, op, ARN(obj)); if (session_policy_res == Effect::Deny) { return false; } if (princ_type == rgw::IAM::PolicyPrincipal::Role) { //Intersection of session policy and identity policy plus intersection of session policy and bucket policy if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || (session_policy_res == Effect::Allow && r == Effect::Allow)) return true; } else if (princ_type == rgw::IAM::PolicyPrincipal::Session) { //Intersection of session policy and identity policy plus bucket policy if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || r == Effect::Allow) return true; } else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) return true; } return false; } if (r == Effect::Allow || identity_policy_res == Effect::Allow) // It looks like S3 ACLs only GRANT permissions rather than // denying them, so this should be safe. return true; const auto perm = op_to_perm(op); if (check_deferred_bucket_perms(dpp, s, obj.bucket, user_acl, bucket_acl, bucket_policy, identity_policies, session_policies, RGW_DEFER_TO_BUCKET_ACLS_RECURSE, op) || check_deferred_bucket_perms(dpp, s, obj.bucket, user_acl, bucket_acl, bucket_policy, identity_policies, session_policies, RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL, rgw::IAM::s3All)) { return true; } if (!object_acl) { return false; } bool ret = object_acl->verify_permission(dpp, *s->identity, s->perm_mask, perm, nullptr, /* http_referrer */ s->bucket_access_conf && s->bucket_access_conf->ignore_public_acls()); if (ret) { return true; } if (!s->cct->_conf->rgw_enforce_swift_acls) return ret; if ((perm & (int)s->perm_mask) != perm) return false; int swift_perm = 0; if (perm & (RGW_PERM_READ | RGW_PERM_READ_ACP)) swift_perm |= RGW_PERM_READ_OBJS; if (perm & RGW_PERM_WRITE) swift_perm |= RGW_PERM_WRITE_OBJS; if (!swift_perm) return false; /* we already verified the user mask above, so we pass swift_perm as the mask here, otherwise the mask might not cover the swift permissions bits */ if (bucket_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm, s->get_referer())) return true; if (!user_acl) return false; return user_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm); } bool verify_object_permission(const DoutPrefixProvider* dpp, req_state * const s, const rgw_obj& obj, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, RGWAccessControlPolicy * const object_acl, const boost::optional<Policy>& bucket_policy, const vector<Policy>& identity_policies, const vector<Policy>& session_policies, const uint64_t op) { perm_state_from_req_state ps(s); return verify_object_permission(dpp, &ps, obj, user_acl, bucket_acl, object_acl, bucket_policy, identity_policies, session_policies, op); } bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, RGWAccessControlPolicy * const object_acl, const int perm) { if (check_deferred_bucket_only_acl(dpp, s, user_acl, bucket_acl, RGW_DEFER_TO_BUCKET_ACLS_RECURSE, perm) || check_deferred_bucket_only_acl(dpp, s, user_acl, bucket_acl, RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL, RGW_PERM_FULL_CONTROL)) { return true; } if (!object_acl) { return false; } bool ret = object_acl->verify_permission(dpp, *s->identity, s->perm_mask, perm, nullptr, /* http referrer */ s->bucket_access_conf && s->bucket_access_conf->ignore_public_acls()); if (ret) { return true; } if (!s->cct->_conf->rgw_enforce_swift_acls) return ret; if ((perm & (int)s->perm_mask) != perm) return false; int swift_perm = 0; if (perm & (RGW_PERM_READ | RGW_PERM_READ_ACP)) swift_perm |= RGW_PERM_READ_OBJS; if (perm & RGW_PERM_WRITE) swift_perm |= RGW_PERM_WRITE_OBJS; if (!swift_perm) return false; /* we already verified the user mask above, so we pass swift_perm as the mask here, otherwise the mask might not cover the swift permissions bits */ if (bucket_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm, s->get_referer())) return true; if (!user_acl) return false; return user_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm); } bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp, req_state *s, int perm) { perm_state_from_req_state ps(s); if (!verify_requester_payer_permission(&ps)) return false; return verify_object_permission_no_policy(dpp, &ps, s->user_acl.get(), s->bucket_acl.get(), s->object_acl.get(), perm); } bool verify_object_permission(const DoutPrefixProvider* dpp, req_state *s, uint64_t op) { perm_state_from_req_state ps(s); return verify_object_permission(dpp, &ps, rgw_obj(s->bucket->get_key(), s->object->get_key()), s->user_acl.get(), s->bucket_acl.get(), s->object_acl.get(), s->iam_policy, s->iam_user_policies, s->session_policies, op); } int verify_object_lock(const DoutPrefixProvider* dpp, const rgw::sal::Attrs& attrs, const bool bypass_perm, const bool bypass_governance_mode) { auto aiter = attrs.find(RGW_ATTR_OBJECT_RETENTION); if (aiter != attrs.end()) { RGWObjectRetention obj_retention; try { decode(obj_retention, aiter->second); } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; return -EIO; } if (ceph::real_clock::to_time_t(obj_retention.get_retain_until_date()) > ceph_clock_now()) { if (obj_retention.get_mode().compare("GOVERNANCE") != 0 || !bypass_perm || !bypass_governance_mode) { return -EACCES; } } } aiter = attrs.find(RGW_ATTR_OBJECT_LEGAL_HOLD); if (aiter != attrs.end()) { RGWObjectLegalHold obj_legal_hold; try { decode(obj_legal_hold, aiter->second); } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; return -EIO; } if (obj_legal_hold.is_enabled()) { return -EACCES; } } return 0; } class HexTable { char table[256]; public: HexTable() { // FIPS zeroization audit 20191115: this memset is not security related. memset(table, -1, sizeof(table)); int i; for (i = '0'; i<='9'; i++) table[i] = i - '0'; for (i = 'A'; i<='F'; i++) table[i] = i - 'A' + 0xa; for (i = 'a'; i<='f'; i++) table[i] = i - 'a' + 0xa; } char to_num(char c) { return table[(int)c]; } }; static char hex_to_num(char c) { static HexTable hex_table; return hex_table.to_num(c); } std::string url_decode(const std::string_view& src_str, bool in_query) { std::string dest_str; dest_str.reserve(src_str.length() + 1); for (auto src = std::begin(src_str); src != std::end(src_str); ++src) { if (*src != '%') { if (!in_query || *src != '+') { if (*src == '?') { in_query = true; } dest_str.push_back(*src); } else { dest_str.push_back(' '); } } else { /* 3 == strlen("%%XX") */ if (std::distance(src, std::end(src_str)) < 3) { break; } src++; const char c1 = hex_to_num(*src++); const char c2 = hex_to_num(*src); if (c1 < 0 || c2 < 0) { return std::string(); } else { dest_str.push_back(c1 << 4 | c2); } } } return dest_str; } void rgw_uri_escape_char(char c, string& dst) { char buf[16]; snprintf(buf, sizeof(buf), "%%%.2X", (int)(unsigned char)c); dst.append(buf); } static bool char_needs_url_encoding(char c) { if (c <= 0x20 || c >= 0x7f) return true; switch (c) { case 0x22: case 0x23: case 0x25: case 0x26: case 0x2B: case 0x2C: case 0x2F: case 0x3A: case 0x3B: case 0x3C: case 0x3E: case 0x3D: case 0x3F: case 0x40: case 0x5B: case 0x5D: case 0x5C: case 0x5E: case 0x60: case 0x7B: case 0x7D: return true; } return false; } void url_encode(const string& src, string& dst, bool encode_slash) { const char *p = src.c_str(); for (unsigned i = 0; i < src.size(); i++, p++) { if ((!encode_slash && *p == 0x2F) || !char_needs_url_encoding(*p)) { dst.append(p, 1); }else { rgw_uri_escape_char(*p, dst); } } } std::string url_encode(const std::string& src, bool encode_slash) { std::string dst; url_encode(src, dst, encode_slash); return dst; } std::string url_remove_prefix(const std::string& url) { std::string dst = url; auto pos = dst.find("http://"); if (pos == std::string::npos) { pos = dst.find("https://"); if (pos != std::string::npos) { dst.erase(pos, 8); } else { pos = dst.find("www."); if (pos != std::string::npos) { dst.erase(pos, 4); } } } else { dst.erase(pos, 7); } return dst; } string rgw_trim_whitespace(const string& src) { if (src.empty()) { return string(); } int start = 0; for (; start != (int)src.size(); start++) { if (!isspace(src[start])) break; } int end = src.size() - 1; if (end < start) { return string(); } for (; end > start; end--) { if (!isspace(src[end])) break; } return src.substr(start, end - start + 1); } std::string_view rgw_trim_whitespace(const std::string_view& src) { std::string_view res = src; while (res.size() > 0 && std::isspace(res.front())) { res.remove_prefix(1); } while (res.size() > 0 && std::isspace(res.back())) { res.remove_suffix(1); } return res; } string rgw_trim_quotes(const string& val) { string s = rgw_trim_whitespace(val); if (s.size() < 2) return s; int start = 0; int end = s.size() - 1; int quotes_count = 0; if (s[start] == '"') { start++; quotes_count++; } if (s[end] == '"') { end--; quotes_count++; } if (quotes_count == 2) { return s.substr(start, end - start + 1); } return s; } static struct rgw_name_to_flag cap_names[] = { {"*", RGW_CAP_ALL}, {"read", RGW_CAP_READ}, {"write", RGW_CAP_WRITE}, {NULL, 0} }; static int rgw_parse_list_of_flags(struct rgw_name_to_flag *mapping, const string& str, uint32_t *perm) { list<string> strs; get_str_list(str, strs); list<string>::iterator iter; uint32_t v = 0; for (iter = strs.begin(); iter != strs.end(); ++iter) { string& s = *iter; for (int i = 0; mapping[i].type_name; i++) { if (s.compare(mapping[i].type_name) == 0) v |= mapping[i].flag; } } *perm = v; return 0; } int RGWUserCaps::parse_cap_perm(const string& str, uint32_t *perm) { return rgw_parse_list_of_flags(cap_names, str, perm); } int RGWUserCaps::get_cap(const string& cap, string& type, uint32_t *pperm) { int pos = cap.find('='); if (pos >= 0) { type = rgw_trim_whitespace(cap.substr(0, pos)); } if (!is_valid_cap_type(type)) return -ERR_INVALID_CAP; string cap_perm; uint32_t perm = 0; if (pos < (int)cap.size() - 1) { cap_perm = cap.substr(pos + 1); int r = RGWUserCaps::parse_cap_perm(cap_perm, &perm); if (r < 0) return r; } *pperm = perm; return 0; } int RGWUserCaps::add_cap(const string& cap) { uint32_t perm; string type; int r = get_cap(cap, type, &perm); if (r < 0) return r; caps[type] |= perm; return 0; } int RGWUserCaps::remove_cap(const string& cap) { uint32_t perm; string type; int r = get_cap(cap, type, &perm); if (r < 0) return r; map<string, uint32_t>::iterator iter = caps.find(type); if (iter == caps.end()) return 0; uint32_t& old_perm = iter->second; old_perm &= ~perm; if (!old_perm) caps.erase(iter); return 0; } int RGWUserCaps::add_from_string(const string& str) { int start = 0; do { auto end = str.find(';', start); if (end == string::npos) end = str.size(); int r = add_cap(str.substr(start, end - start)); if (r < 0) return r; start = end + 1; } while (start < (int)str.size()); return 0; } int RGWUserCaps::remove_from_string(const string& str) { int start = 0; do { auto end = str.find(';', start); if (end == string::npos) end = str.size(); int r = remove_cap(str.substr(start, end - start)); if (r < 0) return r; start = end + 1; } while (start < (int)str.size()); return 0; } void RGWUserCaps::dump(Formatter *f) const { dump(f, "caps"); } void RGWUserCaps::dump(Formatter *f, const char *name) const { f->open_array_section(name); map<string, uint32_t>::const_iterator iter; for (iter = caps.begin(); iter != caps.end(); ++iter) { f->open_object_section("cap"); f->dump_string("type", iter->first); uint32_t perm = iter->second; string perm_str; for (int i=0; cap_names[i].type_name; i++) { if ((perm & cap_names[i].flag) == cap_names[i].flag) { if (perm_str.size()) perm_str.append(", "); perm_str.append(cap_names[i].type_name); perm &= ~cap_names[i].flag; } } if (perm_str.empty()) perm_str = "<none>"; f->dump_string("perm", perm_str); f->close_section(); } f->close_section(); } struct RGWUserCap { string type; uint32_t perm; void decode_json(JSONObj *obj) { JSONDecoder::decode_json("type", type, obj); string perm_str; JSONDecoder::decode_json("perm", perm_str, obj); if (RGWUserCaps::parse_cap_perm(perm_str, &perm) < 0) { throw JSONDecoder::err("failed to parse permissions"); } } }; void RGWUserCaps::decode_json(JSONObj *obj) { list<RGWUserCap> caps_list; decode_json_obj(caps_list, obj); list<RGWUserCap>::iterator iter; for (iter = caps_list.begin(); iter != caps_list.end(); ++iter) { RGWUserCap& cap = *iter; caps[cap.type] = cap.perm; } } int RGWUserCaps::check_cap(const string& cap, uint32_t perm) const { auto iter = caps.find(cap); if ((iter == caps.end()) || (iter->second & perm) != perm) { return -EPERM; } return 0; } bool RGWUserCaps::is_valid_cap_type(const string& tp) { static const char *cap_type[] = { "user", "users", "buckets", "metadata", "info", "usage", "zone", "bilog", "mdlog", "datalog", "roles", "user-policy", "amz-cache", "oidc-provider", "ratelimit"}; for (unsigned int i = 0; i < sizeof(cap_type) / sizeof(char *); ++i) { if (tp.compare(cap_type[i]) == 0) { return true; } } return false; } void rgw_pool::from_str(const string& s) { size_t pos = rgw_unescape_str(s, 0, '\\', ':', &name); if (pos != string::npos) { pos = rgw_unescape_str(s, pos, '\\', ':', &ns); /* ignore return; if pos != string::npos it means that we had a colon * in the middle of ns that wasn't escaped, we're going to stop there */ } } string rgw_pool::to_str() const { string esc_name; rgw_escape_str(name, '\\', ':', &esc_name); if (ns.empty()) { return esc_name; } string esc_ns; rgw_escape_str(ns, '\\', ':', &esc_ns); return esc_name + ":" + esc_ns; } void rgw_raw_obj::decode_from_rgw_obj(bufferlist::const_iterator& bl) { using ceph::decode; rgw_obj old_obj; decode(old_obj, bl); get_obj_bucket_and_oid_loc(old_obj, oid, loc); pool = old_obj.get_explicit_data_pool(); } static struct rgw_name_to_flag op_type_mapping[] = { {"*", RGW_OP_TYPE_ALL}, {"read", RGW_OP_TYPE_READ}, {"write", RGW_OP_TYPE_WRITE}, {"delete", RGW_OP_TYPE_DELETE}, {NULL, 0} }; int rgw_parse_op_type_list(const string& str, uint32_t *perm) { return rgw_parse_list_of_flags(op_type_mapping, str, perm); } bool match_policy(std::string_view pattern, std::string_view input, uint32_t flag) { const uint32_t flag2 = flag & (MATCH_POLICY_ACTION|MATCH_POLICY_ARN) ? MATCH_CASE_INSENSITIVE : 0; const bool colonblocks = !(flag & (MATCH_POLICY_RESOURCE | MATCH_POLICY_STRING)); const auto npos = std::string_view::npos; std::string_view::size_type last_pos_input = 0, last_pos_pattern = 0; while (true) { auto cur_pos_input = colonblocks ? input.find(":", last_pos_input) : npos; auto cur_pos_pattern = colonblocks ? pattern.find(":", last_pos_pattern) : npos; auto substr_input = input.substr(last_pos_input, cur_pos_input); auto substr_pattern = pattern.substr(last_pos_pattern, cur_pos_pattern); if (!match_wildcards(substr_pattern, substr_input, flag2)) return false; if (cur_pos_pattern == npos) return cur_pos_input == npos; if (cur_pos_input == npos) return false; last_pos_pattern = cur_pos_pattern + 1; last_pos_input = cur_pos_input + 1; } } /* * make attrs look-like-this * converts underscores to dashes */ string lowercase_dash_http_attr(const string& orig) { const char *s = orig.c_str(); char buf[orig.size() + 1]; buf[orig.size()] = '\0'; for (size_t i = 0; i < orig.size(); ++i, ++s) { switch (*s) { case '_': buf[i] = '-'; break; default: buf[i] = tolower(*s); } } return string(buf); } /* * make attrs Look-Like-This * converts underscores to dashes */ string camelcase_dash_http_attr(const string& orig) { const char *s = orig.c_str(); char buf[orig.size() + 1]; buf[orig.size()] = '\0'; bool last_sep = true; for (size_t i = 0; i < orig.size(); ++i, ++s) { switch (*s) { case '_': case '-': buf[i] = '-'; last_sep = true; break; default: if (last_sep) { buf[i] = toupper(*s); } else { buf[i] = tolower(*s); } last_sep = false; } } return string(buf); } RGWBucketInfo::RGWBucketInfo() { } RGWBucketInfo::~RGWBucketInfo() { } void RGWBucketInfo::encode(bufferlist& bl) const { ENCODE_START(23, 4, bl); encode(bucket, bl); encode(owner.id, bl); encode(flags, bl); encode(zonegroup, bl); uint64_t ct = real_clock::to_time_t(creation_time); encode(ct, bl); encode(placement_rule, bl); encode(has_instance_obj, bl); encode(quota, bl); encode(requester_pays, bl); encode(owner.tenant, bl); encode(has_website, bl); if (has_website) { encode(website_conf, bl); } encode(swift_versioning, bl); if (swift_versioning) { encode(swift_ver_location, bl); } encode(creation_time, bl); encode(mdsearch_config, bl); encode(reshard_status, bl); encode(new_bucket_instance_id, bl); if (obj_lock_enabled()) { encode(obj_lock, bl); } bool has_sync_policy = !empty_sync_policy(); encode(has_sync_policy, bl); if (has_sync_policy) { encode(*sync_policy, bl); } encode(layout, bl); encode(owner.ns, bl); ENCODE_FINISH(bl); } void RGWBucketInfo::decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN_32(23, 4, 4, bl); decode(bucket, bl); if (struct_v >= 2) { string s; decode(s, bl); owner.from_str(s); } if (struct_v >= 3) decode(flags, bl); if (struct_v >= 5) decode(zonegroup, bl); if (struct_v >= 6) { uint64_t ct; decode(ct, bl); if (struct_v < 17) creation_time = ceph::real_clock::from_time_t((time_t)ct); } if (struct_v >= 7) decode(placement_rule, bl); if (struct_v >= 8) decode(has_instance_obj, bl); if (struct_v >= 9) decode(quota, bl); static constexpr uint8_t new_layout_v = 22; if (struct_v >= 10 && struct_v < new_layout_v) decode(layout.current_index.layout.normal.num_shards, bl); if (struct_v >= 11 && struct_v < new_layout_v) decode(layout.current_index.layout.normal.hash_type, bl); if (struct_v >= 12) decode(requester_pays, bl); if (struct_v >= 13) decode(owner.tenant, bl); if (struct_v >= 14) { decode(has_website, bl); if (has_website) { decode(website_conf, bl); } else { website_conf = RGWBucketWebsiteConf(); } } if (struct_v >= 15 && struct_v < new_layout_v) { uint32_t it; decode(it, bl); layout.current_index.layout.type = (rgw::BucketIndexType)it; } else { layout.current_index.layout.type = rgw::BucketIndexType::Normal; } swift_versioning = false; swift_ver_location.clear(); if (struct_v >= 16) { decode(swift_versioning, bl); if (swift_versioning) { decode(swift_ver_location, bl); } } if (struct_v >= 17) { decode(creation_time, bl); } if (struct_v >= 18) { decode(mdsearch_config, bl); } if (struct_v >= 19) { decode(reshard_status, bl); decode(new_bucket_instance_id, bl); } if (struct_v >= 20 && obj_lock_enabled()) { decode(obj_lock, bl); } if (struct_v >= 21) { decode(sync_policy, bl); } if (struct_v >= 22) { decode(layout, bl); } if (struct_v >= 23) { decode(owner.ns, bl); } if (layout.logs.empty() && layout.current_index.layout.type == rgw::BucketIndexType::Normal) { layout.logs.push_back(rgw::log_layout_from_index(0, layout.current_index)); } DECODE_FINISH(bl); } void RGWBucketInfo::set_sync_policy(rgw_sync_policy_info&& policy) { sync_policy = std::move(policy); } bool RGWBucketInfo::empty_sync_policy() const { if (!sync_policy) { return true; } return sync_policy->empty(); } struct rgw_pool; struct rgw_placement_rule; class RGWUserCaps; void decode_json_obj(rgw_pool& pool, JSONObj *obj) { string s; decode_json_obj(s, obj); pool = rgw_pool(s); } void encode_json(const char *name, const rgw_placement_rule& r, Formatter *f) { encode_json(name, r.to_str(), f); } void encode_json(const char *name, const rgw_pool& pool, Formatter *f) { f->dump_string(name, pool.to_str()); } void encode_json(const char *name, const RGWUserCaps& val, Formatter *f) { val.dump(f, name); } void RGWBucketEnt::generate_test_instances(list<RGWBucketEnt*>& o) { RGWBucketEnt *e = new RGWBucketEnt; init_bucket(&e->bucket, "tenant", "bucket", "pool", ".index_pool", "marker", "10"); e->size = 1024; e->size_rounded = 4096; e->count = 1; o.push_back(e); o.push_back(new RGWBucketEnt); } void RGWBucketEnt::dump(Formatter *f) const { encode_json("bucket", bucket, f); encode_json("size", size, f); encode_json("size_rounded", size_rounded, f); utime_t ut(creation_time); encode_json("mtime", ut, f); /* mtime / creation time discrepency needed for backward compatibility */ encode_json("count", count, f); encode_json("placement_rule", placement_rule.to_str(), f); } void rgw_obj::generate_test_instances(list<rgw_obj*>& o) { rgw_bucket b; init_bucket(&b, "tenant", "bucket", "pool", ".index_pool", "marker", "10"); rgw_obj *obj = new rgw_obj(b, "object"); o.push_back(obj); o.push_back(new rgw_obj); } void rgw_bucket_placement::dump(Formatter *f) const { encode_json("bucket", bucket, f); encode_json("placement_rule", placement_rule, f); } void RGWBucketInfo::generate_test_instances(list<RGWBucketInfo*>& o) { // Since things without a log will have one synthesized on decode, // ensure the things we attempt to encode will have one added so we // round-trip properly. auto gen_layout = [](rgw::BucketLayout& l) { l.current_index.gen = 0; l.current_index.layout.normal.hash_type = rgw::BucketHashType::Mod; l.current_index.layout.type = rgw::BucketIndexType::Normal; l.current_index.layout.normal.num_shards = 11; l.logs.push_back(log_layout_from_index( l.current_index.gen, l.current_index)); }; RGWBucketInfo *i = new RGWBucketInfo; init_bucket(&i->bucket, "tenant", "bucket", "pool", ".index_pool", "marker", "10"); i->owner = "owner"; i->flags = BUCKET_SUSPENDED; gen_layout(i->layout); o.push_back(i); i = new RGWBucketInfo; gen_layout(i->layout); o.push_back(i); } void RGWBucketInfo::dump(Formatter *f) const { encode_json("bucket", bucket, f); utime_t ut(creation_time); encode_json("creation_time", ut, f); encode_json("owner", owner.to_str(), f); encode_json("flags", flags, f); encode_json("zonegroup", zonegroup, f); encode_json("placement_rule", placement_rule, f); encode_json("has_instance_obj", has_instance_obj, f); encode_json("quota", quota, f); encode_json("num_shards", layout.current_index.layout.normal.num_shards, f); encode_json("bi_shard_hash_type", (uint32_t)layout.current_index.layout.normal.hash_type, f); encode_json("requester_pays", requester_pays, f); encode_json("has_website", has_website, f); if (has_website) { encode_json("website_conf", website_conf, f); } encode_json("swift_versioning", swift_versioning, f); encode_json("swift_ver_location", swift_ver_location, f); encode_json("index_type", (uint32_t)layout.current_index.layout.type, f); encode_json("mdsearch_config", mdsearch_config, f); encode_json("reshard_status", (int)reshard_status, f); encode_json("new_bucket_instance_id", new_bucket_instance_id, f); if (!empty_sync_policy()) { encode_json("sync_policy", *sync_policy, f); } } void RGWBucketInfo::decode_json(JSONObj *obj) { JSONDecoder::decode_json("bucket", bucket, obj); utime_t ut; JSONDecoder::decode_json("creation_time", ut, obj); creation_time = ut.to_real_time(); JSONDecoder::decode_json("owner", owner, obj); JSONDecoder::decode_json("flags", flags, obj); JSONDecoder::decode_json("zonegroup", zonegroup, obj); /* backward compatability with region */ if (zonegroup.empty()) { JSONDecoder::decode_json("region", zonegroup, obj); } string pr; JSONDecoder::decode_json("placement_rule", pr, obj); placement_rule.from_str(pr); JSONDecoder::decode_json("has_instance_obj", has_instance_obj, obj); JSONDecoder::decode_json("quota", quota, obj); JSONDecoder::decode_json("num_shards", layout.current_index.layout.normal.num_shards, obj); uint32_t hash_type; JSONDecoder::decode_json("bi_shard_hash_type", hash_type, obj); layout.current_index.layout.normal.hash_type = static_cast<rgw::BucketHashType>(hash_type); JSONDecoder::decode_json("requester_pays", requester_pays, obj); JSONDecoder::decode_json("has_website", has_website, obj); if (has_website) { JSONDecoder::decode_json("website_conf", website_conf, obj); } JSONDecoder::decode_json("swift_versioning", swift_versioning, obj); JSONDecoder::decode_json("swift_ver_location", swift_ver_location, obj); uint32_t it; JSONDecoder::decode_json("index_type", it, obj); layout.current_index.layout.type = (rgw::BucketIndexType)it; JSONDecoder::decode_json("mdsearch_config", mdsearch_config, obj); int rs; JSONDecoder::decode_json("reshard_status", rs, obj); reshard_status = (cls_rgw_reshard_status)rs; rgw_sync_policy_info sp; JSONDecoder::decode_json("sync_policy", sp, obj); if (!sp.empty()) { set_sync_policy(std::move(sp)); } } void RGWUserInfo::generate_test_instances(list<RGWUserInfo*>& o) { RGWUserInfo *i = new RGWUserInfo; i->user_id = "user_id"; i->display_name = "display_name"; i->user_email = "user@email"; RGWAccessKey k1, k2; k1.id = "id1"; k1.key = "key1"; k2.id = "id2"; k2.subuser = "subuser"; RGWSubUser u; u.name = "id2"; u.perm_mask = 0x1; i->access_keys[k1.id] = k1; i->swift_keys[k2.id] = k2; i->subusers[u.name] = u; o.push_back(i); o.push_back(new RGWUserInfo); } static void user_info_dump_subuser(const char *name, const RGWSubUser& subuser, Formatter *f, void *parent) { RGWUserInfo *info = static_cast<RGWUserInfo *>(parent); subuser.dump(f, info->user_id.to_str()); } static void user_info_dump_key(const char *name, const RGWAccessKey& key, Formatter *f, void *parent) { RGWUserInfo *info = static_cast<RGWUserInfo *>(parent); key.dump(f, info->user_id.to_str(), false); } static void user_info_dump_swift_key(const char *name, const RGWAccessKey& key, Formatter *f, void *parent) { RGWUserInfo *info = static_cast<RGWUserInfo *>(parent); key.dump(f, info->user_id.to_str(), true); } static void decode_access_keys(map<string, RGWAccessKey>& m, JSONObj *o) { RGWAccessKey k; k.decode_json(o); m[k.id] = k; } static void decode_swift_keys(map<string, RGWAccessKey>& m, JSONObj *o) { RGWAccessKey k; k.decode_json(o, true); m[k.id] = k; } static void decode_subusers(map<string, RGWSubUser>& m, JSONObj *o) { RGWSubUser u; u.decode_json(o); m[u.name] = u; } struct rgw_flags_desc { uint32_t mask; const char *str; }; static struct rgw_flags_desc rgw_perms[] = { { RGW_PERM_FULL_CONTROL, "full-control" }, { RGW_PERM_READ | RGW_PERM_WRITE, "read-write" }, { RGW_PERM_READ, "read" }, { RGW_PERM_WRITE, "write" }, { RGW_PERM_READ_ACP, "read-acp" }, { RGW_PERM_WRITE_ACP, "write-acp" }, { 0, NULL } }; void rgw_perm_to_str(uint32_t mask, char *buf, int len) { const char *sep = ""; int pos = 0; if (!mask) { snprintf(buf, len, "<none>"); return; } while (mask) { uint32_t orig_mask = mask; for (int i = 0; rgw_perms[i].mask; i++) { struct rgw_flags_desc *desc = &rgw_perms[i]; if ((mask & desc->mask) == desc->mask) { pos += snprintf(buf + pos, len - pos, "%s%s", sep, desc->str); if (pos == len) return; sep = ", "; mask &= ~desc->mask; if (!mask) return; } } if (mask == orig_mask) // no change break; } } uint32_t rgw_str_to_perm(const char *str) { if (strcasecmp(str, "") == 0) return RGW_PERM_NONE; else if (strcasecmp(str, "read") == 0) return RGW_PERM_READ; else if (strcasecmp(str, "write") == 0) return RGW_PERM_WRITE; else if (strcasecmp(str, "readwrite") == 0) return RGW_PERM_READ | RGW_PERM_WRITE; else if (strcasecmp(str, "full") == 0) return RGW_PERM_FULL_CONTROL; return RGW_PERM_INVALID; } template <class T> static void mask_to_str(T *mask_list, uint32_t mask, char *buf, int len) { const char *sep = ""; int pos = 0; if (!mask) { snprintf(buf, len, "<none>"); return; } while (mask) { uint32_t orig_mask = mask; for (int i = 0; mask_list[i].mask; i++) { T *desc = &mask_list[i]; if ((mask & desc->mask) == desc->mask) { pos += snprintf(buf + pos, len - pos, "%s%s", sep, desc->str); if (pos == len) return; sep = ", "; mask &= ~desc->mask; if (!mask) return; } } if (mask == orig_mask) // no change break; } } static void perm_to_str(uint32_t mask, char *buf, int len) { return mask_to_str(rgw_perms, mask, buf, len); } static struct rgw_flags_desc op_type_flags[] = { { RGW_OP_TYPE_READ, "read" }, { RGW_OP_TYPE_WRITE, "write" }, { RGW_OP_TYPE_DELETE, "delete" }, { 0, NULL } }; void op_type_to_str(uint32_t mask, char *buf, int len) { return mask_to_str(op_type_flags, mask, buf, len); } void RGWRateLimitInfo::decode_json(JSONObj *obj) { JSONDecoder::decode_json("max_read_ops", max_read_ops, obj); JSONDecoder::decode_json("max_write_ops", max_write_ops, obj); JSONDecoder::decode_json("max_read_bytes", max_read_ops, obj); JSONDecoder::decode_json("max_write_bytes", max_write_ops, obj); JSONDecoder::decode_json("enabled", enabled, obj); } void RGWRateLimitInfo::dump(Formatter *f) const { f->dump_int("max_read_ops", max_read_ops); f->dump_int("max_write_ops", max_write_ops); f->dump_int("max_read_bytes", max_read_bytes); f->dump_int("max_write_bytes", max_write_bytes); f->dump_bool("enabled", enabled); } void RGWUserInfo::dump(Formatter *f) const { encode_json("user_id", user_id.to_str(), f); encode_json("display_name", display_name, f); encode_json("email", user_email, f); encode_json("suspended", (int)suspended, f); encode_json("max_buckets", (int)max_buckets, f); encode_json_map("subusers", NULL, "subuser", NULL, user_info_dump_subuser,(void *)this, subusers, f); encode_json_map("keys", NULL, "key", NULL, user_info_dump_key,(void *)this, access_keys, f); encode_json_map("swift_keys", NULL, "key", NULL, user_info_dump_swift_key,(void *)this, swift_keys, f); encode_json("caps", caps, f); char buf[256]; op_type_to_str(op_mask, buf, sizeof(buf)); encode_json("op_mask", (const char *)buf, f); if (system) { /* no need to show it for every user */ encode_json("system", (bool)system, f); } if (admin) { encode_json("admin", (bool)admin, f); } encode_json("default_placement", default_placement.name, f); encode_json("default_storage_class", default_placement.storage_class, f); encode_json("placement_tags", placement_tags, f); encode_json("bucket_quota", quota.bucket_quota, f); encode_json("user_quota", quota.user_quota, f); encode_json("temp_url_keys", temp_url_keys, f); string user_source_type; switch ((RGWIdentityType)type) { case TYPE_RGW: user_source_type = "rgw"; break; case TYPE_KEYSTONE: user_source_type = "keystone"; break; case TYPE_LDAP: user_source_type = "ldap"; break; case TYPE_NONE: user_source_type = "none"; break; default: user_source_type = "none"; break; } encode_json("type", user_source_type, f); encode_json("mfa_ids", mfa_ids, f); } void RGWUserInfo::decode_json(JSONObj *obj) { string uid; JSONDecoder::decode_json("user_id", uid, obj, true); user_id.from_str(uid); JSONDecoder::decode_json("display_name", display_name, obj); JSONDecoder::decode_json("email", user_email, obj); bool susp = false; JSONDecoder::decode_json("suspended", susp, obj); suspended = (__u8)susp; JSONDecoder::decode_json("max_buckets", max_buckets, obj); JSONDecoder::decode_json("keys", access_keys, decode_access_keys, obj); JSONDecoder::decode_json("swift_keys", swift_keys, decode_swift_keys, obj); JSONDecoder::decode_json("subusers", subusers, decode_subusers, obj); JSONDecoder::decode_json("caps", caps, obj); string mask_str; JSONDecoder::decode_json("op_mask", mask_str, obj); rgw_parse_op_type_list(mask_str, &op_mask); bool sys = false; JSONDecoder::decode_json("system", sys, obj); system = (__u8)sys; bool ad = false; JSONDecoder::decode_json("admin", ad, obj); admin = (__u8)ad; JSONDecoder::decode_json("default_placement", default_placement.name, obj); JSONDecoder::decode_json("default_storage_class", default_placement.storage_class, obj); JSONDecoder::decode_json("placement_tags", placement_tags, obj); JSONDecoder::decode_json("bucket_quota", quota.bucket_quota, obj); JSONDecoder::decode_json("user_quota", quota.user_quota, obj); JSONDecoder::decode_json("temp_url_keys", temp_url_keys, obj); string user_source_type; JSONDecoder::decode_json("type", user_source_type, obj); if (user_source_type == "rgw") { type = TYPE_RGW; } else if (user_source_type == "keystone") { type = TYPE_KEYSTONE; } else if (user_source_type == "ldap") { type = TYPE_LDAP; } else if (user_source_type == "none") { type = TYPE_NONE; } JSONDecoder::decode_json("mfa_ids", mfa_ids, obj); } void RGWSubUser::generate_test_instances(list<RGWSubUser*>& o) { RGWSubUser *u = new RGWSubUser; u->name = "name"; u->perm_mask = 0xf; o.push_back(u); o.push_back(new RGWSubUser); } void RGWSubUser::dump(Formatter *f) const { encode_json("id", name, f); char buf[256]; perm_to_str(perm_mask, buf, sizeof(buf)); encode_json("permissions", (const char *)buf, f); } void RGWSubUser::dump(Formatter *f, const string& user) const { string s = user; s.append(":"); s.append(name); encode_json("id", s, f); char buf[256]; perm_to_str(perm_mask, buf, sizeof(buf)); encode_json("permissions", (const char *)buf, f); } uint32_t str_to_perm(const string& s) { if (s.compare("read") == 0) return RGW_PERM_READ; else if (s.compare("write") == 0) return RGW_PERM_WRITE; else if (s.compare("read-write") == 0) return RGW_PERM_READ | RGW_PERM_WRITE; else if (s.compare("full-control") == 0) return RGW_PERM_FULL_CONTROL; return 0; } void RGWSubUser::decode_json(JSONObj *obj) { string uid; JSONDecoder::decode_json("id", uid, obj); int pos = uid.find(':'); if (pos >= 0) name = uid.substr(pos + 1); string perm_str; JSONDecoder::decode_json("permissions", perm_str, obj); perm_mask = str_to_perm(perm_str); } void RGWAccessKey::generate_test_instances(list<RGWAccessKey*>& o) { RGWAccessKey *k = new RGWAccessKey; k->id = "id"; k->key = "key"; k->subuser = "subuser"; o.push_back(k); o.push_back(new RGWAccessKey); } void RGWAccessKey::dump(Formatter *f) const { encode_json("access_key", id, f); encode_json("secret_key", key, f); encode_json("subuser", subuser, f); } void RGWAccessKey::dump_plain(Formatter *f) const { encode_json("access_key", id, f); encode_json("secret_key", key, f); } void RGWAccessKey::dump(Formatter *f, const string& user, bool swift) const { string u = user; if (!subuser.empty()) { u.append(":"); u.append(subuser); } encode_json("user", u, f); if (!swift) { encode_json("access_key", id, f); } encode_json("secret_key", key, f); } void RGWAccessKey::decode_json(JSONObj *obj) { JSONDecoder::decode_json("access_key", id, obj, true); JSONDecoder::decode_json("secret_key", key, obj, true); if (!JSONDecoder::decode_json("subuser", subuser, obj)) { string user; JSONDecoder::decode_json("user", user, obj); int pos = user.find(':'); if (pos >= 0) { subuser = user.substr(pos + 1); } } } void RGWAccessKey::decode_json(JSONObj *obj, bool swift) { if (!swift) { decode_json(obj); return; } if (!JSONDecoder::decode_json("subuser", subuser, obj)) { JSONDecoder::decode_json("user", id, obj, true); int pos = id.find(':'); if (pos >= 0) { subuser = id.substr(pos + 1); } } JSONDecoder::decode_json("secret_key", key, obj, true); } void RGWStorageStats::dump(Formatter *f) const { encode_json("size", size, f); encode_json("size_actual", size_rounded, f); if (dump_utilized) { encode_json("size_utilized", size_utilized, f); } encode_json("size_kb", rgw_rounded_kb(size), f); encode_json("size_kb_actual", rgw_rounded_kb(size_rounded), f); if (dump_utilized) { encode_json("size_kb_utilized", rgw_rounded_kb(size_utilized), f); } encode_json("num_objects", num_objects, f); } void rgw_obj_key::dump(Formatter *f) const { encode_json("name", name, f); encode_json("instance", instance, f); encode_json("ns", ns, f); } void rgw_obj_key::decode_json(JSONObj *obj) { JSONDecoder::decode_json("name", name, obj); JSONDecoder::decode_json("instance", instance, obj); JSONDecoder::decode_json("ns", ns, obj); } void rgw_raw_obj::dump(Formatter *f) const { encode_json("pool", pool, f); encode_json("oid", oid, f); encode_json("loc", loc, f); } void rgw_raw_obj::decode_json(JSONObj *obj) { JSONDecoder::decode_json("pool", pool, obj); JSONDecoder::decode_json("oid", oid, obj); JSONDecoder::decode_json("loc", loc, obj); } void rgw_obj::dump(Formatter *f) const { encode_json("bucket", bucket, f); encode_json("key", key, f); } int rgw_bucket_parse_bucket_instance(const string& bucket_instance, string *bucket_name, string *bucket_id, int *shard_id) { auto pos = bucket_instance.rfind(':'); if (pos == string::npos) { return -EINVAL; } string first = bucket_instance.substr(0, pos); string second = bucket_instance.substr(pos + 1); pos = first.find(':'); if (pos == string::npos) { *shard_id = -1; *bucket_name = first; *bucket_id = second; return 0; } *bucket_name = first.substr(0, pos); *bucket_id = first.substr(pos + 1); string err; *shard_id = strict_strtol(second.c_str(), 10, &err); if (!err.empty()) { return -EINVAL; } return 0; } boost::intrusive_ptr<CephContext> rgw_global_init(const std::map<std::string,std::string> *defaults, std::vector < const char* >& args, uint32_t module_type, code_environment_t code_env, int flags) { // Load the config from the files, but not the mon global_pre_init(defaults, args, module_type, code_env, flags); // Get the store backend const auto& config_store = g_conf().get_val<std::string>("rgw_backend_store"); if ((config_store == "dbstore") || (config_store == "motr") || (config_store == "daos")) { // These stores don't use the mon flags |= CINIT_FLAG_NO_MON_CONFIG; } // Finish global init, indicating we already ran pre-init return global_init(defaults, args, module_type, code_env, flags, false); } void RGWObjVersionTracker::generate_new_write_ver(CephContext *cct) { write_version.ver = 1; #define TAG_LEN 24 write_version.tag.clear(); append_rand_alpha(cct, write_version.tag, write_version.tag, TAG_LEN); }
88,229
27.683355
150
cc
null
ceph-main/src/rgw/rgw_common.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) 2004-2009 Sage Weil <[email protected]> * Copyright (C) 2015 Yehuda Sadeh <[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 <array> #include <string_view> #include <atomic> #include <unordered_map> #include <fmt/format.h> #include "common/ceph_crypto.h" #include "common/random_string.h" #include "rgw_acl.h" #include "rgw_bucket_layout.h" #include "rgw_cors.h" #include "rgw_basic_types.h" #include "rgw_iam_policy.h" #include "rgw_quota_types.h" #include "rgw_string.h" #include "common/async/yield_context.h" #include "rgw_website.h" #include "rgw_object_lock.h" #include "rgw_tag.h" #include "rgw_op_type.h" #include "rgw_sync_policy.h" #include "cls/version/cls_version_types.h" #include "cls/user/cls_user_types.h" #include "cls/rgw/cls_rgw_types.h" #include "include/rados/librados.hpp" #include "rgw_public_access.h" #include "common/tracer.h" #include "rgw_sal_fwd.h" namespace ceph { class Formatter; } namespace rgw::sal { using Attrs = std::map<std::string, ceph::buffer::list>; } namespace rgw::lua { class Background; } struct RGWProcessEnv; using ceph::crypto::MD5; #define RGW_ATTR_PREFIX "user.rgw." #define RGW_HTTP_RGWX_ATTR_PREFIX "RGWX_ATTR_" #define RGW_HTTP_RGWX_ATTR_PREFIX_OUT "Rgwx-Attr-" #define RGW_AMZ_PREFIX "x-amz-" #define RGW_AMZ_META_PREFIX RGW_AMZ_PREFIX "meta-" #define RGW_AMZ_WEBSITE_REDIRECT_LOCATION RGW_AMZ_PREFIX "website-redirect-location" #define RGW_AMZ_TAG_COUNT RGW_AMZ_PREFIX "tagging-count" #define RGW_SYS_PARAM_PREFIX "rgwx-" #define RGW_ATTR_ACL RGW_ATTR_PREFIX "acl" #define RGW_ATTR_RATELIMIT RGW_ATTR_PREFIX "ratelimit" #define RGW_ATTR_LC RGW_ATTR_PREFIX "lc" #define RGW_ATTR_CORS RGW_ATTR_PREFIX "cors" #define RGW_ATTR_ETAG RGW_ATTR_PREFIX "etag" #define RGW_ATTR_BUCKETS RGW_ATTR_PREFIX "buckets" #define RGW_ATTR_META_PREFIX RGW_ATTR_PREFIX RGW_AMZ_META_PREFIX #define RGW_ATTR_CONTENT_TYPE RGW_ATTR_PREFIX "content_type" #define RGW_ATTR_CACHE_CONTROL RGW_ATTR_PREFIX "cache_control" #define RGW_ATTR_CONTENT_DISP RGW_ATTR_PREFIX "content_disposition" #define RGW_ATTR_CONTENT_ENC RGW_ATTR_PREFIX "content_encoding" #define RGW_ATTR_CONTENT_LANG RGW_ATTR_PREFIX "content_language" #define RGW_ATTR_EXPIRES RGW_ATTR_PREFIX "expires" #define RGW_ATTR_DELETE_AT RGW_ATTR_PREFIX "delete_at" #define RGW_ATTR_ID_TAG RGW_ATTR_PREFIX "idtag" #define RGW_ATTR_TAIL_TAG RGW_ATTR_PREFIX "tail_tag" #define RGW_ATTR_SHADOW_OBJ RGW_ATTR_PREFIX "shadow_name" #define RGW_ATTR_MANIFEST RGW_ATTR_PREFIX "manifest" #define RGW_ATTR_USER_MANIFEST RGW_ATTR_PREFIX "user_manifest" #define RGW_ATTR_AMZ_WEBSITE_REDIRECT_LOCATION RGW_ATTR_PREFIX RGW_AMZ_WEBSITE_REDIRECT_LOCATION #define RGW_ATTR_SLO_MANIFEST RGW_ATTR_PREFIX "slo_manifest" /* Information whether an object is SLO or not must be exposed to * user through custom HTTP header named X-Static-Large-Object. */ #define RGW_ATTR_SLO_UINDICATOR RGW_ATTR_META_PREFIX "static-large-object" #define RGW_ATTR_X_ROBOTS_TAG RGW_ATTR_PREFIX "x-robots-tag" #define RGW_ATTR_STORAGE_CLASS RGW_ATTR_PREFIX "storage_class" /* S3 Object Lock*/ #define RGW_ATTR_OBJECT_LOCK RGW_ATTR_PREFIX "object-lock" #define RGW_ATTR_OBJECT_RETENTION RGW_ATTR_PREFIX "object-retention" #define RGW_ATTR_OBJECT_LEGAL_HOLD RGW_ATTR_PREFIX "object-legal-hold" #define RGW_ATTR_PG_VER RGW_ATTR_PREFIX "pg_ver" #define RGW_ATTR_SOURCE_ZONE RGW_ATTR_PREFIX "source_zone" #define RGW_ATTR_TAGS RGW_ATTR_PREFIX RGW_AMZ_PREFIX "tagging" #define RGW_ATTR_TEMPURL_KEY1 RGW_ATTR_META_PREFIX "temp-url-key" #define RGW_ATTR_TEMPURL_KEY2 RGW_ATTR_META_PREFIX "temp-url-key-2" /* Account/container quota of the Swift API. */ #define RGW_ATTR_QUOTA_NOBJS RGW_ATTR_META_PREFIX "quota-count" #define RGW_ATTR_QUOTA_MSIZE RGW_ATTR_META_PREFIX "quota-bytes" /* Static Web Site of Swift API. */ #define RGW_ATTR_WEB_INDEX RGW_ATTR_META_PREFIX "web-index" #define RGW_ATTR_WEB_ERROR RGW_ATTR_META_PREFIX "web-error" #define RGW_ATTR_WEB_LISTINGS RGW_ATTR_META_PREFIX "web-listings" #define RGW_ATTR_WEB_LIST_CSS RGW_ATTR_META_PREFIX "web-listings-css" #define RGW_ATTR_SUBDIR_MARKER RGW_ATTR_META_PREFIX "web-directory-type" #define RGW_ATTR_OLH_PREFIX RGW_ATTR_PREFIX "olh." #define RGW_ATTR_OLH_INFO RGW_ATTR_OLH_PREFIX "info" #define RGW_ATTR_OLH_VER RGW_ATTR_OLH_PREFIX "ver" #define RGW_ATTR_OLH_ID_TAG RGW_ATTR_OLH_PREFIX "idtag" #define RGW_ATTR_OLH_PENDING_PREFIX RGW_ATTR_OLH_PREFIX "pending." #define RGW_ATTR_COMPRESSION RGW_ATTR_PREFIX "compression" #define RGW_ATTR_TORRENT RGW_ATTR_PREFIX "torrent" #define RGW_ATTR_APPEND_PART_NUM RGW_ATTR_PREFIX "append_part_num" /* Attrs to store cloudtier config information. These are used internally * for the replication of cloudtiered objects but not stored as xattrs in * the head object. */ #define RGW_ATTR_CLOUD_TIER_TYPE RGW_ATTR_PREFIX "cloud_tier_type" #define RGW_ATTR_CLOUD_TIER_CONFIG RGW_ATTR_PREFIX "cloud_tier_config" #define RGW_ATTR_OBJ_REPLICATION_STATUS RGW_ATTR_PREFIX "amz-replication-status" #define RGW_ATTR_OBJ_REPLICATION_TRACE RGW_ATTR_PREFIX "replication-trace" /* IAM Policy */ #define RGW_ATTR_IAM_POLICY RGW_ATTR_PREFIX "iam-policy" #define RGW_ATTR_USER_POLICY RGW_ATTR_PREFIX "user-policy" #define RGW_ATTR_PUBLIC_ACCESS RGW_ATTR_PREFIX "public-access" /* RGW File Attributes */ #define RGW_ATTR_UNIX_KEY1 RGW_ATTR_PREFIX "unix-key1" #define RGW_ATTR_UNIX1 RGW_ATTR_PREFIX "unix1" #define RGW_ATTR_CRYPT_PREFIX RGW_ATTR_PREFIX "crypt." #define RGW_ATTR_CRYPT_MODE RGW_ATTR_CRYPT_PREFIX "mode" #define RGW_ATTR_CRYPT_KEYMD5 RGW_ATTR_CRYPT_PREFIX "keymd5" #define RGW_ATTR_CRYPT_KEYID RGW_ATTR_CRYPT_PREFIX "keyid" #define RGW_ATTR_CRYPT_KEYSEL RGW_ATTR_CRYPT_PREFIX "keysel" #define RGW_ATTR_CRYPT_CONTEXT RGW_ATTR_CRYPT_PREFIX "context" #define RGW_ATTR_CRYPT_DATAKEY RGW_ATTR_CRYPT_PREFIX "datakey" /* SSE-S3 Encryption Attributes */ #define RGW_ATTR_BUCKET_ENCRYPTION_PREFIX RGW_ATTR_PREFIX "sse-s3." #define RGW_ATTR_BUCKET_ENCRYPTION_POLICY RGW_ATTR_BUCKET_ENCRYPTION_PREFIX "policy" #define RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID RGW_ATTR_BUCKET_ENCRYPTION_PREFIX "key-id" #define RGW_ATTR_TRACE RGW_ATTR_PREFIX "trace" enum class RGWFormat : int8_t { BAD_FORMAT = -1, PLAIN = 0, XML, JSON, HTML, }; static inline const char* to_mime_type(const RGWFormat f) { switch (f) { case RGWFormat::XML: return "application/xml"; break; case RGWFormat::JSON: return "application/json"; break; case RGWFormat::HTML: return "text/html"; break; case RGWFormat::PLAIN: return "text/plain"; break; default: return "invalid format"; } } #define RGW_CAP_READ 0x1 #define RGW_CAP_WRITE 0x2 #define RGW_CAP_ALL (RGW_CAP_READ | RGW_CAP_WRITE) #define RGW_REST_SWIFT 0x1 #define RGW_REST_SWIFT_AUTH 0x2 #define RGW_REST_S3 0x4 #define RGW_REST_WEBSITE 0x8 #define RGW_REST_STS 0x10 #define RGW_REST_IAM 0x20 #define RGW_REST_SNS 0x30 #define RGW_SUSPENDED_USER_AUID (uint64_t)-2 #define RGW_OP_TYPE_READ 0x01 #define RGW_OP_TYPE_WRITE 0x02 #define RGW_OP_TYPE_DELETE 0x04 #define RGW_OP_TYPE_MODIFY (RGW_OP_TYPE_WRITE | RGW_OP_TYPE_DELETE) #define RGW_OP_TYPE_ALL (RGW_OP_TYPE_READ | RGW_OP_TYPE_WRITE | RGW_OP_TYPE_DELETE) #define RGW_DEFAULT_MAX_BUCKETS 1000 #define RGW_DEFER_TO_BUCKET_ACLS_RECURSE 1 #define RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL 2 #define STATUS_CREATED 1900 #define STATUS_ACCEPTED 1901 #define STATUS_NO_CONTENT 1902 #define STATUS_PARTIAL_CONTENT 1903 #define STATUS_REDIRECT 1904 #define STATUS_NO_APPLY 1905 #define STATUS_APPLIED 1906 #define ERR_INVALID_BUCKET_NAME 2000 #define ERR_INVALID_OBJECT_NAME 2001 #define ERR_NO_SUCH_BUCKET 2002 #define ERR_METHOD_NOT_ALLOWED 2003 #define ERR_INVALID_DIGEST 2004 #define ERR_BAD_DIGEST 2005 #define ERR_UNRESOLVABLE_EMAIL 2006 #define ERR_INVALID_PART 2007 #define ERR_INVALID_PART_ORDER 2008 #define ERR_NO_SUCH_UPLOAD 2009 #define ERR_REQUEST_TIMEOUT 2010 #define ERR_LENGTH_REQUIRED 2011 #define ERR_REQUEST_TIME_SKEWED 2012 #define ERR_BUCKET_EXISTS 2013 #define ERR_BAD_URL 2014 #define ERR_PRECONDITION_FAILED 2015 #define ERR_NOT_MODIFIED 2016 #define ERR_INVALID_UTF8 2017 #define ERR_UNPROCESSABLE_ENTITY 2018 #define ERR_TOO_LARGE 2019 #define ERR_TOO_MANY_BUCKETS 2020 #define ERR_INVALID_REQUEST 2021 #define ERR_TOO_SMALL 2022 #define ERR_NOT_FOUND 2023 #define ERR_PERMANENT_REDIRECT 2024 #define ERR_LOCKED 2025 #define ERR_QUOTA_EXCEEDED 2026 #define ERR_SIGNATURE_NO_MATCH 2027 #define ERR_INVALID_ACCESS_KEY 2028 #define ERR_MALFORMED_XML 2029 #define ERR_USER_EXIST 2030 #define ERR_NOT_SLO_MANIFEST 2031 #define ERR_EMAIL_EXIST 2032 #define ERR_KEY_EXIST 2033 #define ERR_INVALID_SECRET_KEY 2034 #define ERR_INVALID_KEY_TYPE 2035 #define ERR_INVALID_CAP 2036 #define ERR_INVALID_TENANT_NAME 2037 #define ERR_WEBSITE_REDIRECT 2038 #define ERR_NO_SUCH_WEBSITE_CONFIGURATION 2039 #define ERR_AMZ_CONTENT_SHA256_MISMATCH 2040 #define ERR_NO_SUCH_LC 2041 #define ERR_NO_SUCH_USER 2042 #define ERR_NO_SUCH_SUBUSER 2043 #define ERR_MFA_REQUIRED 2044 #define ERR_NO_SUCH_CORS_CONFIGURATION 2045 #define ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION 2046 #define ERR_INVALID_RETENTION_PERIOD 2047 #define ERR_NO_SUCH_BUCKET_ENCRYPTION_CONFIGURATION 2048 #define ERR_USER_SUSPENDED 2100 #define ERR_INTERNAL_ERROR 2200 #define ERR_NOT_IMPLEMENTED 2201 #define ERR_SERVICE_UNAVAILABLE 2202 #define ERR_ROLE_EXISTS 2203 #define ERR_MALFORMED_DOC 2204 #define ERR_NO_ROLE_FOUND 2205 #define ERR_DELETE_CONFLICT 2206 #define ERR_NO_SUCH_BUCKET_POLICY 2207 #define ERR_INVALID_LOCATION_CONSTRAINT 2208 #define ERR_TAG_CONFLICT 2209 #define ERR_INVALID_TAG 2210 #define ERR_ZERO_IN_URL 2211 #define ERR_MALFORMED_ACL_ERROR 2212 #define ERR_ZONEGROUP_DEFAULT_PLACEMENT_MISCONFIGURATION 2213 #define ERR_INVALID_ENCRYPTION_ALGORITHM 2214 #define ERR_INVALID_CORS_RULES_ERROR 2215 #define ERR_NO_CORS_FOUND 2216 #define ERR_INVALID_WEBSITE_ROUTING_RULES_ERROR 2217 #define ERR_RATE_LIMITED 2218 #define ERR_POSITION_NOT_EQUAL_TO_LENGTH 2219 #define ERR_OBJECT_NOT_APPENDABLE 2220 #define ERR_INVALID_BUCKET_STATE 2221 #define ERR_INVALID_OBJECT_STATE 2222 #define ERR_BUSY_RESHARDING 2300 #define ERR_NO_SUCH_ENTITY 2301 #define ERR_LIMIT_EXCEEDED 2302 // STS Errors #define ERR_PACKED_POLICY_TOO_LARGE 2400 #define ERR_INVALID_IDENTITY_TOKEN 2401 #define ERR_NO_SUCH_TAG_SET 2402 #ifndef UINT32_MAX #define UINT32_MAX (0xffffffffu) #endif typedef void *RGWAccessHandle; /* Helper class used for RGWHTTPArgs parsing */ class NameVal { const std::string str; std::string name; std::string val; public: explicit NameVal(const std::string& nv) : str(nv) {} int parse(); std::string& get_name() { return name; } std::string& get_val() { return val; } }; /** Stores the XML arguments associated with the HTTP request in req_state*/ class RGWHTTPArgs { std::string str, empty_str; std::map<std::string, std::string> val_map; std::map<std::string, std::string> sys_val_map; std::map<std::string, std::string> sub_resources; bool has_resp_modifier = false; bool admin_subresource_added = false; public: RGWHTTPArgs() = default; explicit RGWHTTPArgs(const std::string& s, const DoutPrefixProvider *dpp) { set(s); parse(dpp); } /** Set the arguments; as received */ void set(const std::string& s) { has_resp_modifier = false; val_map.clear(); sub_resources.clear(); str = s; } /** parse the received arguments */ int parse(const DoutPrefixProvider *dpp); void append(const std::string& name, const std::string& val); void remove(const std::string& name); /** Get the value for a specific argument parameter */ const std::string& get(const std::string& name, bool *exists = NULL) const; boost::optional<const std::string&> get_optional(const std::string& name) const; int get_bool(const std::string& name, bool *val, bool *exists) const; int get_bool(const char *name, bool *val, bool *exists) const; void get_bool(const char *name, bool *val, bool def_val) const; int get_int(const char *name, int *val, int def_val) const; /** Get the value for specific system argument parameter */ std::string sys_get(const std::string& name, bool *exists = nullptr) const; /** see if a parameter is contained in this RGWHTTPArgs */ bool exists(const char *name) const { return (val_map.find(name) != std::end(val_map)); } bool sub_resource_exists(const char *name) const { return (sub_resources.find(name) != std::end(sub_resources)); } bool exist_obj_excl_sub_resource() const { const char* const obj_sub_resource[] = {"append", "torrent", "uploadId", "partNumber", "versionId"}; for (unsigned i = 0; i != std::size(obj_sub_resource); i++) { if (sub_resource_exists(obj_sub_resource[i])) return true; } return false; } std::map<std::string, std::string>& get_params() { return val_map; } const std::map<std::string, std::string>& get_params() const { return val_map; } std::map<std::string, std::string>& get_sys_params() { return sys_val_map; } const std::map<std::string, std::string>& get_sys_params() const { return sys_val_map; } const std::map<std::string, std::string>& get_sub_resources() const { return sub_resources; } unsigned get_num_params() const { return val_map.size(); } bool has_response_modifier() const { return has_resp_modifier; } void set_system() { /* make all system params visible */ std::map<std::string, std::string>::iterator iter; for (iter = sys_val_map.begin(); iter != sys_val_map.end(); ++iter) { val_map[iter->first] = iter->second; } } const std::string& get_str() { return str; } }; // RGWHTTPArgs const char *rgw_conf_get(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const char *name, const char *def_val); boost::optional<const std::string&> rgw_conf_get_optional(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const std::string& name); int rgw_conf_get_int(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const char *name, int def_val); bool rgw_conf_get_bool(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const char *name, bool def_val); class RGWEnv; class RGWConf { friend class RGWEnv; int enable_ops_log; int enable_usage_log; uint8_t defer_to_bucket_acls; void init(CephContext *cct); public: RGWConf() : enable_ops_log(1), enable_usage_log(1), defer_to_bucket_acls(0) { } }; class RGWEnv { std::map<std::string, std::string, ltstr_nocase> env_map; RGWConf conf; public: void init(CephContext *cct); void init(CephContext *cct, char **envp); void set(std::string name, std::string val); const char *get(const char *name, const char *def_val = nullptr) const; boost::optional<const std::string&> get_optional(const std::string& name) const; int get_int(const char *name, int def_val = 0) const; bool get_bool(const char *name, bool def_val = 0); size_t get_size(const char *name, size_t def_val = 0) const; bool exists(const char *name) const; bool exists_prefix(const char *prefix) const; void remove(const char *name); const std::map<std::string, std::string, ltstr_nocase>& get_map() const { return env_map; } int get_enable_ops_log() const { return conf.enable_ops_log; } int get_enable_usage_log() const { return conf.enable_usage_log; } int get_defer_to_bucket_acls() const { return conf.defer_to_bucket_acls; } }; // return true if the connection is secure. this either means that the // connection arrived via ssl, or was forwarded as https by a trusted proxy bool rgw_transport_is_secure(CephContext *cct, const RGWEnv& env); enum http_op { OP_GET, OP_PUT, OP_DELETE, OP_HEAD, OP_POST, OP_COPY, OP_OPTIONS, OP_UNKNOWN, }; class RGWAccessControlPolicy; class JSONObj; void encode_json(const char *name, const obj_version& v, Formatter *f); void encode_json(const char *name, const RGWUserCaps& val, Formatter *f); void decode_json_obj(obj_version& v, JSONObj *obj); enum RGWIdentityType { TYPE_NONE=0, TYPE_RGW=1, TYPE_KEYSTONE=2, TYPE_LDAP=3, TYPE_ROLE=4, TYPE_WEB=5, }; void encode_json(const char *name, const rgw_placement_rule& val, ceph::Formatter *f); void decode_json_obj(rgw_placement_rule& v, JSONObj *obj); inline std::ostream& operator<<(std::ostream& out, const rgw_placement_rule& rule) { return out << rule.to_str(); } class RateLimiter; struct RGWRateLimitInfo { int64_t max_write_ops; int64_t max_read_ops; int64_t max_write_bytes; int64_t max_read_bytes; bool enabled = false; RGWRateLimitInfo() : max_write_ops(0), max_read_ops(0), max_write_bytes(0), max_read_bytes(0) {} void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(max_write_ops, bl); encode(max_read_ops, bl); encode(max_write_bytes, bl); encode(max_read_bytes, bl); encode(enabled, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(max_write_ops,bl); decode(max_read_ops, bl); decode(max_write_bytes,bl); decode(max_read_bytes, bl); decode(enabled, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWRateLimitInfo) struct RGWUserInfo { rgw_user user_id; std::string display_name; std::string user_email; std::map<std::string, RGWAccessKey> access_keys; std::map<std::string, RGWAccessKey> swift_keys; std::map<std::string, RGWSubUser> subusers; __u8 suspended; int32_t max_buckets; uint32_t op_mask; RGWUserCaps caps; __u8 admin; __u8 system; rgw_placement_rule default_placement; std::list<std::string> placement_tags; std::map<int, std::string> temp_url_keys; RGWQuota quota; uint32_t type; std::set<std::string> mfa_ids; RGWUserInfo() : suspended(0), max_buckets(RGW_DEFAULT_MAX_BUCKETS), op_mask(RGW_OP_TYPE_ALL), admin(0), system(0), type(TYPE_NONE) { } RGWAccessKey* get_key(const std::string& access_key) { if (access_keys.empty()) return nullptr; auto k = access_keys.find(access_key); if (k == access_keys.end()) return nullptr; else return &(k->second); } void encode(bufferlist& bl) const { ENCODE_START(22, 9, bl); encode((uint64_t)0, bl); // old auid std::string access_key; std::string secret_key; if (!access_keys.empty()) { std::map<std::string, RGWAccessKey>::const_iterator iter = access_keys.begin(); const RGWAccessKey& k = iter->second; access_key = k.id; secret_key = k.key; } encode(access_key, bl); encode(secret_key, bl); encode(display_name, bl); encode(user_email, bl); std::string swift_name; std::string swift_key; if (!swift_keys.empty()) { std::map<std::string, RGWAccessKey>::const_iterator iter = swift_keys.begin(); const RGWAccessKey& k = iter->second; swift_name = k.id; swift_key = k.key; } encode(swift_name, bl); encode(swift_key, bl); encode(user_id.id, bl); encode(access_keys, bl); encode(subusers, bl); encode(suspended, bl); encode(swift_keys, bl); encode(max_buckets, bl); encode(caps, bl); encode(op_mask, bl); encode(system, bl); encode(default_placement, bl); encode(placement_tags, bl); encode(quota.bucket_quota, bl); encode(temp_url_keys, bl); encode(quota.user_quota, bl); encode(user_id.tenant, bl); encode(admin, bl); encode(type, bl); encode(mfa_ids, bl); { std::string assumed_role_arn; // removed encode(assumed_role_arn, bl); } encode(user_id.ns, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN_32(22, 9, 9, bl); if (struct_v >= 2) { uint64_t old_auid; decode(old_auid, bl); } std::string access_key; std::string secret_key; decode(access_key, bl); decode(secret_key, bl); if (struct_v < 6) { RGWAccessKey k; k.id = access_key; k.key = secret_key; access_keys[access_key] = k; } decode(display_name, bl); decode(user_email, bl); /* We populate swift_keys map later nowadays, but we have to decode. */ std::string swift_name; std::string swift_key; if (struct_v >= 3) decode(swift_name, bl); if (struct_v >= 4) decode(swift_key, bl); if (struct_v >= 5) decode(user_id.id, bl); else user_id.id = access_key; if (struct_v >= 6) { decode(access_keys, bl); decode(subusers, bl); } suspended = 0; if (struct_v >= 7) { decode(suspended, bl); } if (struct_v >= 8) { decode(swift_keys, bl); } if (struct_v >= 10) { decode(max_buckets, bl); } else { max_buckets = RGW_DEFAULT_MAX_BUCKETS; } if (struct_v >= 11) { decode(caps, bl); } if (struct_v >= 12) { decode(op_mask, bl); } else { op_mask = RGW_OP_TYPE_ALL; } if (struct_v >= 13) { decode(system, bl); decode(default_placement, bl); decode(placement_tags, bl); /* tags of allowed placement rules */ } if (struct_v >= 14) { decode(quota.bucket_quota, bl); } if (struct_v >= 15) { decode(temp_url_keys, bl); } if (struct_v >= 16) { decode(quota.user_quota, bl); } if (struct_v >= 17) { decode(user_id.tenant, bl); } else { user_id.tenant.clear(); } if (struct_v >= 18) { decode(admin, bl); } if (struct_v >= 19) { decode(type, bl); } if (struct_v >= 20) { decode(mfa_ids, bl); } if (struct_v >= 21) { std::string assumed_role_arn; // removed decode(assumed_role_arn, bl); } if (struct_v >= 22) { decode(user_id.ns, bl); } else { user_id.ns.clear(); } DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWUserInfo*>& o); void decode_json(JSONObj *obj); }; WRITE_CLASS_ENCODER(RGWUserInfo) /// `RGWObjVersionTracker` /// ====================== /// /// What and why is this? /// --------------------- /// /// This is a wrapper around `cls_version` functionality. If two RGWs /// (or two non-synchronized threads in the same RGW) are accessing /// the same object, they may race and overwrite each other's work. /// /// This class solves this issue by tracking and recording an object's /// version in the extended attributes. Operations are failed with /// ECANCELED if the version is not what we expect. /// /// How to Use It /// ------------- /// /// When preparing a read operation, call `prepare_op_for_read`. /// For a write, call `prepare_op_for_write` when preparing the /// operation, and `apply_write` after it succeeds. /// /// Adhere to the following guidelines: /// /// - Each RGWObjVersionTracker should be used with only one object. /// /// - If you receive `ECANCELED`, throw away whatever you were doing /// based on the content of the versioned object, re-read, and /// restart as appropriate. /// /// - If one code path uses RGWObjVersionTracker, then they all /// should. In a situation where a writer should unconditionally /// overwrite an object, call `generate_new_write_ver` on a default /// constructed `RGWObjVersionTracker`. /// /// - If we have a version from a previous read, we will check against /// it and fail the read if it doesn't match. Thus, if we want to /// re-read a new version of the object, call `clear()` on the /// `RGWObjVersionTracker`. /// /// - This type is not thread-safe. Every thread must have its own /// instance. /// struct RGWObjVersionTracker { obj_version read_version; //< The version read from an object. If // set, this value is used to check the // stored version. obj_version write_version; //< Set the object to this version on // write, if set. /// Pointer to the read version. obj_version* version_for_read() { return &read_version; } /// If we have a write version, return a pointer to it. Otherwise /// return null. This is used in `prepare_op_for_write` to treat the /// `write_version` as effectively an `option` type. obj_version* version_for_write() { if (write_version.ver == 0) return nullptr; return &write_version; } /// If read_version is non-empty, return a pointer to it, otherwise /// null. This is used internally by `prepare_op_for_read` and /// `prepare_op_for_write` to treat the `read_version` as /// effectively an `option` type. obj_version* version_for_check() { if (read_version.ver == 0) return nullptr; return &read_version; } /// This function is to be called on any read operation. If we have /// a non-empty `read_version`, assert on the OSD that the object /// has the same version. Also reads the version into `read_version`. /// /// This function is defined in `rgw_rados.cc` rather than `rgw_common.cc`. void prepare_op_for_read(librados::ObjectReadOperation* op); /// This function is to be called on any write operation. If we have /// a non-empty read operation, assert on the OSD that the object /// has the same version. If we have a non-empty `write_version`, /// set the object to it. Otherwise increment the version on the OSD. /// /// This function is defined in `rgw_rados.cc` rather than /// `rgw_common.cc`. void prepare_op_for_write(librados::ObjectWriteOperation* op); /// This function is to be called after the completion of any write /// operation on which `prepare_op_for_write` was called. If we did /// not set the write version explicitly, it increments /// `read_version`. If we did, it sets `read_version` to /// `write_version`. In either case, it clears `write_version`. /// /// RADOS write operations, at least those not using the relatively /// new RETURNVEC flag, cannot return more information than an error /// code. Thus, write operations can't simply fill in the read /// version the way read operations can, so prepare_op_for_write` /// instructs the OSD to increment the object as stored in RADOS and /// `apply_write` increments our `read_version` in RAM. /// /// This function is defined in `rgw_rados.cc` rather than /// `rgw_common.cc`. void apply_write(); /// Clear `read_version` and `write_version`, making the instance /// identical to a default-constructed instance. void clear() { read_version = obj_version(); write_version = obj_version(); } /// Set `write_version` to a new, unique version. /// /// An `obj_version` contains an opaque, random tag and a /// sequence. If the tags of two `obj_version`s don't match, the /// versions are unordered and unequal. This function creates a /// version with a new tag, ensuring that any other process /// operating on the object will receive `ECANCELED` and will know /// to re-read the object and restart whatever it was doing. void generate_new_write_ver(CephContext* cct); }; inline std::ostream& operator<<(std::ostream& out, const obj_version &v) { out << v.tag << ":" << v.ver; return out; } inline std::ostream& operator<<(std::ostream& out, const RGWObjVersionTracker &ot) { out << "{r=" << ot.read_version << ",w=" << ot.write_version << "}"; return out; } enum RGWBucketFlags { BUCKET_SUSPENDED = 0x1, BUCKET_VERSIONED = 0x2, BUCKET_VERSIONS_SUSPENDED = 0x4, BUCKET_DATASYNC_DISABLED = 0X8, BUCKET_MFA_ENABLED = 0X10, BUCKET_OBJ_LOCK_ENABLED = 0X20, }; class RGWSI_Zone; struct RGWBucketInfo { rgw_bucket bucket; rgw_user owner; uint32_t flags{0}; std::string zonegroup; ceph::real_time creation_time; rgw_placement_rule placement_rule; bool has_instance_obj{false}; RGWObjVersionTracker objv_tracker; /* we don't need to serialize this, for runtime tracking */ RGWQuotaInfo quota; // layout of bucket index objects rgw::BucketLayout layout; // Represents the shard number for blind bucket. const static uint32_t NUM_SHARDS_BLIND_BUCKET; bool requester_pays{false}; bool has_website{false}; RGWBucketWebsiteConf website_conf; bool swift_versioning{false}; std::string swift_ver_location; std::map<std::string, uint32_t> mdsearch_config; // resharding cls_rgw_reshard_status reshard_status{cls_rgw_reshard_status::NOT_RESHARDING}; std::string new_bucket_instance_id; RGWObjectLock obj_lock; std::optional<rgw_sync_policy_info> sync_policy; void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& bl); void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWBucketInfo*>& o); void decode_json(JSONObj *obj); bool versioned() const { return (flags & BUCKET_VERSIONED) != 0; } int versioning_status() const { return flags & (BUCKET_VERSIONED | BUCKET_VERSIONS_SUSPENDED | BUCKET_MFA_ENABLED); } bool versioning_enabled() const { return (versioning_status() & (BUCKET_VERSIONED | BUCKET_VERSIONS_SUSPENDED)) == BUCKET_VERSIONED; } bool mfa_enabled() const { return (versioning_status() & BUCKET_MFA_ENABLED) != 0; } bool datasync_flag_enabled() const { return (flags & BUCKET_DATASYNC_DISABLED) == 0; } bool obj_lock_enabled() const { return (flags & BUCKET_OBJ_LOCK_ENABLED) != 0; } bool has_swift_versioning() const { /* A bucket may be versioned through one mechanism only. */ return swift_versioning && !versioned(); } void set_sync_policy(rgw_sync_policy_info&& policy); bool empty_sync_policy() const; bool is_indexless() const { return rgw::is_layout_indexless(layout.current_index); } const rgw::bucket_index_layout_generation& get_current_index() const { return layout.current_index; } rgw::bucket_index_layout_generation& get_current_index() { return layout.current_index; } RGWBucketInfo(); ~RGWBucketInfo(); }; WRITE_CLASS_ENCODER(RGWBucketInfo) struct RGWBucketEntryPoint { rgw_bucket bucket; rgw_user owner; ceph::real_time creation_time; bool linked; bool has_bucket_info; RGWBucketInfo old_bucket_info; RGWBucketEntryPoint() : linked(false), has_bucket_info(false) {} void encode(bufferlist& bl) const { ENCODE_START(10, 8, bl); encode(bucket, bl); encode(owner.id, bl); encode(linked, bl); uint64_t ctime = (uint64_t)real_clock::to_time_t(creation_time); encode(ctime, bl); encode(owner, bl); encode(creation_time, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { auto orig_iter = bl; DECODE_START_LEGACY_COMPAT_LEN_32(10, 4, 4, bl); if (struct_v < 8) { /* ouch, old entry, contains the bucket info itself */ old_bucket_info.decode(orig_iter); has_bucket_info = true; return; } has_bucket_info = false; decode(bucket, bl); decode(owner.id, bl); decode(linked, bl); uint64_t ctime; decode(ctime, bl); if (struct_v < 10) { creation_time = real_clock::from_time_t((time_t)ctime); } if (struct_v >= 9) { decode(owner, bl); } if (struct_v >= 10) { decode(creation_time, bl); } DECODE_FINISH(bl); } void dump(Formatter *f) const; void decode_json(JSONObj *obj); static void generate_test_instances(std::list<RGWBucketEntryPoint*>& o); }; WRITE_CLASS_ENCODER(RGWBucketEntryPoint) struct RGWStorageStats { RGWObjCategory category; uint64_t size; uint64_t size_rounded; uint64_t num_objects; uint64_t size_utilized{0}; //< size after compression, encryption bool dump_utilized; // whether dump should include utilized values RGWStorageStats(bool _dump_utilized=true) : category(RGWObjCategory::None), size(0), size_rounded(0), num_objects(0), dump_utilized(_dump_utilized) {} void dump(Formatter *f) const; }; // RGWStorageStats class RGWEnv; /* Namespaced forward declarations. */ namespace rgw { namespace auth { namespace s3 { class AWSBrowserUploadAbstractor; class STSEngine; } class Completer; } namespace io { class BasicClient; } } using meta_map_t = boost::container::flat_map <std::string, std::string>; struct req_info { const RGWEnv *env; RGWHTTPArgs args; meta_map_t x_meta_map; meta_map_t crypt_attribute_map; std::string host; const char *method; std::string script_uri; std::string request_uri; std::string request_uri_aws4; std::string effective_uri; std::string request_params; std::string domain; std::string storage_class; req_info(CephContext *cct, const RGWEnv *env); void rebuild_from(req_info& src); void init_meta_info(const DoutPrefixProvider *dpp, bool *found_bad_meta); }; struct req_init_state { /* Keeps [[tenant]:]bucket until we parse the token. */ std::string url_bucket; std::string src_bucket; }; #include "rgw_auth.h" class RGWObjectCtx; /** Store all the state necessary to complete and respond to an HTTP request*/ struct req_state : DoutPrefixProvider { CephContext *cct; const RGWProcessEnv& penv; rgw::io::BasicClient *cio{nullptr}; http_op op{OP_UNKNOWN}; RGWOpType op_type{}; std::shared_ptr<RateLimiter> ratelimit_data; RGWRateLimitInfo user_ratelimit; RGWRateLimitInfo bucket_ratelimit; std::string ratelimit_bucket_marker; std::string ratelimit_user_name; bool content_started{false}; RGWFormat format{RGWFormat::PLAIN}; ceph::Formatter *formatter{nullptr}; std::string decoded_uri; std::string relative_uri; const char *length{nullptr}; int64_t content_length{0}; std::map<std::string, std::string> generic_attrs; rgw_err err; bool expect_cont{false}; uint64_t obj_size{0}; bool enable_ops_log; bool enable_usage_log; uint8_t defer_to_bucket_acls; uint32_t perm_mask{0}; /* Set once when url_bucket is parsed and not violated thereafter. */ std::string account_name; std::string bucket_tenant; std::string bucket_name; /* bucket is only created in rgw_build_bucket_policies() and should never be * overwritten */ std::unique_ptr<rgw::sal::Bucket> bucket; std::unique_ptr<rgw::sal::Object> object; std::string src_tenant_name; std::string src_bucket_name; std::unique_ptr<rgw::sal::Object> src_object; ACLOwner bucket_owner; ACLOwner owner; std::string zonegroup_name; std::string zonegroup_endpoint; std::string bucket_instance_id; int bucket_instance_shard_id{-1}; std::string redirect_zone_endpoint; std::string redirect; real_time bucket_mtime; std::map<std::string, ceph::bufferlist> bucket_attrs; bool bucket_exists{false}; rgw_placement_rule dest_placement; bool has_bad_meta{false}; std::unique_ptr<rgw::sal::User> user; struct { /* TODO(rzarzynski): switch out to the static_ptr for both members. */ /* Object having the knowledge about an authenticated identity and allowing * to apply it during the authorization phase (verify_permission() methods * of a given RGWOp). Thus, it bounds authentication and authorization steps * through a well-defined interface. For more details, see rgw_auth.h. */ std::unique_ptr<rgw::auth::Identity> identity; std::shared_ptr<rgw::auth::Completer> completer; /* A container for credentials of the S3's browser upload. It's necessary * because: 1) the ::authenticate() method of auth engines and strategies * take req_state only; 2) auth strategies live much longer than RGWOps - * there is no way to pass additional data dependencies through ctors. */ class { /* Writer. */ friend class RGWPostObj_ObjStore_S3; /* Reader. */ friend class rgw::auth::s3::AWSBrowserUploadAbstractor; friend class rgw::auth::s3::STSEngine; std::string access_key; std::string signature; std::string x_amz_algorithm; std::string x_amz_credential; std::string x_amz_date; std::string x_amz_security_token; ceph::bufferlist encoded_policy; } s3_postobj_creds; } auth; std::unique_ptr<RGWAccessControlPolicy> user_acl; std::unique_ptr<RGWAccessControlPolicy> bucket_acl; std::unique_ptr<RGWAccessControlPolicy> object_acl; rgw::IAM::Environment env; boost::optional<rgw::IAM::Policy> iam_policy; boost::optional<PublicAccessBlockConfiguration> bucket_access_conf; std::vector<rgw::IAM::Policy> iam_user_policies; /* Is the request made by an user marked as a system one? * Being system user means we also have the admin status. */ bool system_request{false}; std::string canned_acl; bool has_acl_header{false}; bool local_source{false}; /* source is local */ int prot_flags{0}; /* Content-Disposition override for TempURL of Swift API. */ struct { std::string override; std::string fallback; } content_disp; std::string host_id; req_info info; req_init_state init_state; using Clock = ceph::coarse_real_clock; Clock::time_point time; Clock::duration time_elapsed() const { return Clock::now() - time; } std::string dialect; std::string req_id; std::string trans_id; uint64_t id; RGWObjTags tagset; bool mfa_verified{false}; /// optional coroutine context optional_yield yield{null_yield}; //token claims from STS token for ops log (can be used for Keystone token also) std::vector<std::string> token_claims; std::vector<rgw::IAM::Policy> session_policies; jspan trace; bool trace_enabled = false; //Principal tags that come in as part of AssumeRoleWithWebIdentity std::vector<std::pair<std::string, std::string>> principal_tags; req_state(CephContext* _cct, const RGWProcessEnv& penv, RGWEnv* e, uint64_t id); ~req_state(); void set_user(std::unique_ptr<rgw::sal::User>& u) { user.swap(u); } bool is_err() const { return err.is_err(); } // implements DoutPrefixProvider std::ostream& gen_prefix(std::ostream& out) const override; CephContext* get_cct() const override { return cct; } unsigned get_subsys() const override { return ceph_subsys_rgw; } }; void set_req_state_err(req_state*, int); void set_req_state_err(req_state*, int, const std::string&); void set_req_state_err(struct rgw_err&, int, const int); void dump(req_state*); /** Store basic data on bucket */ struct RGWBucketEnt { rgw_bucket bucket; size_t size; size_t size_rounded; ceph::real_time creation_time; uint64_t count; /* The placement_rule is necessary to calculate per-storage-policy statics * of the Swift API. Although the info available in RGWBucketInfo, we need * to duplicate it here to not affect the performance of buckets listing. */ rgw_placement_rule placement_rule; RGWBucketEnt() : size(0), size_rounded(0), count(0) { } RGWBucketEnt(const RGWBucketEnt&) = default; RGWBucketEnt(RGWBucketEnt&&) = default; explicit RGWBucketEnt(const rgw_user& u, cls_user_bucket_entry&& e) : bucket(u, std::move(e.bucket)), size(e.size), size_rounded(e.size_rounded), creation_time(e.creation_time), count(e.count) { } RGWBucketEnt& operator=(const RGWBucketEnt&) = default; void convert(cls_user_bucket_entry *b) const { bucket.convert(&b->bucket); b->size = size; b->size_rounded = size_rounded; b->creation_time = creation_time; b->count = count; } void encode(bufferlist& bl) const { ENCODE_START(7, 5, bl); uint64_t s = size; // issue tracked here: https://tracker.ceph.com/issues/61160 // coverity[store_truncates_time_t:SUPPRESS] __u32 mt = ceph::real_clock::to_time_t(creation_time); std::string empty_str; // originally had the bucket name here, but we encode bucket later encode(empty_str, bl); encode(s, bl); encode(mt, bl); encode(count, bl); encode(bucket, bl); s = size_rounded; encode(s, bl); encode(creation_time, bl); encode(placement_rule, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(7, 5, 5, bl); __u32 mt; uint64_t s; std::string empty_str; // backward compatibility decode(empty_str, bl); decode(s, bl); decode(mt, bl); size = s; if (struct_v < 6) { creation_time = ceph::real_clock::from_time_t(mt); } if (struct_v >= 2) decode(count, bl); if (struct_v >= 3) decode(bucket, bl); if (struct_v >= 4) decode(s, bl); size_rounded = s; if (struct_v >= 6) decode(creation_time, bl); if (struct_v >= 7) decode(placement_rule, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; static void generate_test_instances(std::list<RGWBucketEnt*>& o); }; WRITE_CLASS_ENCODER(RGWBucketEnt) struct rgw_cache_entry_info { std::string cache_locator; uint64_t gen; rgw_cache_entry_info() : gen(0) {} }; inline std::ostream& operator<<(std::ostream& out, const rgw_obj &o) { return out << o.bucket.name << ":" << o.get_oid(); } struct multipart_upload_info { rgw_placement_rule dest_placement; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(dest_placement, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(dest_placement, bl); DECODE_FINISH(bl); } }; WRITE_CLASS_ENCODER(multipart_upload_info) static inline void buf_to_hex(const unsigned char* const buf, const size_t len, char* const str) { str[0] = '\0'; for (size_t i = 0; i < len; i++) { ::sprintf(&str[i*2], "%02x", static_cast<int>(buf[i])); } } template<size_t N> static inline std::array<char, N * 2 + 1> buf_to_hex(const std::array<unsigned char, N>& buf) { static_assert(N > 0, "The input array must be at least one element long"); std::array<char, N * 2 + 1> hex_dest; buf_to_hex(buf.data(), N, hex_dest.data()); return hex_dest; } static inline int hexdigit(char c) { if (c >= '0' && c <= '9') return (c - '0'); c = toupper(c); if (c >= 'A' && c <= 'F') return c - 'A' + 0xa; return -EINVAL; } static inline int hex_to_buf(const char *hex, char *buf, int len) { int i = 0; const char *p = hex; while (*p) { if (i >= len) return -EINVAL; buf[i] = 0; int d = hexdigit(*p); if (d < 0) return d; buf[i] = d << 4; p++; if (!*p) return -EINVAL; d = hexdigit(*p); if (d < 0) return d; buf[i] += d; i++; p++; } return i; } static inline int rgw_str_to_bool(const char *s, int def_val) { if (!s) return def_val; return (strcasecmp(s, "true") == 0 || strcasecmp(s, "on") == 0 || strcasecmp(s, "yes") == 0 || strcasecmp(s, "1") == 0); } static inline void append_rand_alpha(CephContext *cct, const std::string& src, std::string& dest, int len) { dest = src; char buf[len + 1]; gen_rand_alphanumeric(cct, buf, len); dest.append("_"); dest.append(buf); } static inline uint64_t rgw_rounded_kb(uint64_t bytes) { return (bytes + 1023) / 1024; } static inline uint64_t rgw_rounded_objsize(uint64_t bytes) { return ((bytes + 4095) & ~4095); } static inline uint64_t rgw_rounded_objsize_kb(uint64_t bytes) { return ((bytes + 4095) & ~4095) / 1024; } /* implement combining step, S3 header canonicalization; k is a * valid header and in lc form */ void rgw_add_amz_meta_header( meta_map_t& x_meta_map, const std::string& k, const std::string& v); enum rgw_set_action_if_set { DISCARD=0, OVERWRITE, APPEND }; bool rgw_set_amz_meta_header( meta_map_t& x_meta_map, const std::string& k, const std::string& v, rgw_set_action_if_set f); extern std::string rgw_string_unquote(const std::string& s); extern void parse_csv_string(const std::string& ival, std::vector<std::string>& ovals); extern int parse_key_value(std::string& in_str, std::string& key, std::string& val); extern int parse_key_value(std::string& in_str, const char *delim, std::string& key, std::string& val); extern boost::optional<std::pair<std::string_view,std::string_view>> parse_key_value(const std::string_view& in_str, const std::string_view& delim); extern boost::optional<std::pair<std::string_view,std::string_view>> parse_key_value(const std::string_view& in_str); struct rgw_name_to_flag { const char *type_name; uint32_t flag; }; /** time parsing */ extern int parse_time(const char *time_str, real_time *time); extern bool parse_rfc2616(const char *s, struct tm *t); extern bool parse_iso8601(const char *s, struct tm *t, uint32_t *pns = NULL, bool extended_format = true); extern std::string rgw_trim_whitespace(const std::string& src); extern std::string_view rgw_trim_whitespace(const std::string_view& src); extern std::string rgw_trim_quotes(const std::string& val); extern void rgw_to_iso8601(const real_time& t, char *dest, int buf_size); extern void rgw_to_iso8601(const real_time& t, std::string *dest); extern std::string rgw_to_asctime(const utime_t& t); struct perm_state_base { CephContext *cct; const rgw::IAM::Environment& env; rgw::auth::Identity *identity; const RGWBucketInfo bucket_info; int perm_mask; bool defer_to_bucket_acls; boost::optional<PublicAccessBlockConfiguration> bucket_access_conf; perm_state_base(CephContext *_cct, const rgw::IAM::Environment& _env, rgw::auth::Identity *_identity, const RGWBucketInfo& _bucket_info, int _perm_mask, bool _defer_to_bucket_acls, boost::optional<PublicAccessBlockConfiguration> _bucket_acess_conf = boost::none) : cct(_cct), env(_env), identity(_identity), bucket_info(_bucket_info), perm_mask(_perm_mask), defer_to_bucket_acls(_defer_to_bucket_acls), bucket_access_conf(_bucket_acess_conf) {} virtual ~perm_state_base() {} virtual const char *get_referer() const = 0; virtual std::optional<bool> get_request_payer() const = 0; /* * empty state means that request_payer param was not passed in */ }; struct perm_state : public perm_state_base { const char *referer; bool request_payer; perm_state(CephContext *_cct, const rgw::IAM::Environment& _env, rgw::auth::Identity *_identity, const RGWBucketInfo& _bucket_info, int _perm_mask, bool _defer_to_bucket_acls, const char *_referer, bool _request_payer) : perm_state_base(_cct, _env, _identity, _bucket_info, _perm_mask, _defer_to_bucket_acls), referer(_referer), request_payer(_request_payer) {} const char *get_referer() const override { return referer; } std::optional<bool> get_request_payer() const override { return request_payer; } }; /** Check if the req_state's user has the necessary permissions * to do the requested action */ bool verify_bucket_permission_no_policy( const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const int perm); bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, const int perm); bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp, struct perm_state_base * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, RGWAccessControlPolicy * const object_acl, const int perm); /** Check if the req_state's user has the necessary permissions * to do the requested action */ rgw::IAM::Effect eval_identity_or_session_policies(const DoutPrefixProvider* dpp, const std::vector<rgw::IAM::Policy>& user_policies, const rgw::IAM::Environment& env, const uint64_t op, const rgw::ARN& arn); bool verify_user_permission(const DoutPrefixProvider* dpp, req_state * const s, RGWAccessControlPolicy * const user_acl, const std::vector<rgw::IAM::Policy>& user_policies, const std::vector<rgw::IAM::Policy>& session_policies, const rgw::ARN& res, const uint64_t op, bool mandatory_policy=true); bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, RGWAccessControlPolicy * const user_acl, const int perm); bool verify_user_permission(const DoutPrefixProvider* dpp, req_state * const s, const rgw::ARN& res, const uint64_t op, bool mandatory_policy=true); bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, int perm); bool verify_bucket_permission( const DoutPrefixProvider* dpp, req_state * const s, const rgw_bucket& bucket, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const boost::optional<rgw::IAM::Policy>& bucket_policy, const std::vector<rgw::IAM::Policy>& identity_policies, const std::vector<rgw::IAM::Policy>& session_policies, const uint64_t op); bool verify_bucket_permission(const DoutPrefixProvider* dpp, req_state * const s, const uint64_t op); bool verify_bucket_permission_no_policy( const DoutPrefixProvider* dpp, req_state * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, const int perm); bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, const int perm); int verify_bucket_owner_or_policy(req_state* const s, const uint64_t op); extern bool verify_object_permission( const DoutPrefixProvider* dpp, req_state * const s, const rgw_obj& obj, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, RGWAccessControlPolicy * const object_acl, const boost::optional<rgw::IAM::Policy>& bucket_policy, const std::vector<rgw::IAM::Policy>& identity_policies, const std::vector<rgw::IAM::Policy>& session_policies, const uint64_t op); extern bool verify_object_permission(const DoutPrefixProvider* dpp, req_state *s, uint64_t op); extern bool verify_object_permission_no_policy( const DoutPrefixProvider* dpp, req_state * const s, RGWAccessControlPolicy * const user_acl, RGWAccessControlPolicy * const bucket_acl, RGWAccessControlPolicy * const object_acl, int perm); extern bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp, req_state *s, int perm); extern int verify_object_lock( const DoutPrefixProvider* dpp, const rgw::sal::Attrs& attrs, const bool bypass_perm, const bool bypass_governance_mode); /** Convert an input URL into a sane object name * by converting %-escaped std::strings into characters, etc*/ extern void rgw_uri_escape_char(char c, std::string& dst); extern std::string url_decode(const std::string_view& src_str, bool in_query = false); extern void url_encode(const std::string& src, std::string& dst, bool encode_slash = true); extern std::string url_encode(const std::string& src, bool encode_slash = true); extern std::string url_remove_prefix(const std::string& url); // Removes hhtp, https and www from url /* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */ extern void calc_hmac_sha1(const char *key, int key_len, const char *msg, int msg_len, char *dest); static inline sha1_digest_t calc_hmac_sha1(const std::string_view& key, const std::string_view& msg) { sha1_digest_t dest; calc_hmac_sha1(key.data(), key.size(), msg.data(), msg.size(), reinterpret_cast<char*>(dest.v)); return dest; } /* destination should be CEPH_CRYPTO_HMACSHA256_DIGESTSIZE bytes long */ extern void calc_hmac_sha256(const char *key, int key_len, const char *msg, int msg_len, char *dest); static inline sha256_digest_t calc_hmac_sha256(const char *key, const int key_len, const char *msg, const int msg_len) { sha256_digest_t dest; calc_hmac_sha256(key, key_len, msg, msg_len, reinterpret_cast<char*>(dest.v)); return dest; } static inline sha256_digest_t calc_hmac_sha256(const std::string_view& key, const std::string_view& msg) { sha256_digest_t dest; calc_hmac_sha256(key.data(), key.size(), msg.data(), msg.size(), reinterpret_cast<char*>(dest.v)); return dest; } static inline sha256_digest_t calc_hmac_sha256(const sha256_digest_t &key, const std::string_view& msg) { sha256_digest_t dest; calc_hmac_sha256(reinterpret_cast<const char*>(key.v), sha256_digest_t::SIZE, msg.data(), msg.size(), reinterpret_cast<char*>(dest.v)); return dest; } static inline sha256_digest_t calc_hmac_sha256(const std::vector<unsigned char>& key, const std::string_view& msg) { sha256_digest_t dest; calc_hmac_sha256(reinterpret_cast<const char*>(key.data()), key.size(), msg.data(), msg.size(), reinterpret_cast<char*>(dest.v)); return dest; } template<size_t KeyLenN> static inline sha256_digest_t calc_hmac_sha256(const std::array<unsigned char, KeyLenN>& key, const std::string_view& msg) { sha256_digest_t dest; calc_hmac_sha256(reinterpret_cast<const char*>(key.data()), key.size(), msg.data(), msg.size(), reinterpret_cast<char*>(dest.v)); return dest; } extern sha256_digest_t calc_hash_sha256(const std::string_view& msg); extern ceph::crypto::SHA256* calc_hash_sha256_open_stream(); extern void calc_hash_sha256_update_stream(ceph::crypto::SHA256* hash, const char* msg, int len); extern std::string calc_hash_sha256_close_stream(ceph::crypto::SHA256** phash); extern std::string calc_hash_sha256_restart_stream(ceph::crypto::SHA256** phash); extern int rgw_parse_op_type_list(const std::string& str, uint32_t *perm); static constexpr uint32_t MATCH_POLICY_ACTION = 0x01; static constexpr uint32_t MATCH_POLICY_RESOURCE = 0x02; static constexpr uint32_t MATCH_POLICY_ARN = 0x04; static constexpr uint32_t MATCH_POLICY_STRING = 0x08; extern bool match_policy(std::string_view pattern, std::string_view input, uint32_t flag); extern std::string camelcase_dash_http_attr(const std::string& orig); extern std::string lowercase_dash_http_attr(const std::string& orig); void rgw_setup_saved_curl_handles(); void rgw_release_all_curl_handles(); static inline void rgw_escape_str(const std::string& s, char esc_char, char special_char, std::string *dest) { const char *src = s.c_str(); char dest_buf[s.size() * 2 + 1]; char *destp = dest_buf; for (size_t i = 0; i < s.size(); i++) { char c = src[i]; if (c == esc_char || c == special_char) { *destp++ = esc_char; } *destp++ = c; } *destp++ = '\0'; *dest = dest_buf; } static inline ssize_t rgw_unescape_str(const std::string& s, ssize_t ofs, char esc_char, char special_char, std::string *dest) { const char *src = s.c_str(); char dest_buf[s.size() + 1]; char *destp = dest_buf; bool esc = false; dest_buf[0] = '\0'; for (size_t i = ofs; i < s.size(); i++) { char c = src[i]; if (!esc && c == esc_char) { esc = true; continue; } if (!esc && c == special_char) { *destp = '\0'; *dest = dest_buf; return (ssize_t)i + 1; } *destp++ = c; esc = false; } *destp = '\0'; *dest = dest_buf; return std::string::npos; } static inline std::string rgw_bl_str(ceph::buffer::list& raw) { size_t len = raw.length(); std::string s(raw.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } return s; } template <typename T> int decode_bl(bufferlist& bl, T& t) { auto iter = bl.cbegin(); try { decode(t, iter); } catch (buffer::error& err) { return -EIO; } return 0; } extern int rgw_bucket_parse_bucket_instance(const std::string& bucket_instance, std::string *bucket_name, std::string *bucket_id, int *shard_id); boost::intrusive_ptr<CephContext> rgw_global_init(const std::map<std::string,std::string> *defaults, std::vector < const char* >& args, uint32_t module_type, code_environment_t code_env, int flags);
59,215
31.095393
149
h
null
ceph-main/src/rgw/rgw_compression.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_compression.h" #define dout_subsys ceph_subsys_rgw using namespace std; int rgw_compression_info_from_attr(const bufferlist& attr, bool& need_decompress, RGWCompressionInfo& cs_info) { auto bliter = attr.cbegin(); try { decode(cs_info, bliter); } catch (buffer::error& err) { return -EIO; } if (cs_info.blocks.size() == 0) { return -EIO; } if (cs_info.compression_type != "none") need_decompress = true; else need_decompress = false; return 0; } int rgw_compression_info_from_attrset(const map<string, bufferlist>& attrs, bool& need_decompress, RGWCompressionInfo& cs_info) { auto value = attrs.find(RGW_ATTR_COMPRESSION); if (value == attrs.end()) { need_decompress = false; return 0; } return rgw_compression_info_from_attr(value->second, need_decompress, cs_info); } //------------RGWPutObj_Compress--------------- int RGWPutObj_Compress::process(bufferlist&& in, uint64_t logical_offset) { bufferlist out; compressed_ofs = logical_offset; if (in.length() > 0) { // compression stuff if ((logical_offset > 0 && compressed) || // if previous part was compressed (logical_offset == 0)) { // or it's the first part ldout(cct, 10) << "Compression for rgw is enabled, compress part " << in.length() << dendl; int cr = compressor->compress(in, out, compressor_message); if (cr < 0) { if (logical_offset > 0) { lderr(cct) << "Compression failed with exit code " << cr << " for next part, compression process failed" << dendl; return -EIO; } compressed = false; ldout(cct, 5) << "Compression failed with exit code " << cr << " for first part, storing uncompressed" << dendl; out = std::move(in); } else { compressed = true; compression_block newbl; size_t bs = blocks.size(); newbl.old_ofs = logical_offset; newbl.new_ofs = bs > 0 ? blocks[bs-1].len + blocks[bs-1].new_ofs : 0; newbl.len = out.length(); blocks.push_back(newbl); compressed_ofs = newbl.new_ofs; } } else { compressed = false; out = std::move(in); } // end of compression stuff } else { size_t bs = blocks.size(); compressed_ofs = bs > 0 ? blocks[bs-1].len + blocks[bs-1].new_ofs : logical_offset; } return Pipe::process(std::move(out), compressed_ofs); } //----------------RGWGetObj_Decompress--------------------- RGWGetObj_Decompress::RGWGetObj_Decompress(CephContext* cct_, RGWCompressionInfo* cs_info_, bool partial_content_, RGWGetObj_Filter* next): RGWGetObj_Filter(next), cct(cct_), cs_info(cs_info_), partial_content(partial_content_), q_ofs(0), q_len(0), cur_ofs(0) { compressor = Compressor::create(cct, cs_info->compression_type); if (!compressor.get()) lderr(cct) << "Cannot load compressor of type " << cs_info->compression_type << dendl; } int RGWGetObj_Decompress::handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { ldout(cct, 10) << "Compression for rgw is enabled, decompress part " << "bl_ofs=" << bl_ofs << ", bl_len=" << bl_len << dendl; if (!compressor.get()) { // if compressor isn't available - error, because cannot return decompressed data? lderr(cct) << "Cannot load compressor of type " << cs_info->compression_type << dendl; return -EIO; } bufferlist out_bl, in_bl, temp_in_bl; bl.begin(bl_ofs).copy(bl_len, temp_in_bl); bl_ofs = 0; int r = 0; if (waiting.length() != 0) { in_bl.append(waiting); in_bl.append(temp_in_bl); waiting.clear(); } else { in_bl = std::move(temp_in_bl); } bl_len = in_bl.length(); auto iter_in_bl = in_bl.cbegin(); while (first_block <= last_block) { bufferlist tmp; off_t ofs_in_bl = first_block->new_ofs - cur_ofs; if (ofs_in_bl + (off_t)first_block->len > bl_len) { // not complete block, put it to waiting unsigned tail = bl_len - ofs_in_bl; if (iter_in_bl.get_off() != ofs_in_bl) { iter_in_bl.seek(ofs_in_bl); } iter_in_bl.copy(tail, waiting); cur_ofs -= tail; break; } if (iter_in_bl.get_off() != ofs_in_bl) { iter_in_bl.seek(ofs_in_bl); } iter_in_bl.copy(first_block->len, tmp); int cr = compressor->decompress(tmp, out_bl, cs_info->compressor_message); if (cr < 0) { lderr(cct) << "Decompression failed with exit code " << cr << dendl; return cr; } ++first_block; while (out_bl.length() - q_ofs >= static_cast<off_t>(cct->_conf->rgw_max_chunk_size)) { off_t ch_len = std::min<off_t>(cct->_conf->rgw_max_chunk_size, q_len); q_len -= ch_len; r = next->handle_data(out_bl, q_ofs, ch_len); if (r < 0) { lsubdout(cct, rgw, 0) << "handle_data failed with exit code " << r << dendl; return r; } out_bl.splice(0, q_ofs + ch_len); q_ofs = 0; } } cur_ofs += bl_len; off_t ch_len = std::min<off_t>(out_bl.length() - q_ofs, q_len); if (ch_len > 0) { r = next->handle_data(out_bl, q_ofs, ch_len); if (r < 0) { lsubdout(cct, rgw, 0) << "handle_data failed with exit code " << r << dendl; return r; } out_bl.splice(0, q_ofs + ch_len); q_len -= ch_len; q_ofs = 0; } return r; } int RGWGetObj_Decompress::fixup_range(off_t& ofs, off_t& end) { if (partial_content) { // if user set range, we need to calculate it in decompressed data first_block = cs_info->blocks.begin(); last_block = cs_info->blocks.begin(); if (cs_info->blocks.size() > 1) { vector<compression_block>::iterator fb, lb; // not bad to use auto for lambda, I think auto cmp_u = [] (off_t ofs, const compression_block& e) { return (uint64_t)ofs < e.old_ofs; }; auto cmp_l = [] (const compression_block& e, off_t ofs) { return e.old_ofs <= (uint64_t)ofs; }; fb = upper_bound(cs_info->blocks.begin()+1, cs_info->blocks.end(), ofs, cmp_u); first_block = fb - 1; lb = lower_bound(fb, cs_info->blocks.end(), end, cmp_l); last_block = lb - 1; } } else { first_block = cs_info->blocks.begin(); last_block = cs_info->blocks.end() - 1; } q_ofs = ofs - first_block->old_ofs; q_len = end + 1 - ofs; ofs = first_block->new_ofs; end = last_block->new_ofs + last_block->len - 1; cur_ofs = ofs; waiting.clear(); return next->fixup_range(ofs, end); } void compression_block::dump(Formatter *f) const { f->dump_unsigned("old_ofs", old_ofs); f->dump_unsigned("new_ofs", new_ofs); f->dump_unsigned("len", len); } void RGWCompressionInfo::dump(Formatter *f) const { f->dump_string("compression_type", compression_type); f->dump_unsigned("orig_size", orig_size); if (compressor_message) { f->dump_int("compressor_message", *compressor_message); } ::encode_json("blocks", blocks, f); }
7,803
31.92827
101
cc
null
ceph-main/src/rgw/rgw_compression.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <vector> #include "compressor/Compressor.h" #include "rgw_putobj.h" #include "rgw_op.h" #include "rgw_compression_types.h" int rgw_compression_info_from_attr(const bufferlist& attr, bool& need_decompress, RGWCompressionInfo& cs_info); int rgw_compression_info_from_attrset(const std::map<std::string, bufferlist>& attrs, bool& need_decompress, RGWCompressionInfo& cs_info); class RGWGetObj_Decompress : public RGWGetObj_Filter { CephContext* cct; CompressorRef compressor; RGWCompressionInfo* cs_info; bool partial_content; std::vector<compression_block>::iterator first_block, last_block; off_t q_ofs, q_len; uint64_t cur_ofs; bufferlist waiting; public: RGWGetObj_Decompress(CephContext* cct_, RGWCompressionInfo* cs_info_, bool partial_content_, RGWGetObj_Filter* next); virtual ~RGWGetObj_Decompress() override {} int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override; int fixup_range(off_t& ofs, off_t& end) override; }; class RGWPutObj_Compress : public rgw::putobj::Pipe { CephContext* cct; bool compressed{false}; CompressorRef compressor; std::optional<int32_t> compressor_message; std::vector<compression_block> blocks; uint64_t compressed_ofs{0}; public: RGWPutObj_Compress(CephContext* cct_, CompressorRef compressor, rgw::sal::DataProcessor *next) : Pipe(next), cct(cct_), compressor(compressor) {} virtual ~RGWPutObj_Compress() override {}; int process(bufferlist&& data, uint64_t logical_offset) override; bool is_compressed() { return compressed; } std::vector<compression_block>& get_compression_blocks() { return blocks; } std::optional<int32_t> get_compressor_message() { return compressor_message; } }; /* RGWPutObj_Compress */
2,091
32.206349
85
h
null
ceph-main/src/rgw/rgw_compression_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once struct compression_block { uint64_t old_ofs; uint64_t new_ofs; uint64_t len; void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(old_ofs, bl); encode(new_ofs, bl); encode(len, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(old_ofs, bl); decode(new_ofs, bl); decode(len, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; }; WRITE_CLASS_ENCODER(compression_block) struct RGWCompressionInfo { std::string compression_type; uint64_t orig_size; std::optional<int32_t> compressor_message; std::vector<compression_block> blocks; RGWCompressionInfo() : compression_type("none"), orig_size(0) {} RGWCompressionInfo(const RGWCompressionInfo& cs_info) : compression_type(cs_info.compression_type), orig_size(cs_info.orig_size), compressor_message(cs_info.compressor_message), blocks(cs_info.blocks) {} void encode(bufferlist& bl) const { ENCODE_START(2, 1, bl); encode(compression_type, bl); encode(orig_size, bl); encode(compressor_message, bl); encode(blocks, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(2, bl); decode(compression_type, bl); decode(orig_size, bl); if (struct_v >= 2) { decode(compressor_message, bl); } decode(blocks, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; }; WRITE_CLASS_ENCODER(RGWCompressionInfo)
2,050
25.636364
101
h
null
ceph-main/src/rgw/rgw_coroutine.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "include/Context.h" #include "common/ceph_json.h" #include "rgw_coroutine.h" // re-include our assert to clobber the system one; fix dout: #include "include/ceph_assert.h" #include <boost/asio/yield.hpp> #define dout_subsys ceph_subsys_rgw #define dout_context g_ceph_context using namespace std; class RGWCompletionManager::WaitContext : public Context { RGWCompletionManager *manager; void *opaque; public: WaitContext(RGWCompletionManager *_cm, void *_opaque) : manager(_cm), opaque(_opaque) {} void finish(int r) override { manager->_wakeup(opaque); } }; RGWCompletionManager::RGWCompletionManager(CephContext *_cct) : cct(_cct), timer(cct, lock) { timer.init(); } RGWCompletionManager::~RGWCompletionManager() { std::lock_guard l{lock}; timer.cancel_all_events(); timer.shutdown(); } void RGWCompletionManager::complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info) { std::lock_guard l{lock}; _complete(cn, io_id, user_info); } void RGWCompletionManager::register_completion_notifier(RGWAioCompletionNotifier *cn) { std::lock_guard l{lock}; if (cn) { cns.insert(cn); } } void RGWCompletionManager::unregister_completion_notifier(RGWAioCompletionNotifier *cn) { std::lock_guard l{lock}; if (cn) { cns.erase(cn); } } void RGWCompletionManager::_complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info) { if (cn) { cns.erase(cn); } if (complete_reqs_set.find(io_id) != complete_reqs_set.end()) { /* already have completion for this io_id, don't allow multiple completions for it */ return; } complete_reqs.push_back(io_completion{io_id, user_info}); cond.notify_all(); } int RGWCompletionManager::get_next(io_completion *io) { std::unique_lock l{lock}; while (complete_reqs.empty()) { if (going_down) { return -ECANCELED; } cond.wait(l); } *io = complete_reqs.front(); complete_reqs_set.erase(io->io_id); complete_reqs.pop_front(); return 0; } bool RGWCompletionManager::try_get_next(io_completion *io) { std::lock_guard l{lock}; if (complete_reqs.empty()) { return false; } *io = complete_reqs.front(); complete_reqs_set.erase(io->io_id); complete_reqs.pop_front(); return true; } void RGWCompletionManager::go_down() { std::lock_guard l{lock}; for (auto cn : cns) { cn->unregister(); } going_down = true; cond.notify_all(); } void RGWCompletionManager::wait_interval(void *opaque, const utime_t& interval, void *user_info) { std::lock_guard l{lock}; ceph_assert(waiters.find(opaque) == waiters.end()); waiters[opaque] = user_info; timer.add_event_after(interval, new WaitContext(this, opaque)); } void RGWCompletionManager::wakeup(void *opaque) { std::lock_guard l{lock}; _wakeup(opaque); } void RGWCompletionManager::_wakeup(void *opaque) { map<void *, void *>::iterator iter = waiters.find(opaque); if (iter != waiters.end()) { void *user_id = iter->second; waiters.erase(iter); _complete(NULL, rgw_io_id{0, -1} /* no IO id */, user_id); } } RGWCoroutine::~RGWCoroutine() { for (auto stack : spawned.entries) { stack->put(); } } void RGWCoroutine::init_new_io(RGWIOProvider *io_provider) { ceph_assert(stack); // if there's no stack, io_provider won't be uninitialized stack->init_new_io(io_provider); } void RGWCoroutine::set_io_blocked(bool flag) { if (stack) { stack->set_io_blocked(flag); } } void RGWCoroutine::set_sleeping(bool flag) { if (stack) { stack->set_sleeping(flag); } } int RGWCoroutine::io_block(int ret, int64_t io_id) { return io_block(ret, rgw_io_id{io_id, -1}); } int RGWCoroutine::io_block(int ret, const rgw_io_id& io_id) { if (!stack) { return 0; } if (stack->consume_io_finish(io_id)) { return 0; } set_io_blocked(true); stack->set_io_blocked_id(io_id); return ret; } void RGWCoroutine::io_complete(const rgw_io_id& io_id) { if (stack) { stack->io_complete(io_id); } } void RGWCoroutine::StatusItem::dump(Formatter *f) const { ::encode_json("timestamp", timestamp, f); ::encode_json("status", status, f); } stringstream& RGWCoroutine::Status::set_status() { std::unique_lock l{lock}; string s = status.str(); status.str(string()); if (!timestamp.is_zero()) { history.push_back(StatusItem(timestamp, s)); } if (history.size() > (size_t)max_history) { history.pop_front(); } timestamp = ceph_clock_now(); return status; } RGWCoroutinesManager::~RGWCoroutinesManager() { stop(); completion_mgr->put(); if (cr_registry) { cr_registry->remove(this); } } int64_t RGWCoroutinesManager::get_next_io_id() { return (int64_t)++max_io_id; } uint64_t RGWCoroutinesManager::get_next_stack_id() { return (uint64_t)++max_stack_id; } RGWCoroutinesStack::RGWCoroutinesStack(CephContext *_cct, RGWCoroutinesManager *_ops_mgr, RGWCoroutine *start) : cct(_cct), ops_mgr(_ops_mgr), done_flag(false), error_flag(false), blocked_flag(false), sleep_flag(false), interval_wait_flag(false), is_scheduled(false), is_waiting_for_child(false), retcode(0), run_count(0), env(NULL), parent(NULL) { id = ops_mgr->get_next_stack_id(); if (start) { ops.push_back(start); } pos = ops.begin(); } RGWCoroutinesStack::~RGWCoroutinesStack() { for (auto op : ops) { op->put(); } for (auto stack : spawned.entries) { stack->put(); } } int RGWCoroutinesStack::operate(const DoutPrefixProvider *dpp, RGWCoroutinesEnv *_env) { env = _env; RGWCoroutine *op = *pos; op->stack = this; ldpp_dout(dpp, 20) << *op << ": operate()" << dendl; int r = op->operate_wrapper(dpp); if (r < 0) { ldpp_dout(dpp, 20) << *op << ": operate() returned r=" << r << dendl; } error_flag = op->is_error(); if (op->is_done()) { int op_retcode = r; r = unwind(op_retcode); op->put(); done_flag = (pos == ops.end()); blocked_flag &= !done_flag; if (done_flag) { retcode = op_retcode; } return r; } /* should r ever be negative at this point? */ ceph_assert(r >= 0); return 0; } string RGWCoroutinesStack::error_str() { if (pos != ops.end()) { return (*pos)->error_str(); } return string(); } void RGWCoroutinesStack::call(RGWCoroutine *next_op) { if (!next_op) { return; } ops.push_back(next_op); if (pos != ops.end()) { ++pos; } else { pos = ops.begin(); } } void RGWCoroutinesStack::schedule() { env->manager->schedule(env, this); } void RGWCoroutinesStack::_schedule() { env->manager->_schedule(env, this); } RGWCoroutinesStack *RGWCoroutinesStack::spawn(RGWCoroutine *source_op, RGWCoroutine *op, bool wait) { if (!op) { return NULL; } rgw_spawned_stacks *s = (source_op ? &source_op->spawned : &spawned); RGWCoroutinesStack *stack = env->manager->allocate_stack(); s->add_pending(stack); stack->parent = this; stack->get(); /* we'll need to collect the stack */ stack->call(op); env->manager->schedule(env, stack); if (wait) { set_blocked_by(stack); } return stack; } RGWCoroutinesStack *RGWCoroutinesStack::spawn(RGWCoroutine *op, bool wait) { return spawn(NULL, op, wait); } int RGWCoroutinesStack::wait(const utime_t& interval) { RGWCompletionManager *completion_mgr = env->manager->get_completion_mgr(); completion_mgr->wait_interval((void *)this, interval, (void *)this); set_io_blocked(true); set_interval_wait(true); return 0; } void RGWCoroutinesStack::wakeup() { RGWCompletionManager *completion_mgr = env->manager->get_completion_mgr(); completion_mgr->wakeup((void *)this); } void RGWCoroutinesStack::io_complete(const rgw_io_id& io_id) { RGWCompletionManager *completion_mgr = env->manager->get_completion_mgr(); completion_mgr->complete(nullptr, io_id, (void *)this); } int RGWCoroutinesStack::unwind(int retcode) { rgw_spawned_stacks *src_spawned = &(*pos)->spawned; if (pos == ops.begin()) { ldout(cct, 15) << "stack " << (void *)this << " end" << dendl; spawned.inherit(src_spawned); ops.clear(); pos = ops.end(); return retcode; } --pos; ops.pop_back(); RGWCoroutine *op = *pos; op->set_retcode(retcode); op->spawned.inherit(src_spawned); return 0; } void RGWCoroutinesStack::cancel() { while (!ops.empty()) { RGWCoroutine *op = *pos; unwind(-ECANCELED); op->put(); } put(); } bool RGWCoroutinesStack::collect(RGWCoroutine *op, int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id) /* returns true if needs to be called again */ { bool need_retry = false; rgw_spawned_stacks *s = (op ? &op->spawned : &spawned); *ret = 0; vector<RGWCoroutinesStack *> new_list; for (vector<RGWCoroutinesStack *>::iterator iter = s->entries.begin(); iter != s->entries.end(); ++iter) { RGWCoroutinesStack *stack = *iter; if (stack == skip_stack || !stack->is_done()) { new_list.push_back(stack); if (!stack->is_done()) { ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " is still running" << dendl; } else if (stack == skip_stack) { ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " explicitly skipping stack" << dendl; } continue; } if (stack_id) { *stack_id = stack->get_id(); } int r = stack->get_ret_status(); stack->put(); if (r < 0) { *ret = r; ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " encountered error (r=" << r << "), skipping next stacks" << dendl; new_list.insert(new_list.end(), ++iter, s->entries.end()); need_retry = (iter != s->entries.end()); break; } ldout(cct, 20) << "collect(): s=" << (void *)this << " stack=" << (void *)stack << " is complete" << dendl; } s->entries.swap(new_list); return need_retry; } bool RGWCoroutinesStack::collect_next(RGWCoroutine *op, int *ret, RGWCoroutinesStack **collected_stack) /* returns true if found a stack to collect */ { rgw_spawned_stacks *s = (op ? &op->spawned : &spawned); *ret = 0; if (collected_stack) { *collected_stack = NULL; } for (vector<RGWCoroutinesStack *>::iterator iter = s->entries.begin(); iter != s->entries.end(); ++iter) { RGWCoroutinesStack *stack = *iter; if (!stack->is_done()) { continue; } int r = stack->get_ret_status(); if (r < 0) { *ret = r; } if (collected_stack) { *collected_stack = stack; } stack->put(); s->entries.erase(iter); return true; } return false; } bool RGWCoroutinesStack::collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id) /* returns true if needs to be called again */ { return collect(NULL, ret, skip_stack, stack_id); } static void _aio_completion_notifier_cb(librados::completion_t cb, void *arg) { (static_cast<RGWAioCompletionNotifier *>(arg))->cb(); } RGWAioCompletionNotifier::RGWAioCompletionNotifier(RGWCompletionManager *_mgr, const rgw_io_id& _io_id, void *_user_data) : completion_mgr(_mgr), io_id(_io_id), user_data(_user_data), registered(true) { c = librados::Rados::aio_create_completion(this, _aio_completion_notifier_cb); } RGWAioCompletionNotifier *RGWCoroutinesStack::create_completion_notifier() { return ops_mgr->create_completion_notifier(this); } RGWCompletionManager *RGWCoroutinesStack::get_completion_mgr() { return ops_mgr->get_completion_mgr(); } bool RGWCoroutinesStack::unblock_stack(RGWCoroutinesStack **s) { if (blocking_stacks.empty()) { return false; } set<RGWCoroutinesStack *>::iterator iter = blocking_stacks.begin(); *s = *iter; blocking_stacks.erase(iter); (*s)->blocked_by_stack.erase(this); return true; } void RGWCoroutinesManager::report_error(RGWCoroutinesStack *op) { if (!op) { return; } string err = op->error_str(); if (err.empty()) { return; } lderr(cct) << "ERROR: failed operation: " << op->error_str() << dendl; } void RGWCoroutinesStack::dump(Formatter *f) const { stringstream ss; ss << (void *)this; ::encode_json("stack", ss.str(), f); ::encode_json("run_count", run_count, f); f->open_array_section("ops"); for (auto& i : ops) { encode_json("op", *i, f); } f->close_section(); } void RGWCoroutinesStack::init_new_io(RGWIOProvider *io_provider) { io_provider->set_io_user_info((void *)this); io_provider->assign_io(env->manager->get_io_id_provider()); } bool RGWCoroutinesStack::try_io_unblock(const rgw_io_id& io_id) { if (!can_io_unblock(io_id)) { auto p = io_finish_ids.emplace(io_id.id, io_id); auto& iter = p.first; bool inserted = p.second; if (!inserted) { /* could not insert, entry already existed, add channel to completion mask */ iter->second.channels |= io_id.channels; } return false; } return true; } bool RGWCoroutinesStack::consume_io_finish(const rgw_io_id& io_id) { auto iter = io_finish_ids.find(io_id.id); if (iter == io_finish_ids.end()) { return false; } int finish_mask = iter->second.channels; bool found = (finish_mask & io_id.channels) != 0; finish_mask &= ~(finish_mask & io_id.channels); if (finish_mask == 0) { io_finish_ids.erase(iter); } return found; } void RGWCoroutinesManager::handle_unblocked_stack(set<RGWCoroutinesStack *>& context_stacks, list<RGWCoroutinesStack *>& scheduled_stacks, RGWCompletionManager::io_completion& io, int *blocked_count, int *interval_wait_count) { ceph_assert(ceph_mutex_is_wlocked(lock)); RGWCoroutinesStack *stack = static_cast<RGWCoroutinesStack *>(io.user_info); if (context_stacks.find(stack) == context_stacks.end()) { return; } if (!stack->try_io_unblock(io.io_id)) { return; } if (stack->is_io_blocked()) { --(*blocked_count); stack->set_io_blocked(false); if (stack->is_interval_waiting()) { --(*interval_wait_count); } } stack->set_interval_wait(false); if (!stack->is_done()) { if (!stack->is_scheduled) { scheduled_stacks.push_back(stack); stack->set_is_scheduled(true); } } else { context_stacks.erase(stack); stack->put(); } } void RGWCoroutinesManager::schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack) { std::unique_lock wl{lock}; _schedule(env, stack); } void RGWCoroutinesManager::_schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack) { ceph_assert(ceph_mutex_is_wlocked(lock)); if (!stack->is_scheduled) { env->scheduled_stacks->push_back(stack); stack->set_is_scheduled(true); } set<RGWCoroutinesStack *>& context_stacks = run_contexts[env->run_context]; context_stacks.insert(stack); } void RGWCoroutinesManager::set_sleeping(RGWCoroutine *cr, bool flag) { cr->set_sleeping(flag); } void RGWCoroutinesManager::io_complete(RGWCoroutine *cr, const rgw_io_id& io_id) { cr->io_complete(io_id); } int RGWCoroutinesManager::run(const DoutPrefixProvider *dpp, list<RGWCoroutinesStack *>& stacks) { int ret = 0; int blocked_count = 0; int interval_wait_count = 0; bool canceled = false; // set on going_down RGWCoroutinesEnv env; bool op_not_blocked; uint64_t run_context = ++run_context_count; lock.lock(); set<RGWCoroutinesStack *>& context_stacks = run_contexts[run_context]; list<RGWCoroutinesStack *> scheduled_stacks; for (auto& st : stacks) { context_stacks.insert(st); scheduled_stacks.push_back(st); st->set_is_scheduled(true); } env.run_context = run_context; env.manager = this; env.scheduled_stacks = &scheduled_stacks; for (list<RGWCoroutinesStack *>::iterator iter = scheduled_stacks.begin(); iter != scheduled_stacks.end() && !going_down;) { RGWCompletionManager::io_completion io; RGWCoroutinesStack *stack = *iter; ++iter; scheduled_stacks.pop_front(); if (context_stacks.find(stack) == context_stacks.end()) { /* stack was probably schedule more than once due to IO, but was since complete */ goto next; } env.stack = stack; lock.unlock(); ret = stack->operate(dpp, &env); lock.lock(); stack->set_is_scheduled(false); if (ret < 0) { ldpp_dout(dpp, 20) << "stack->operate() returned ret=" << ret << dendl; } if (stack->is_error()) { report_error(stack); } op_not_blocked = false; if (stack->is_io_blocked()) { ldout(cct, 20) << __func__ << ":" << " stack=" << (void *)stack << " is io blocked" << dendl; if (stack->is_interval_waiting()) { interval_wait_count++; } blocked_count++; } else if (stack->is_blocked()) { /* do nothing, we'll re-add the stack when the blocking stack is done, * or when we're awaken */ ldout(cct, 20) << __func__ << ":" << " stack=" << (void *)stack << " is_blocked_by_stack()=" << stack->is_blocked_by_stack() << " is_sleeping=" << stack->is_sleeping() << " waiting_for_child()=" << stack->waiting_for_child() << dendl; } else if (stack->is_done()) { ldout(cct, 20) << __func__ << ":" << " stack=" << (void *)stack << " is done" << dendl; RGWCoroutinesStack *s; while (stack->unblock_stack(&s)) { if (!s->is_blocked_by_stack() && !s->is_done()) { if (s->is_io_blocked()) { if (stack->is_interval_waiting()) { interval_wait_count++; } blocked_count++; } else { s->_schedule(); } } } if (stack->parent && stack->parent->waiting_for_child()) { stack->parent->set_wait_for_child(false); stack->parent->_schedule(); } context_stacks.erase(stack); stack->put(); stack = NULL; } else { op_not_blocked = true; stack->run_count++; stack->_schedule(); } if (!op_not_blocked && stack) { stack->run_count = 0; } while (completion_mgr->try_get_next(&io)) { handle_unblocked_stack(context_stacks, scheduled_stacks, io, &blocked_count, &interval_wait_count); } /* * only account blocked operations that are not in interval_wait, these are stacks that * were put on a wait without any real IO operations. While we mark these as io_blocked, * these aren't really waiting for IOs */ while (blocked_count - interval_wait_count >= ops_window) { lock.unlock(); ret = completion_mgr->get_next(&io); lock.lock(); if (ret < 0) { ldout(cct, 5) << "completion_mgr.get_next() returned ret=" << ret << dendl; } handle_unblocked_stack(context_stacks, scheduled_stacks, io, &blocked_count, &interval_wait_count); } next: while (scheduled_stacks.empty() && blocked_count > 0) { lock.unlock(); ret = completion_mgr->get_next(&io); lock.lock(); if (ret < 0) { ldout(cct, 5) << "completion_mgr.get_next() returned ret=" << ret << dendl; } if (going_down) { ldout(cct, 5) << __func__ << "(): was stopped, exiting" << dendl; ret = -ECANCELED; canceled = true; break; } handle_unblocked_stack(context_stacks, scheduled_stacks, io, &blocked_count, &interval_wait_count); iter = scheduled_stacks.begin(); } if (canceled) { break; } if (iter == scheduled_stacks.end()) { iter = scheduled_stacks.begin(); } } if (!context_stacks.empty() && !going_down) { JSONFormatter formatter(true); formatter.open_array_section("context_stacks"); for (auto& s : context_stacks) { ::encode_json("entry", *s, &formatter); } formatter.close_section(); lderr(cct) << __func__ << "(): ERROR: deadlock detected, dumping remaining coroutines:\n"; formatter.flush(*_dout); *_dout << dendl; ceph_assert(context_stacks.empty() || going_down); // assert on deadlock } for (auto stack : context_stacks) { ldout(cct, 20) << "clearing stack on run() exit: stack=" << (void *)stack << " nref=" << stack->get_nref() << dendl; stack->cancel(); } run_contexts.erase(run_context); lock.unlock(); return ret; } int RGWCoroutinesManager::run(const DoutPrefixProvider *dpp, RGWCoroutine *op) { if (!op) { return 0; } list<RGWCoroutinesStack *> stacks; RGWCoroutinesStack *stack = allocate_stack(); op->get(); stack->call(op); stacks.push_back(stack); int r = run(dpp, stacks); if (r < 0) { ldpp_dout(dpp, 20) << "run(stacks) returned r=" << r << dendl; } else { r = op->get_ret_status(); } op->put(); return r; } RGWAioCompletionNotifier *RGWCoroutinesManager::create_completion_notifier(RGWCoroutinesStack *stack) { rgw_io_id io_id{get_next_io_id(), -1}; RGWAioCompletionNotifier *cn = new RGWAioCompletionNotifier(completion_mgr, io_id, (void *)stack); completion_mgr->register_completion_notifier(cn); return cn; } void RGWCoroutinesManager::dump(Formatter *f) const { std::shared_lock rl{lock}; f->open_array_section("run_contexts"); for (auto& i : run_contexts) { f->open_object_section("context"); ::encode_json("id", i.first, f); f->open_array_section("entries"); for (auto& s : i.second) { ::encode_json("entry", *s, f); } f->close_section(); f->close_section(); } f->close_section(); } RGWCoroutinesStack *RGWCoroutinesManager::allocate_stack() { return new RGWCoroutinesStack(cct, this); } string RGWCoroutinesManager::get_id() { if (!id.empty()) { return id; } stringstream ss; ss << (void *)this; return ss.str(); } void RGWCoroutinesManagerRegistry::add(RGWCoroutinesManager *mgr) { std::unique_lock wl{lock}; if (managers.find(mgr) == managers.end()) { managers.insert(mgr); get(); } } void RGWCoroutinesManagerRegistry::remove(RGWCoroutinesManager *mgr) { std::unique_lock wl{lock}; if (managers.find(mgr) != managers.end()) { managers.erase(mgr); put(); } } RGWCoroutinesManagerRegistry::~RGWCoroutinesManagerRegistry() { AdminSocket *admin_socket = cct->get_admin_socket(); if (!admin_command.empty()) { admin_socket->unregister_commands(this); } } int RGWCoroutinesManagerRegistry::hook_to_admin_command(const string& command) { AdminSocket *admin_socket = cct->get_admin_socket(); if (!admin_command.empty()) { admin_socket->unregister_commands(this); } admin_command = command; int r = admin_socket->register_command(admin_command, this, "dump current coroutines stack state"); if (r < 0) { lderr(cct) << "ERROR: fail to register admin socket command (r=" << r << ")" << dendl; return r; } return 0; } int RGWCoroutinesManagerRegistry::call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& out) { std::shared_lock rl{lock}; ::encode_json("cr_managers", *this, f); return 0; } void RGWCoroutinesManagerRegistry::dump(Formatter *f) const { f->open_array_section("coroutine_managers"); for (auto m : managers) { ::encode_json("entry", *m, f); } f->close_section(); } void RGWCoroutine::call(RGWCoroutine *op) { if (op) { stack->call(op); } else { // the call()er expects this to set a retcode retcode = 0; } } RGWCoroutinesStack *RGWCoroutine::spawn(RGWCoroutine *op, bool wait) { return stack->spawn(this, op, wait); } bool RGWCoroutine::collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id) /* returns true if needs to be called again */ { return stack->collect(this, ret, skip_stack, stack_id); } bool RGWCoroutine::collect_next(int *ret, RGWCoroutinesStack **collected_stack) /* returns true if found a stack to collect */ { return stack->collect_next(this, ret, collected_stack); } int RGWCoroutine::wait(const utime_t& interval) { return stack->wait(interval); } void RGWCoroutine::wait_for_child() { /* should only wait for child if there is a child that is not done yet, and no complete children */ if (spawned.entries.empty()) { return; } for (vector<RGWCoroutinesStack *>::iterator iter = spawned.entries.begin(); iter != spawned.entries.end(); ++iter) { if ((*iter)->is_done()) { return; } } stack->set_wait_for_child(true); } string RGWCoroutine::to_str() const { return typeid(*this).name(); } ostream& operator<<(ostream& out, const RGWCoroutine& cr) { out << "cr:s=" << (void *)cr.get_stack() << ":op=" << (void *)&cr << ":" << typeid(cr).name(); return out; } bool RGWCoroutine::drain_children(int num_cr_left, RGWCoroutinesStack *skip_stack, std::optional<std::function<void(uint64_t stack_id, int ret)> > cb) { bool done = false; ceph_assert(num_cr_left >= 0); if (num_cr_left == 0 && skip_stack) { num_cr_left = 1; } reenter(&drain_status.cr) { while (num_spawned() > (size_t)num_cr_left) { yield wait_for_child(); int ret; uint64_t stack_id; bool again = false; do { again = collect(&ret, skip_stack, &stack_id); if (ret < 0) { ldout(cct, 10) << "collect() returned ret=" << ret << dendl; /* we should have reported this error */ log_error() << "ERROR: collect() returned error (ret=" << ret << ")"; } if (cb) { (*cb)(stack_id, ret); } } while (again); } done = true; } return done; } bool RGWCoroutine::drain_children(int num_cr_left, std::optional<std::function<int(uint64_t stack_id, int ret)> > cb) { bool done = false; ceph_assert(num_cr_left >= 0); reenter(&drain_status.cr) { while (num_spawned() > (size_t)num_cr_left) { yield wait_for_child(); int ret; uint64_t stack_id; bool again = false; do { again = collect(&ret, nullptr, &stack_id); if (ret < 0) { ldout(cct, 10) << "collect() returned ret=" << ret << dendl; /* we should have reported this error */ log_error() << "ERROR: collect() returned error (ret=" << ret << ")"; } if (cb && !drain_status.should_exit) { int r = (*cb)(stack_id, ret); if (r < 0) { drain_status.ret = r; drain_status.should_exit = true; num_cr_left = 0; /* need to drain all */ } } } while (again); } done = true; } return done; } void RGWCoroutine::wakeup() { if (stack) { stack->wakeup(); } } RGWCoroutinesEnv *RGWCoroutine::get_env() const { return stack->get_env(); } void RGWCoroutine::dump(Formatter *f) const { if (!description.str().empty()) { encode_json("description", description.str(), f); } encode_json("type", to_str(), f); if (!spawned.entries.empty()) { f->open_array_section("spawned"); for (auto& i : spawned.entries) { char buf[32]; snprintf(buf, sizeof(buf), "%p", (void *)i); encode_json("stack", string(buf), f); } f->close_section(); } if (!status.history.empty()) { encode_json("history", status.history, f); } if (!status.status.str().empty()) { f->open_object_section("status"); encode_json("status", status.status.str(), f); encode_json("timestamp", status.timestamp, f); f->close_section(); } } RGWSimpleCoroutine::~RGWSimpleCoroutine() { if (!called_cleanup) { request_cleanup(); } } void RGWSimpleCoroutine::call_cleanup() { called_cleanup = true; request_cleanup(); } int RGWSimpleCoroutine::operate(const DoutPrefixProvider *dpp) { int ret = 0; reenter(this) { yield return state_init(); yield return state_send_request(dpp); yield return state_request_complete(); yield return state_all_complete(); drain_all(); call_cleanup(); return set_state(RGWCoroutine_Done, ret); } return 0; } int RGWSimpleCoroutine::state_init() { int ret = init(); if (ret < 0) { call_cleanup(); return set_state(RGWCoroutine_Error, ret); } return 0; } int RGWSimpleCoroutine::state_send_request(const DoutPrefixProvider *dpp) { int ret = send_request(dpp); if (ret < 0) { call_cleanup(); return set_state(RGWCoroutine_Error, ret); } return io_block(0); } int RGWSimpleCoroutine::state_request_complete() { int ret = request_complete(); if (ret < 0) { call_cleanup(); return set_state(RGWCoroutine_Error, ret); } return 0; } int RGWSimpleCoroutine::state_all_complete() { int ret = finish(); if (ret < 0) { call_cleanup(); return set_state(RGWCoroutine_Error, ret); } return 0; }
29,156
24.779841
200
cc
null
ceph-main/src/rgw/rgw_coroutine.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #ifdef _ASSERT_H #define NEED_ASSERT_H #pragma push_macro("_ASSERT_H") #endif #include <boost/asio.hpp> #include <boost/intrusive_ptr.hpp> #ifdef NEED_ASSERT_H #pragma pop_macro("_ASSERT_H") #endif #include "include/utime.h" #include "common/RefCountedObj.h" #include "common/debug.h" #include "common/Timer.h" #include "common/admin_socket.h" #include "rgw_common.h" #include "rgw_http_client_types.h" #include <boost/asio/coroutine.hpp> #include <atomic> #define RGW_ASYNC_OPS_MGR_WINDOW 100 class RGWCoroutinesStack; class RGWCoroutinesManager; class RGWAioCompletionNotifier; class RGWCompletionManager : public RefCountedObject { friend class RGWCoroutinesManager; CephContext *cct; struct io_completion { rgw_io_id io_id; void *user_info; }; std::list<io_completion> complete_reqs; std::set<rgw_io_id> complete_reqs_set; using NotifierRef = boost::intrusive_ptr<RGWAioCompletionNotifier>; std::set<NotifierRef> cns; ceph::mutex lock = ceph::make_mutex("RGWCompletionManager::lock"); ceph::condition_variable cond; SafeTimer timer; std::atomic<bool> going_down = { false }; std::map<void *, void *> waiters; class WaitContext; protected: void _wakeup(void *opaque); void _complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info); public: explicit RGWCompletionManager(CephContext *_cct); virtual ~RGWCompletionManager() override; void complete(RGWAioCompletionNotifier *cn, const rgw_io_id& io_id, void *user_info); int get_next(io_completion *io); bool try_get_next(io_completion *io); void go_down(); /* * wait for interval length to complete user_info */ void wait_interval(void *opaque, const utime_t& interval, void *user_info); void wakeup(void *opaque); void register_completion_notifier(RGWAioCompletionNotifier *cn); void unregister_completion_notifier(RGWAioCompletionNotifier *cn); }; /* a single use librados aio completion notifier that hooks into the RGWCompletionManager */ class RGWAioCompletionNotifier : public RefCountedObject { librados::AioCompletion *c; RGWCompletionManager *completion_mgr; rgw_io_id io_id; void *user_data; ceph::mutex lock = ceph::make_mutex("RGWAioCompletionNotifier"); bool registered; public: RGWAioCompletionNotifier(RGWCompletionManager *_mgr, const rgw_io_id& _io_id, void *_user_data); virtual ~RGWAioCompletionNotifier() override { c->release(); lock.lock(); bool need_unregister = registered; if (registered) { completion_mgr->get(); } registered = false; lock.unlock(); if (need_unregister) { completion_mgr->unregister_completion_notifier(this); completion_mgr->put(); } } librados::AioCompletion *completion() { return c; } void unregister() { std::lock_guard l{lock}; if (!registered) { return; } registered = false; } void cb() { lock.lock(); if (!registered) { lock.unlock(); put(); return; } completion_mgr->get(); registered = false; lock.unlock(); completion_mgr->complete(this, io_id, user_data); completion_mgr->put(); put(); } }; // completion notifier with opaque payload (ie a reference-counted pointer) template <typename T> class RGWAioCompletionNotifierWith : public RGWAioCompletionNotifier { T value; public: RGWAioCompletionNotifierWith(RGWCompletionManager *mgr, const rgw_io_id& io_id, void *user_data, T value) : RGWAioCompletionNotifier(mgr, io_id, user_data), value(std::move(value)) {} }; struct RGWCoroutinesEnv { uint64_t run_context; RGWCoroutinesManager *manager; std::list<RGWCoroutinesStack *> *scheduled_stacks; RGWCoroutinesStack *stack; RGWCoroutinesEnv() : run_context(0), manager(NULL), scheduled_stacks(NULL), stack(NULL) {} }; enum RGWCoroutineState { RGWCoroutine_Error = -2, RGWCoroutine_Done = -1, RGWCoroutine_Run = 0, }; struct rgw_spawned_stacks { std::vector<RGWCoroutinesStack *> entries; rgw_spawned_stacks() {} void add_pending(RGWCoroutinesStack *s) { entries.push_back(s); } void inherit(rgw_spawned_stacks *source) { for (auto* entry : source->entries) { add_pending(entry); } source->entries.clear(); } }; class RGWCoroutine : public RefCountedObject, public boost::asio::coroutine { friend class RGWCoroutinesStack; struct StatusItem { utime_t timestamp; std::string status; StatusItem(utime_t& t, const std::string& s) : timestamp(t), status(s) {} void dump(Formatter *f) const; }; #define MAX_COROUTINE_HISTORY 10 struct Status { CephContext *cct; ceph::shared_mutex lock = ceph::make_shared_mutex("RGWCoroutine::Status::lock"); int max_history; utime_t timestamp; std::stringstream status; explicit Status(CephContext *_cct) : cct(_cct), max_history(MAX_COROUTINE_HISTORY) {} std::deque<StatusItem> history; std::stringstream& set_status(); } status; std::stringstream description; protected: bool _yield_ret; struct { boost::asio::coroutine cr; bool should_exit{false}; int ret{0}; void init() { cr = boost::asio::coroutine(); should_exit = false; ret = 0; } } drain_status; CephContext *cct; RGWCoroutinesStack *stack; int retcode; int state; rgw_spawned_stacks spawned; std::stringstream error_stream; int set_state(int s, int ret = 0) { retcode = ret; state = s; return ret; } int set_cr_error(int ret) { return set_state(RGWCoroutine_Error, ret); } int set_cr_done() { return set_state(RGWCoroutine_Done, 0); } void set_io_blocked(bool flag); void reset_description() { description.str(std::string()); } std::stringstream& set_description() { return description; } std::stringstream& set_status() { return status.set_status(); } std::stringstream& set_status(const std::string& s) { std::stringstream& status = set_status(); status << s; return status; } virtual int operate_wrapper(const DoutPrefixProvider *dpp) { return operate(dpp); } public: RGWCoroutine(CephContext *_cct) : status(_cct), _yield_ret(false), cct(_cct), stack(NULL), retcode(0), state(RGWCoroutine_Run) {} virtual ~RGWCoroutine() override; virtual int operate(const DoutPrefixProvider *dpp) = 0; bool is_done() { return (state == RGWCoroutine_Done || state == RGWCoroutine_Error); } bool is_error() { return (state == RGWCoroutine_Error); } std::stringstream& log_error() { return error_stream; } std::string error_str() { return error_stream.str(); } void set_retcode(int r) { retcode = r; } int get_ret_status() { return retcode; } void call(RGWCoroutine *op); /* call at the same stack we're in */ RGWCoroutinesStack *spawn(RGWCoroutine *op, bool wait); /* execute on a different stack */ bool collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id = nullptr); /* returns true if needs to be called again */ bool collect_next(int *ret, RGWCoroutinesStack **collected_stack = NULL); /* returns true if found a stack to collect */ int wait(const utime_t& interval); bool drain_children(int num_cr_left, RGWCoroutinesStack *skip_stack = nullptr, std::optional<std::function<void(uint64_t stack_id, int ret)> > cb = std::nullopt); /* returns true if needed to be called again, cb will be called on completion of every completion. */ bool drain_children(int num_cr_left, std::optional<std::function<int(uint64_t stack_id, int ret)> > cb); /* returns true if needed to be called again, cb will be called on every completion, can filter errors. A negative return value from cb means that current cr will need to exit */ void wakeup(); void set_sleeping(bool flag); /* put in sleep, or wakeup from sleep */ size_t num_spawned() { return spawned.entries.size(); } void wait_for_child(); virtual std::string to_str() const; RGWCoroutinesStack *get_stack() const { return stack; } RGWCoroutinesEnv *get_env() const; void dump(Formatter *f) const; void init_new_io(RGWIOProvider *io_provider); /* only links the default io id */ int io_block(int ret = 0) { return io_block(ret, -1); } int io_block(int ret, int64_t io_id); int io_block(int ret, const rgw_io_id& io_id); void io_complete() { io_complete(rgw_io_id{}); } void io_complete(const rgw_io_id& io_id); }; std::ostream& operator<<(std::ostream& out, const RGWCoroutine& cr); #define yield_until_true(x) \ do { \ do { \ yield _yield_ret = x; \ } while (!_yield_ret); \ _yield_ret = false; \ } while (0) #define drain_all() \ drain_status.init(); \ yield_until_true(drain_children(0)) #define drain_all_but(n) \ drain_status.init(); \ yield_until_true(drain_children(n)) #define drain_all_but_stack(stack) \ drain_status.init(); \ yield_until_true(drain_children(1, stack)) #define drain_all_but_stack_cb(stack, cb) \ drain_status.init(); \ yield_until_true(drain_children(1, stack, cb)) #define drain_with_cb(n, cb) \ drain_status.init(); \ yield_until_true(drain_children(n, cb)); \ if (drain_status.should_exit) { \ return set_cr_error(drain_status.ret); \ } #define drain_all_cb(cb) \ drain_with_cb(0, cb) #define yield_spawn_window(cr, n, cb) \ do { \ spawn(cr, false); \ drain_with_cb(n, cb); /* this is guaranteed to yield */ \ } while (0) template <class T> class RGWConsumerCR : public RGWCoroutine { std::list<T> product; public: explicit RGWConsumerCR(CephContext *_cct) : RGWCoroutine(_cct) {} bool has_product() { return !product.empty(); } void wait_for_product() { if (!has_product()) { set_sleeping(true); } } bool consume(T *p) { if (product.empty()) { return false; } *p = product.front(); product.pop_front(); return true; } void receive(const T& p, bool wakeup = true); void receive(std::list<T>& l, bool wakeup = true); }; class RGWCoroutinesStack : public RefCountedObject { friend class RGWCoroutine; friend class RGWCoroutinesManager; CephContext *cct; int64_t id{-1}; RGWCoroutinesManager *ops_mgr; std::list<RGWCoroutine *> ops; std::list<RGWCoroutine *>::iterator pos; rgw_spawned_stacks spawned; std::set<RGWCoroutinesStack *> blocked_by_stack; std::set<RGWCoroutinesStack *> blocking_stacks; std::map<int64_t, rgw_io_id> io_finish_ids; rgw_io_id io_blocked_id; bool done_flag; bool error_flag; bool blocked_flag; bool sleep_flag; bool interval_wait_flag; bool is_scheduled; bool is_waiting_for_child; int retcode; uint64_t run_count; protected: RGWCoroutinesEnv *env; RGWCoroutinesStack *parent; RGWCoroutinesStack *spawn(RGWCoroutine *source_op, RGWCoroutine *next_op, bool wait); bool collect(RGWCoroutine *op, int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id); /* returns true if needs to be called again */ bool collect_next(RGWCoroutine *op, int *ret, RGWCoroutinesStack **collected_stack); /* returns true if found a stack to collect */ public: RGWCoroutinesStack(CephContext *_cct, RGWCoroutinesManager *_ops_mgr, RGWCoroutine *start = NULL); virtual ~RGWCoroutinesStack() override; int64_t get_id() const { return id; } int operate(const DoutPrefixProvider *dpp, RGWCoroutinesEnv *env); bool is_done() { return done_flag; } bool is_error() { return error_flag; } bool is_blocked_by_stack() { return !blocked_by_stack.empty(); } void set_io_blocked(bool flag) { blocked_flag = flag; } void set_io_blocked_id(const rgw_io_id& io_id) { io_blocked_id = io_id; } bool is_io_blocked() { return blocked_flag && !done_flag; } bool can_io_unblock(const rgw_io_id& io_id) { return ((io_blocked_id.id < 0) || io_blocked_id.intersects(io_id)); } bool try_io_unblock(const rgw_io_id& io_id); bool consume_io_finish(const rgw_io_id& io_id); void set_interval_wait(bool flag) { interval_wait_flag = flag; } bool is_interval_waiting() { return interval_wait_flag; } void set_sleeping(bool flag) { bool wakeup = sleep_flag & !flag; sleep_flag = flag; if (wakeup) { schedule(); } } bool is_sleeping() { return sleep_flag; } void set_is_scheduled(bool flag) { is_scheduled = flag; } bool is_blocked() { return is_blocked_by_stack() || is_sleeping() || is_io_blocked() || waiting_for_child() ; } void schedule(); void _schedule(); int get_ret_status() { return retcode; } std::string error_str(); void call(RGWCoroutine *next_op); RGWCoroutinesStack *spawn(RGWCoroutine *next_op, bool wait); int unwind(int retcode); int wait(const utime_t& interval); void wakeup(); void io_complete() { io_complete(rgw_io_id{}); } void io_complete(const rgw_io_id& io_id); bool collect(int *ret, RGWCoroutinesStack *skip_stack, uint64_t *stack_id); /* returns true if needs to be called again */ void cancel(); RGWAioCompletionNotifier *create_completion_notifier(); template <typename T> RGWAioCompletionNotifier *create_completion_notifier(T value); RGWCompletionManager *get_completion_mgr(); void set_blocked_by(RGWCoroutinesStack *s) { blocked_by_stack.insert(s); s->blocking_stacks.insert(this); } void set_wait_for_child(bool flag) { is_waiting_for_child = flag; } bool waiting_for_child() { return is_waiting_for_child; } bool unblock_stack(RGWCoroutinesStack **s); RGWCoroutinesEnv *get_env() const { return env; } void dump(Formatter *f) const; void init_new_io(RGWIOProvider *io_provider); }; template <class T> void RGWConsumerCR<T>::receive(std::list<T>& l, bool wakeup) { product.splice(product.end(), l); if (wakeup) { set_sleeping(false); } } template <class T> void RGWConsumerCR<T>::receive(const T& p, bool wakeup) { product.push_back(p); if (wakeup) { set_sleeping(false); } } class RGWCoroutinesManagerRegistry : public RefCountedObject, public AdminSocketHook { CephContext *cct; std::set<RGWCoroutinesManager *> managers; ceph::shared_mutex lock = ceph::make_shared_mutex("RGWCoroutinesRegistry::lock"); std::string admin_command; public: explicit RGWCoroutinesManagerRegistry(CephContext *_cct) : cct(_cct) {} virtual ~RGWCoroutinesManagerRegistry() override; void add(RGWCoroutinesManager *mgr); void remove(RGWCoroutinesManager *mgr); int hook_to_admin_command(const std::string& command); int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& ss, bufferlist& out) override; void dump(Formatter *f) const; }; class RGWCoroutinesManager { CephContext *cct; std::atomic<bool> going_down = { false }; std::atomic<int64_t> run_context_count = { 0 }; std::map<uint64_t, std::set<RGWCoroutinesStack *> > run_contexts; std::atomic<int64_t> max_io_id = { 0 }; std::atomic<uint64_t> max_stack_id = { 0 }; mutable ceph::shared_mutex lock = ceph::make_shared_mutex("RGWCoroutinesManager::lock"); RGWIOIDProvider io_id_provider; void handle_unblocked_stack(std::set<RGWCoroutinesStack *>& context_stacks, std::list<RGWCoroutinesStack *>& scheduled_stacks, RGWCompletionManager::io_completion& io, int *waiting_count, int *interval_wait_count); protected: RGWCompletionManager *completion_mgr; RGWCoroutinesManagerRegistry *cr_registry; int ops_window; std::string id; void put_completion_notifier(RGWAioCompletionNotifier *cn); public: RGWCoroutinesManager(CephContext *_cct, RGWCoroutinesManagerRegistry *_cr_registry) : cct(_cct), cr_registry(_cr_registry), ops_window(RGW_ASYNC_OPS_MGR_WINDOW) { completion_mgr = new RGWCompletionManager(cct); if (cr_registry) { cr_registry->add(this); } } virtual ~RGWCoroutinesManager(); int run(const DoutPrefixProvider *dpp, std::list<RGWCoroutinesStack *>& ops); int run(const DoutPrefixProvider *dpp, RGWCoroutine *op); void stop() { bool expected = false; if (going_down.compare_exchange_strong(expected, true)) { completion_mgr->go_down(); } } virtual void report_error(RGWCoroutinesStack *op); RGWAioCompletionNotifier *create_completion_notifier(RGWCoroutinesStack *stack); template <typename T> RGWAioCompletionNotifier *create_completion_notifier(RGWCoroutinesStack *stack, T value); RGWCompletionManager *get_completion_mgr() { return completion_mgr; } void schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack); void _schedule(RGWCoroutinesEnv *env, RGWCoroutinesStack *stack); RGWCoroutinesStack *allocate_stack(); int64_t get_next_io_id(); uint64_t get_next_stack_id(); void set_sleeping(RGWCoroutine *cr, bool flag); void io_complete(RGWCoroutine *cr, const rgw_io_id& io_id); virtual std::string get_id(); void dump(Formatter *f) const; RGWIOIDProvider& get_io_id_provider() { return io_id_provider; } }; template <typename T> RGWAioCompletionNotifier *RGWCoroutinesManager::create_completion_notifier(RGWCoroutinesStack *stack, T value) { rgw_io_id io_id{get_next_io_id(), -1}; RGWAioCompletionNotifier *cn = new RGWAioCompletionNotifierWith<T>(completion_mgr, io_id, (void *)stack, std::move(value)); completion_mgr->register_completion_notifier(cn); return cn; } template <typename T> RGWAioCompletionNotifier *RGWCoroutinesStack::create_completion_notifier(T value) { return ops_mgr->create_completion_notifier(this, std::move(value)); } class RGWSimpleCoroutine : public RGWCoroutine { bool called_cleanup; int operate(const DoutPrefixProvider *dpp) override; int state_init(); int state_send_request(const DoutPrefixProvider *dpp); int state_request_complete(); int state_all_complete(); void call_cleanup(); public: RGWSimpleCoroutine(CephContext *_cct) : RGWCoroutine(_cct), called_cleanup(false) {} virtual ~RGWSimpleCoroutine() override; virtual int init() { return 0; } virtual int send_request(const DoutPrefixProvider *dpp) = 0; virtual int request_complete() = 0; virtual int finish() { return 0; } virtual void request_cleanup() {} };
19,197
25.55325
153
h
null
ceph-main/src/rgw/rgw_cors.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <string.h> #include <iostream> #include <map> #include <boost/algorithm/string.hpp> #include "include/types.h" #include "common/debug.h" #include "include/str_list.h" #include "common/Formatter.h" #include "rgw_cors.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; void RGWCORSRule::dump_origins() { unsigned num_origins = allowed_origins.size(); dout(10) << "Allowed origins : " << num_origins << dendl; for(auto& origin : allowed_origins) { dout(10) << origin << "," << dendl; } } void RGWCORSRule::erase_origin_if_present(string& origin, bool *rule_empty) { set<string>::iterator it = allowed_origins.find(origin); if (!rule_empty) return; *rule_empty = false; if (it != allowed_origins.end()) { dout(10) << "Found origin " << origin << ", set size:" << allowed_origins.size() << dendl; allowed_origins.erase(it); *rule_empty = (allowed_origins.empty()); } } /* * make attrs look-like-this * does not convert underscores or dashes * * Per CORS specification, section 3: * === * "Converting a string to ASCII lowercase" means replacing all characters in the * range U+0041 LATIN CAPITAL LETTER A to U+005A LATIN CAPITAL LETTER Z with * the corresponding characters in the range U+0061 LATIN SMALL LETTER A to * U+007A LATIN SMALL LETTER Z). * === * * @todo When UTF-8 is allowed in HTTP headers, this function will need to change */ string lowercase_http_attr(const string& orig) { const char *s = orig.c_str(); char buf[orig.size() + 1]; buf[orig.size()] = '\0'; for (size_t i = 0; i < orig.size(); ++i, ++s) { buf[i] = tolower(*s); } return string(buf); } static bool is_string_in_set(set<string>& s, string h) { if ((s.find("*") != s.end()) || (s.find(h) != s.end())) { return true; } /* The header can be Content-*-type, or Content-* */ for(set<string>::iterator it = s.begin(); it != s.end(); ++it) { size_t off; if ((off = (*it).find("*"))!=string::npos) { list<string> ssplit; unsigned flen = 0; get_str_list((*it), "* \t", ssplit); if (off != 0) { string sl = ssplit.front(); flen = sl.length(); dout(10) << "Finding " << sl << ", in " << h << ", at offset 0" << dendl; if (!boost::algorithm::starts_with(h,sl)) continue; ssplit.pop_front(); } if (off != ((*it).length() - 1)) { string sl = ssplit.front(); dout(10) << "Finding " << sl << ", in " << h << ", at offset not less than " << flen << dendl; if (h.size() < sl.size() || h.compare((h.size() - sl.size()), sl.size(), sl) != 0) continue; ssplit.pop_front(); } if (!ssplit.empty()) continue; return true; } } return false; } bool RGWCORSRule::has_wildcard_origin() { if (allowed_origins.find("*") != allowed_origins.end()) return true; return false; } bool RGWCORSRule::is_origin_present(const char *o) { string origin = o; return is_string_in_set(allowed_origins, origin); } bool RGWCORSRule::is_header_allowed(const char *h, size_t len) { string hdr(h, len); if(lowercase_allowed_hdrs.empty()) { set<string>::iterator iter; for (iter = allowed_hdrs.begin(); iter != allowed_hdrs.end(); ++iter) { lowercase_allowed_hdrs.insert(lowercase_http_attr(*iter)); } } return is_string_in_set(lowercase_allowed_hdrs, lowercase_http_attr(hdr)); } void RGWCORSRule::format_exp_headers(string& s) { s = ""; for (const auto& header : exposable_hdrs) { if (s.length() > 0) s.append(","); // these values are sent to clients in a 'Access-Control-Expose-Headers' // response header, so we escape '\n' to avoid header injection boost::replace_all_copy(std::back_inserter(s), header, "\n", "\\n"); } } RGWCORSRule * RGWCORSConfiguration::host_name_rule(const char *origin) { for(list<RGWCORSRule>::iterator it_r = rules.begin(); it_r != rules.end(); ++it_r) { RGWCORSRule& r = (*it_r); if (r.is_origin_present(origin)) return &r; } return NULL; } void RGWCORSConfiguration::erase_host_name_rule(string& origin) { bool rule_empty; unsigned loop = 0; /*Erase the host name from that rule*/ dout(10) << "Num of rules : " << rules.size() << dendl; for(list<RGWCORSRule>::iterator it_r = rules.begin(); it_r != rules.end(); ++it_r, loop++) { RGWCORSRule& r = (*it_r); r.erase_origin_if_present(origin, &rule_empty); dout(10) << "Origin:" << origin << ", rule num:" << loop << ", emptying now:" << rule_empty << dendl; if (rule_empty) { rules.erase(it_r); break; } } } void RGWCORSConfiguration::dump() { unsigned loop = 1; unsigned num_rules = rules.size(); dout(10) << "Number of rules: " << num_rules << dendl; for(list<RGWCORSRule>::iterator it = rules.begin(); it!= rules.end(); ++it, loop++) { dout(10) << " <<<<<<< Rule " << loop << " >>>>>>> " << dendl; (*it).dump_origins(); } }
5,513
27.42268
81
cc
null
ceph-main/src/rgw/rgw_cors.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <map> #include <string> #include <include/types.h> #define RGW_CORS_GET 0x1 #define RGW_CORS_PUT 0x2 #define RGW_CORS_HEAD 0x4 #define RGW_CORS_POST 0x8 #define RGW_CORS_DELETE 0x10 #define RGW_CORS_COPY 0x20 #define RGW_CORS_ALL (RGW_CORS_GET | \ RGW_CORS_PUT | \ RGW_CORS_HEAD | \ RGW_CORS_POST | \ RGW_CORS_DELETE | \ RGW_CORS_COPY) #define CORS_MAX_AGE_INVALID ((uint32_t)-1) class RGWCORSRule { protected: uint32_t max_age; uint8_t allowed_methods; std::string id; std::set<std::string> allowed_hdrs; /* If you change this, you need to discard lowercase_allowed_hdrs */ std::set<std::string> lowercase_allowed_hdrs; /* Not built until needed in RGWCORSRule::is_header_allowed */ std::set<std::string> allowed_origins; std::list<std::string> exposable_hdrs; public: RGWCORSRule() : max_age(CORS_MAX_AGE_INVALID),allowed_methods(0) {} RGWCORSRule(std::set<std::string>& o, std::set<std::string>& h, std::list<std::string>& e, uint8_t f, uint32_t a) :max_age(a), allowed_methods(f), allowed_hdrs(h), allowed_origins(o), exposable_hdrs(e) {} virtual ~RGWCORSRule() {} std::string& get_id() { return id; } uint32_t get_max_age() { return max_age; } uint8_t get_allowed_methods() { return allowed_methods; } void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(max_age, bl); encode(allowed_methods, bl); encode(id, bl); encode(allowed_hdrs, bl); encode(allowed_origins, bl); encode(exposable_hdrs, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(max_age, bl); decode(allowed_methods, bl); decode(id, bl); decode(allowed_hdrs, bl); decode(allowed_origins, bl); decode(exposable_hdrs, bl); DECODE_FINISH(bl); } bool has_wildcard_origin(); bool is_origin_present(const char *o); void format_exp_headers(std::string& s); void erase_origin_if_present(std::string& origin, bool *rule_empty); void dump_origins(); void dump(Formatter *f) const; bool is_header_allowed(const char *hdr, size_t len); }; WRITE_CLASS_ENCODER(RGWCORSRule) class RGWCORSConfiguration { protected: std::list<RGWCORSRule> rules; public: RGWCORSConfiguration() {} ~RGWCORSConfiguration() {} void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(rules, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(rules, bl); DECODE_FINISH(bl); } void dump(Formatter *f) const; std::list<RGWCORSRule>& get_rules() { return rules; } bool is_empty() { return rules.empty(); } void get_origins_list(const char *origin, std::list<std::string>& origins); RGWCORSRule * host_name_rule(const char *origin); void erase_host_name_rule(std::string& origin); void dump(); void stack_rule(RGWCORSRule& r) { rules.push_front(r); } }; WRITE_CLASS_ENCODER(RGWCORSConfiguration) static inline int validate_name_string(std::string_view o) { if (o.length() == 0) return -1; if (o.find_first_of("*") != o.find_last_of("*")) return -1; return 0; }
3,817
27.281481
110
h
null
ceph-main/src/rgw/rgw_cors_s3.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <string.h> #include <limits.h> #include <iostream> #include <map> #include "include/types.h" #include "rgw_cors_s3.h" #include "rgw_user.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; void RGWCORSRule_S3::to_xml(XMLFormatter& f) { f.open_object_section("CORSRule"); /*ID if present*/ if (id.length() > 0) { f.dump_string("ID", id); } /*AllowedMethods*/ if (allowed_methods & RGW_CORS_GET) f.dump_string("AllowedMethod", "GET"); if (allowed_methods & RGW_CORS_PUT) f.dump_string("AllowedMethod", "PUT"); if (allowed_methods & RGW_CORS_DELETE) f.dump_string("AllowedMethod", "DELETE"); if (allowed_methods & RGW_CORS_HEAD) f.dump_string("AllowedMethod", "HEAD"); if (allowed_methods & RGW_CORS_POST) f.dump_string("AllowedMethod", "POST"); if (allowed_methods & RGW_CORS_COPY) f.dump_string("AllowedMethod", "COPY"); /*AllowedOrigins*/ for(set<string>::iterator it = allowed_origins.begin(); it != allowed_origins.end(); ++it) { string host = *it; f.dump_string("AllowedOrigin", host); } /*AllowedHeader*/ for(set<string>::iterator it = allowed_hdrs.begin(); it != allowed_hdrs.end(); ++it) { f.dump_string("AllowedHeader", *it); } /*MaxAgeSeconds*/ if (max_age != CORS_MAX_AGE_INVALID) { f.dump_unsigned("MaxAgeSeconds", max_age); } /*ExposeHeader*/ for(list<string>::iterator it = exposable_hdrs.begin(); it != exposable_hdrs.end(); ++it) { f.dump_string("ExposeHeader", *it); } f.close_section(); } bool RGWCORSRule_S3::xml_end(const char *el) { XMLObjIter iter = find("AllowedMethod"); XMLObj *obj; /*Check all the allowedmethods*/ obj = iter.get_next(); if (obj) { for( ; obj; obj = iter.get_next()) { const char *s = obj->get_data().c_str(); ldpp_dout(dpp, 10) << "RGWCORSRule::xml_end, el : " << el << ", data : " << s << dendl; if (strcasecmp(s, "GET") == 0) { allowed_methods |= RGW_CORS_GET; } else if (strcasecmp(s, "POST") == 0) { allowed_methods |= RGW_CORS_POST; } else if (strcasecmp(s, "DELETE") == 0) { allowed_methods |= RGW_CORS_DELETE; } else if (strcasecmp(s, "HEAD") == 0) { allowed_methods |= RGW_CORS_HEAD; } else if (strcasecmp(s, "PUT") == 0) { allowed_methods |= RGW_CORS_PUT; } else if (strcasecmp(s, "COPY") == 0) { allowed_methods |= RGW_CORS_COPY; } else { return false; } } } /*Check the id's len, it should be less than 255*/ XMLObj *xml_id = find_first("ID"); if (xml_id != NULL) { string data = xml_id->get_data(); if (data.length() > 255) { ldpp_dout(dpp, 0) << "RGWCORSRule has id of length greater than 255" << dendl; return false; } ldpp_dout(dpp, 10) << "RGWCORRule id : " << data << dendl; id = data; } /*Check if there is atleast one AllowedOrigin*/ iter = find("AllowedOrigin"); if (!(obj = iter.get_next())) { ldpp_dout(dpp, 0) << "RGWCORSRule does not have even one AllowedOrigin" << dendl; return false; } for( ; obj; obj = iter.get_next()) { ldpp_dout(dpp, 10) << "RGWCORSRule - origin : " << obj->get_data() << dendl; /*Just take the hostname*/ string host = obj->get_data(); if (validate_name_string(host) != 0) return false; allowed_origins.insert(allowed_origins.end(), host); } /*Check of max_age*/ iter = find("MaxAgeSeconds"); if ((obj = iter.get_next())) { char *end = NULL; unsigned long long ull = strtoull(obj->get_data().c_str(), &end, 10); if (*end != '\0') { ldpp_dout(dpp, 0) << "RGWCORSRule's MaxAgeSeconds " << obj->get_data() << " is an invalid integer" << dendl; return false; } if (ull >= 0x100000000ull) { max_age = CORS_MAX_AGE_INVALID; } else { max_age = (uint32_t)ull; } ldpp_dout(dpp, 10) << "RGWCORSRule : max_age : " << max_age << dendl; } /*Check and update ExposeHeader*/ iter = find("ExposeHeader"); if ((obj = iter.get_next())) { for(; obj; obj = iter.get_next()) { ldpp_dout(dpp, 10) << "RGWCORSRule - exp_hdr : " << obj->get_data() << dendl; exposable_hdrs.push_back(obj->get_data()); } } /*Check and update AllowedHeader*/ iter = find("AllowedHeader"); if ((obj = iter.get_next())) { for(; obj; obj = iter.get_next()) { ldpp_dout(dpp, 10) << "RGWCORSRule - allowed_hdr : " << obj->get_data() << dendl; string s = obj->get_data(); if (validate_name_string(s) != 0) return false; allowed_hdrs.insert(allowed_hdrs.end(), s); } } return true; } void RGWCORSConfiguration_S3::to_xml(ostream& out) { XMLFormatter f; f.open_object_section_in_ns("CORSConfiguration", XMLNS_AWS_S3); for(list<RGWCORSRule>::iterator it = rules.begin(); it != rules.end(); ++it) { (static_cast<RGWCORSRule_S3 &>(*it)).to_xml(f); } f.close_section(); f.flush(out); } bool RGWCORSConfiguration_S3::xml_end(const char *el) { XMLObjIter iter = find("CORSRule"); RGWCORSRule_S3 *obj; if (!(obj = static_cast<RGWCORSRule_S3 *>(iter.get_next()))) { ldpp_dout(dpp, 0) << "CORSConfiguration should have atleast one CORSRule" << dendl; return false; } for(; obj; obj = static_cast<RGWCORSRule_S3 *>(iter.get_next())) { rules.push_back(*obj); } return true; } class CORSRuleID_S3 : public XMLObj { public: CORSRuleID_S3() {} ~CORSRuleID_S3() override {} }; class CORSRuleAllowedOrigin_S3 : public XMLObj { public: CORSRuleAllowedOrigin_S3() {} ~CORSRuleAllowedOrigin_S3() override {} }; class CORSRuleAllowedMethod_S3 : public XMLObj { public: CORSRuleAllowedMethod_S3() {} ~CORSRuleAllowedMethod_S3() override {} }; class CORSRuleAllowedHeader_S3 : public XMLObj { public: CORSRuleAllowedHeader_S3() {} ~CORSRuleAllowedHeader_S3() override {} }; class CORSRuleMaxAgeSeconds_S3 : public XMLObj { public: CORSRuleMaxAgeSeconds_S3() {} ~CORSRuleMaxAgeSeconds_S3() override {} }; class CORSRuleExposeHeader_S3 : public XMLObj { public: CORSRuleExposeHeader_S3() {} ~CORSRuleExposeHeader_S3() override {} }; XMLObj *RGWCORSXMLParser_S3::alloc_obj(const char *el) { if (strcmp(el, "CORSConfiguration") == 0) { return new RGWCORSConfiguration_S3(dpp); } else if (strcmp(el, "CORSRule") == 0) { return new RGWCORSRule_S3(dpp); } else if (strcmp(el, "ID") == 0) { return new CORSRuleID_S3; } else if (strcmp(el, "AllowedOrigin") == 0) { return new CORSRuleAllowedOrigin_S3; } else if (strcmp(el, "AllowedMethod") == 0) { return new CORSRuleAllowedMethod_S3; } else if (strcmp(el, "AllowedHeader") == 0) { return new CORSRuleAllowedHeader_S3; } else if (strcmp(el, "MaxAgeSeconds") == 0) { return new CORSRuleMaxAgeSeconds_S3; } else if (strcmp(el, "ExposeHeader") == 0) { return new CORSRuleExposeHeader_S3; } return NULL; }
7,425
29.064777
114
cc
null
ceph-main/src/rgw/rgw_cors_s3.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <map> #include <string> #include <iosfwd> #include <include/types.h> #include <common/Formatter.h> #include <common/dout.h> #include "rgw_xml.h" #include "rgw_cors.h" class RGWCORSRule_S3 : public RGWCORSRule, public XMLObj { const DoutPrefixProvider *dpp; public: RGWCORSRule_S3(const DoutPrefixProvider *dpp) : dpp(dpp) {} ~RGWCORSRule_S3() override {} bool xml_end(const char *el) override; void to_xml(XMLFormatter& f); }; class RGWCORSConfiguration_S3 : public RGWCORSConfiguration, public XMLObj { const DoutPrefixProvider *dpp; public: RGWCORSConfiguration_S3(const DoutPrefixProvider *dpp) : dpp(dpp) {} ~RGWCORSConfiguration_S3() override {} bool xml_end(const char *el) override; void to_xml(std::ostream& out); }; class RGWCORSXMLParser_S3 : public RGWXMLParser { const DoutPrefixProvider *dpp; CephContext *cct; XMLObj *alloc_obj(const char *el) override; public: explicit RGWCORSXMLParser_S3(const DoutPrefixProvider *_dpp, CephContext *_cct) : dpp(_dpp), cct(_cct) {} };
1,504
24.508475
107
h
null
ceph-main/src/rgw/rgw_cors_swift.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2013 eNovance SAS <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <map> #include <string> #include <vector> #include <include/types.h> #include <include/str_list.h> #include "rgw_cors.h" class RGWCORSConfiguration_SWIFT : public RGWCORSConfiguration { public: RGWCORSConfiguration_SWIFT() {} ~RGWCORSConfiguration_SWIFT() {} int create_update(const char *allow_origins, const char *allow_headers, const char *expose_headers, const char *max_age) { std::set<std::string> o, h; std::list<std::string> e; unsigned long a = CORS_MAX_AGE_INVALID; uint8_t flags = RGW_CORS_ALL; int nr_invalid_names = 0; auto add_host = [&nr_invalid_names, &o] (auto host) { if (validate_name_string(host) == 0) { o.emplace(std::string{host}); } else { nr_invalid_names++; } }; for_each_substr(allow_origins, ";,= \t", add_host); if (o.empty() || nr_invalid_names > 0) { return -EINVAL; } if (allow_headers) { int nr_invalid_headers = 0; auto add_header = [&nr_invalid_headers, &h] (auto allow_header) { if (validate_name_string(allow_header) == 0) { h.emplace(std::string{allow_header}); } else { nr_invalid_headers++; } }; for_each_substr(allow_headers, ";,= \t", add_header); if (h.empty() || nr_invalid_headers > 0) { return -EINVAL; } } if (expose_headers) { for_each_substr(expose_headers, ";,= \t", [&e] (auto expose_header) { e.emplace_back(std::string(expose_header)); }); } if (max_age) { char *end = NULL; a = strtoul(max_age, &end, 10); if (a == ULONG_MAX) a = CORS_MAX_AGE_INVALID; } RGWCORSRule rule(o, h, e, flags, a); stack_rule(rule); return 0; } };
2,339
26.857143
76
h
null
ceph-main/src/rgw/rgw_cr_rest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_cr_rest.h" #include "rgw_coroutine.h" // re-include our assert to clobber the system one; fix dout: #include "include/ceph_assert.h" #include <boost/asio/yield.hpp> #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; RGWCRHTTPGetDataCB::RGWCRHTTPGetDataCB(RGWCoroutinesEnv *_env, RGWCoroutine *_cr, RGWHTTPStreamRWRequest *_req) : env(_env), cr(_cr), req(_req) { io_id = req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_READ |RGWHTTPClient::HTTPCLIENT_IO_CONTROL); req->set_in_cb(this); } #define GET_DATA_WINDOW_SIZE 2 * 1024 * 1024 int RGWCRHTTPGetDataCB::handle_data(bufferlist& bl, bool *pause) { if (data.length() < GET_DATA_WINDOW_SIZE / 2) { notified = false; } { uint64_t bl_len = bl.length(); std::lock_guard l{lock}; if (!got_all_extra_data) { uint64_t max = extra_data_len - extra_data.length(); if (max > bl_len) { max = bl_len; } bl.splice(0, max, &extra_data); bl_len -= max; got_all_extra_data = extra_data.length() == extra_data_len; } data.append(bl); } uint64_t data_len = data.length(); if (data_len >= GET_DATA_WINDOW_SIZE && !notified) { notified = true; env->manager->io_complete(cr, io_id); } if (data_len >= 2 * GET_DATA_WINDOW_SIZE) { *pause = true; paused = true; } return 0; } void RGWCRHTTPGetDataCB::claim_data(bufferlist *dest, uint64_t max) { bool need_to_unpause = false; { std::lock_guard l{lock}; if (data.length() == 0) { return; } if (data.length() < max) { max = data.length(); } data.splice(0, max, dest); need_to_unpause = (paused && data.length() <= GET_DATA_WINDOW_SIZE); } if (need_to_unpause) { req->unpause_receive(); } } RGWStreamReadHTTPResourceCRF::~RGWStreamReadHTTPResourceCRF() { if (req) { req->cancel(); req->wait(null_yield); delete req; } } int RGWStreamReadHTTPResourceCRF::init(const DoutPrefixProvider *dpp) { env->stack->init_new_io(req); in_cb.emplace(env, caller, req); int r = req->send(http_manager); if (r < 0) { return r; } return 0; } int RGWStreamWriteHTTPResourceCRF::send() { env->stack->init_new_io(req); req->set_write_drain_cb(&write_drain_notify_cb); int r = req->send(http_manager); if (r < 0) { return r; } return 0; } bool RGWStreamReadHTTPResourceCRF::has_attrs() { return got_attrs; } void RGWStreamReadHTTPResourceCRF::get_attrs(std::map<string, string> *attrs) { req->get_out_headers(attrs); } int RGWStreamReadHTTPResourceCRF::decode_rest_obj(const DoutPrefixProvider *dpp, map<string, string>& headers, bufferlist& extra_data) { /* basic generic implementation */ for (auto header : headers) { const string& val = header.second; rest_obj.attrs[header.first] = val; } return 0; } int RGWStreamReadHTTPResourceCRF::read(const DoutPrefixProvider *dpp, bufferlist *out, uint64_t max_size, bool *io_pending) { reenter(&read_state) { io_read_mask = req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_READ | RGWHTTPClient::HTTPCLIENT_IO_CONTROL); while (!req->is_done() || in_cb->has_data()) { *io_pending = true; if (!in_cb->has_data()) { yield caller->io_block(0, io_read_mask); } got_attrs = true; if (need_extra_data() && !got_extra_data) { if (!in_cb->has_all_extra_data()) { continue; } extra_data.claim_append(in_cb->get_extra_data()); map<string, string> attrs; req->get_out_headers(&attrs); int ret = decode_rest_obj(dpp, attrs, extra_data); if (ret < 0) { ldout(cct, 0) << "ERROR: " << __func__ << " decode_rest_obj() returned ret=" << ret << dendl; return ret; } got_extra_data = true; } *io_pending = false; in_cb->claim_data(out, max_size); if (out->length() == 0) { /* this may happen if we just read the prepended extra_data and didn't have any data * after. In that case, retry reading, so that caller doesn't assume it's EOF. */ continue; } if (!req->is_done() || out->length() >= max_size) { yield; } } } return 0; } bool RGWStreamReadHTTPResourceCRF::is_done() { return req->is_done(); } RGWStreamWriteHTTPResourceCRF::~RGWStreamWriteHTTPResourceCRF() { if (req) { req->cancel(); req->wait(null_yield); delete req; } } void RGWStreamWriteHTTPResourceCRF::send_ready(const DoutPrefixProvider *dpp, const rgw_rest_obj& rest_obj) { req->set_send_length(rest_obj.content_len); for (auto h : rest_obj.attrs) { req->append_header(h.first, h.second); } } #define PENDING_WRITES_WINDOW (1 * 1024 * 1024) void RGWStreamWriteHTTPResourceCRF::write_drain_notify(uint64_t pending_size) { lock_guard l(blocked_lock); if (is_blocked && (pending_size < PENDING_WRITES_WINDOW / 2)) { env->manager->io_complete(caller, req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_WRITE | RGWHTTPClient::HTTPCLIENT_IO_CONTROL)); is_blocked = false; } } void RGWStreamWriteHTTPResourceCRF::WriteDrainNotify::notify(uint64_t pending_size) { crf->write_drain_notify(pending_size); } int RGWStreamWriteHTTPResourceCRF::write(bufferlist& data, bool *io_pending) { reenter(&write_state) { while (!req->is_done()) { *io_pending = false; if (req->get_pending_send_size() >= PENDING_WRITES_WINDOW) { *io_pending = true; { lock_guard l(blocked_lock); is_blocked = true; /* it's ok to unlock here, even if io_complete() arrives before io_block(), it'll wakeup * correctly */ } yield caller->io_block(0, req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_WRITE | RGWHTTPClient::HTTPCLIENT_IO_CONTROL)); } yield req->add_send_data(data); } return req->get_status(); } return 0; } int RGWStreamWriteHTTPResourceCRF::drain_writes(bool *need_retry) { reenter(&drain_state) { *need_retry = true; yield req->finish_write(); *need_retry = !req->is_done(); while (!req->is_done()) { yield caller->io_block(0, req->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_CONTROL)); *need_retry = !req->is_done(); } map<string, string> headers; req->get_out_headers(&headers); handle_headers(headers); return req->get_req_retcode(); } return 0; } RGWStreamSpliceCR::RGWStreamSpliceCR(CephContext *_cct, RGWHTTPManager *_mgr, shared_ptr<RGWStreamReadHTTPResourceCRF>& _in_crf, shared_ptr<RGWStreamWriteHTTPResourceCRF>& _out_crf) : RGWCoroutine(_cct), cct(_cct), http_manager(_mgr), in_crf(_in_crf), out_crf(_out_crf) {} RGWStreamSpliceCR::~RGWStreamSpliceCR() { } int RGWStreamSpliceCR::operate(const DoutPrefixProvider *dpp) { reenter(this) { { int ret = in_crf->init(dpp); if (ret < 0) { return set_cr_error(ret); } } do { bl.clear(); do { yield { ret = in_crf->read(dpp, &bl, 4 * 1024 * 1024, &need_retry); if (ret < 0) { return set_cr_error(ret); } } if (retcode < 0) { ldout(cct, 20) << __func__ << ": in_crf->read() retcode=" << retcode << dendl; return set_cr_error(ret); } } while (need_retry); ldout(cct, 20) << "read " << bl.length() << " bytes" << dendl; if (!in_crf->has_attrs()) { assert (bl.length() == 0); continue; } if (!sent_attrs) { int ret = out_crf->init(); if (ret < 0) { return set_cr_error(ret); } out_crf->send_ready(dpp, in_crf->get_rest_obj()); ret = out_crf->send(); if (ret < 0) { return set_cr_error(ret); } sent_attrs = true; } if (bl.length() == 0 && in_crf->is_done()) { break; } total_read += bl.length(); do { yield { ldout(cct, 20) << "writing " << bl.length() << " bytes" << dendl; ret = out_crf->write(bl, &need_retry); if (ret < 0) { return set_cr_error(ret); } } if (retcode < 0) { ldout(cct, 20) << __func__ << ": out_crf->write() retcode=" << retcode << dendl; return set_cr_error(ret); } } while (need_retry); } while (true); do { yield { int ret = out_crf->drain_writes(&need_retry); if (ret < 0) { return set_cr_error(ret); } } } while (need_retry); return set_cr_done(); } return 0; }
8,860
24.173295
145
cc
null
ceph-main/src/rgw/rgw_cr_rest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <boost/intrusive_ptr.hpp> #include <mutex> #include "include/ceph_assert.h" // boost header clobbers our assert.h #include "rgw_coroutine.h" #include "rgw_rest_conn.h" struct rgw_rest_obj { rgw_obj_key key; uint64_t content_len; std::map<std::string, std::string> attrs; std::map<std::string, std::string> custom_attrs; RGWAccessControlPolicy acls; void init(const rgw_obj_key& _key) { key = _key; } }; class RGWReadRawRESTResourceCR : public RGWSimpleCoroutine { bufferlist *result; protected: RGWRESTConn *conn; RGWHTTPManager *http_manager; std::string path; param_vec_t params; param_vec_t extra_headers; public: boost::intrusive_ptr<RGWRESTReadResource> http_op; RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *params, bufferlist *_result) : RGWSimpleCoroutine(_cct), result(_result), conn(_conn), http_manager(_http_manager), path(_path), params(make_param_list(params)) {} RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *params) : RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager), path(_path), params(make_param_list(params)) {} RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *params, param_vec_t &hdrs) : RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager), path(_path), params(make_param_list(params)), extra_headers(hdrs) {} RGWReadRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *params, std::map <std::string, std::string> *hdrs) : RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager), path(_path), params(make_param_list(params)), extra_headers(make_param_list(hdrs)) {} ~RGWReadRawRESTResourceCR() override { request_cleanup(); } int send_request(const DoutPrefixProvider *dpp) override { auto op = boost::intrusive_ptr<RGWRESTReadResource>( new RGWRESTReadResource(conn, path, params, &extra_headers, http_manager)); init_new_io(op.get()); int ret = op->aio_read(dpp); if (ret < 0) { log_error() << "failed to send http operation: " << op->to_str() << " ret=" << ret << std::endl; op->put(); return ret; } std::swap(http_op, op); // store reference in http_op on success return 0; } virtual int wait_result() { return http_op->wait(result, null_yield); } int request_complete() override { int ret; ret = wait_result(); auto op = std::move(http_op); // release ref on return if (ret < 0) { error_stream << "http operation failed: " << op->to_str() << " status=" << op->get_http_status() << std::endl; op->put(); return ret; } op->put(); return 0; } void request_cleanup() override { if (http_op) { http_op->put(); http_op = NULL; } } }; template <class T> class RGWReadRESTResourceCR : public RGWReadRawRESTResourceCR { T *result; public: RGWReadRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *params, T *_result) : RGWReadRawRESTResourceCR(_cct, _conn, _http_manager, _path, params), result(_result) {} RGWReadRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *params, std::map <std::string, std::string> *hdrs, T *_result) : RGWReadRawRESTResourceCR(_cct, _conn, _http_manager, _path, params, hdrs), result(_result) {} int wait_result() override { return http_op->wait(result, null_yield); } }; template <class T, class E = int> class RGWSendRawRESTResourceCR: public RGWSimpleCoroutine { protected: RGWRESTConn *conn; RGWHTTPManager *http_manager; std::string method; std::string path; param_vec_t params; param_vec_t headers; std::map<std::string, std::string> *attrs; T *result; E *err_result; bufferlist input_bl; bool send_content_length=false; boost::intrusive_ptr<RGWRESTSendResource> http_op; public: RGWSendRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _method, const std::string& _path, rgw_http_param_pair *_params, std::map<std::string, std::string> *_attrs, bufferlist& _input, T *_result, bool _send_content_length, E *_err_result = nullptr) : RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager), method(_method), path(_path), params(make_param_list(_params)), headers(make_param_list(_attrs)), attrs(_attrs), result(_result), err_result(_err_result), input_bl(_input), send_content_length(_send_content_length) {} RGWSendRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _method, const std::string& _path, rgw_http_param_pair *_params, std::map<std::string, std::string> *_attrs, T *_result, E *_err_result = nullptr) : RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager), method(_method), path(_path), params(make_param_list(_params)), headers(make_param_list(_attrs)), attrs(_attrs), result(_result), err_result(_err_result) {} ~RGWSendRawRESTResourceCR() override { request_cleanup(); } int send_request(const DoutPrefixProvider *dpp) override { auto op = boost::intrusive_ptr<RGWRESTSendResource>( new RGWRESTSendResource(conn, method, path, params, &headers, http_manager)); init_new_io(op.get()); int ret = op->aio_send(dpp, input_bl); if (ret < 0) { ldpp_subdout(dpp, rgw, 0) << "ERROR: failed to send request" << dendl; op->put(); return ret; } std::swap(http_op, op); // store reference in http_op on success return 0; } int request_complete() override { int ret; if (result || err_result) { ret = http_op->wait(result, null_yield, err_result); } else { bufferlist bl; ret = http_op->wait(&bl, null_yield); } auto op = std::move(http_op); // release ref on return if (ret < 0) { error_stream << "http operation failed: " << op->to_str() << " status=" << op->get_http_status() << std::endl; lsubdout(cct, rgw, 5) << "failed to wait for op, ret=" << ret << ": " << op->to_str() << dendl; op->put(); return ret; } op->put(); return 0; } void request_cleanup() override { if (http_op) { http_op->put(); http_op = NULL; } } }; template <class S, class T, class E = int> class RGWSendRESTResourceCR : public RGWSendRawRESTResourceCR<T, E> { public: RGWSendRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _method, const std::string& _path, rgw_http_param_pair *_params, std::map<std::string, std::string> *_attrs, S& _input, T *_result, E *_err_result = nullptr) : RGWSendRawRESTResourceCR<T, E>(_cct, _conn, _http_manager, _method, _path, _params, _attrs, _result, _err_result) { JSONFormatter jf; encode_json("data", _input, &jf); std::stringstream ss; jf.flush(ss); //bufferlist bl; this->input_bl.append(ss.str()); } }; template <class S, class T, class E = int> class RGWPostRESTResourceCR : public RGWSendRESTResourceCR<S, T, E> { public: RGWPostRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *_params, S& _input, T *_result, E *_err_result = nullptr) : RGWSendRESTResourceCR<S, T, E>(_cct, _conn, _http_manager, "POST", _path, _params, nullptr, _input, _result, _err_result) {} }; template <class T, class E = int> class RGWPutRawRESTResourceCR: public RGWSendRawRESTResourceCR <T, E> { public: RGWPutRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *_params, bufferlist& _input, T *_result, E *_err_result = nullptr) : RGWSendRawRESTResourceCR<T, E>(_cct, _conn, _http_manager, "PUT", _path, _params, nullptr, _input, _result, true, _err_result) {} }; template <class T, class E = int> class RGWPostRawRESTResourceCR: public RGWSendRawRESTResourceCR <T, E> { public: RGWPostRawRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *_params, std::map<std::string, std::string> * _attrs, bufferlist& _input, T *_result, E *_err_result = nullptr) : RGWSendRawRESTResourceCR<T, E>(_cct, _conn, _http_manager, "POST", _path, _params, _attrs, _input, _result, true, _err_result) {} }; template <class S, class T, class E = int> class RGWPutRESTResourceCR : public RGWSendRESTResourceCR<S, T, E> { public: RGWPutRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *_params, S& _input, T *_result, E *_err_result = nullptr) : RGWSendRESTResourceCR<S, T, E>(_cct, _conn, _http_manager, "PUT", _path, _params, nullptr, _input, _result, _err_result) {} RGWPutRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *_params, std::map<std::string, std::string> *_attrs, S& _input, T *_result, E *_err_result = nullptr) : RGWSendRESTResourceCR<S, T, E>(_cct, _conn, _http_manager, "PUT", _path, _params, _attrs, _input, _result, _err_result) {} }; class RGWDeleteRESTResourceCR : public RGWSimpleCoroutine { RGWRESTConn *conn; RGWHTTPManager *http_manager; std::string path; param_vec_t params; boost::intrusive_ptr<RGWRESTDeleteResource> http_op; public: RGWDeleteRESTResourceCR(CephContext *_cct, RGWRESTConn *_conn, RGWHTTPManager *_http_manager, const std::string& _path, rgw_http_param_pair *_params) : RGWSimpleCoroutine(_cct), conn(_conn), http_manager(_http_manager), path(_path), params(make_param_list(_params)) {} ~RGWDeleteRESTResourceCR() override { request_cleanup(); } int send_request(const DoutPrefixProvider *dpp) override { auto op = boost::intrusive_ptr<RGWRESTDeleteResource>( new RGWRESTDeleteResource(conn, path, params, nullptr, http_manager)); init_new_io(op.get()); bufferlist bl; int ret = op->aio_send(dpp, bl); if (ret < 0) { ldpp_subdout(dpp, rgw, 0) << "ERROR: failed to send DELETE request" << dendl; op->put(); return ret; } std::swap(http_op, op); // store reference in http_op on success return 0; } int request_complete() override { int ret; bufferlist bl; ret = http_op->wait(&bl, null_yield); auto op = std::move(http_op); // release ref on return if (ret < 0) { error_stream << "http operation failed: " << op->to_str() << " status=" << op->get_http_status() << std::endl; lsubdout(cct, rgw, 5) << "failed to wait for op, ret=" << ret << ": " << op->to_str() << dendl; op->put(); return ret; } op->put(); return 0; } void request_cleanup() override { if (http_op) { http_op->put(); http_op = NULL; } } }; class RGWCRHTTPGetDataCB : public RGWHTTPStreamRWRequest::ReceiveCB { ceph::mutex lock = ceph::make_mutex("RGWCRHTTPGetDataCB"); RGWCoroutinesEnv *env; RGWCoroutine *cr; RGWHTTPStreamRWRequest *req; rgw_io_id io_id; bufferlist data; bufferlist extra_data; bool got_all_extra_data{false}; bool paused{false}; bool notified{false}; public: RGWCRHTTPGetDataCB(RGWCoroutinesEnv *_env, RGWCoroutine *_cr, RGWHTTPStreamRWRequest *_req); int handle_data(bufferlist& bl, bool *pause) override; void claim_data(bufferlist *dest, uint64_t max); bufferlist& get_extra_data() { return extra_data; } bool has_data() { return (data.length() > 0); } bool has_all_extra_data() { return got_all_extra_data; } }; class RGWStreamReadResourceCRF { protected: boost::asio::coroutine read_state; public: virtual int init(const DoutPrefixProvider *dpp) = 0; virtual int read(const DoutPrefixProvider *dpp, bufferlist *data, uint64_t max, bool *need_retry) = 0; /* reentrant */ virtual int decode_rest_obj(const DoutPrefixProvider *dpp, std::map<std::string, std::string>& headers, bufferlist& extra_data) = 0; virtual bool has_attrs() = 0; virtual void get_attrs(std::map<std::string, std::string> *attrs) = 0; virtual ~RGWStreamReadResourceCRF() = default; }; class RGWStreamWriteResourceCRF { protected: boost::asio::coroutine write_state; boost::asio::coroutine drain_state; public: virtual int init() = 0; virtual void send_ready(const DoutPrefixProvider *dpp, const rgw_rest_obj& rest_obj) = 0; virtual int send() = 0; virtual int write(bufferlist& data, bool *need_retry) = 0; /* reentrant */ virtual int drain_writes(bool *need_retry) = 0; /* reentrant */ virtual ~RGWStreamWriteResourceCRF() = default; }; class RGWStreamReadHTTPResourceCRF : public RGWStreamReadResourceCRF { CephContext *cct; RGWCoroutinesEnv *env; RGWCoroutine *caller; RGWHTTPManager *http_manager; RGWHTTPStreamRWRequest *req{nullptr}; std::optional<RGWCRHTTPGetDataCB> in_cb; bufferlist extra_data; bool got_attrs{false}; bool got_extra_data{false}; rgw_io_id io_read_mask; protected: rgw_rest_obj rest_obj; struct range_info { bool is_set{false}; uint64_t ofs; uint64_t size; } range; ceph::real_time mtime; std::string etag; public: RGWStreamReadHTTPResourceCRF(CephContext *_cct, RGWCoroutinesEnv *_env, RGWCoroutine *_caller, RGWHTTPManager *_http_manager, const rgw_obj_key& _src_key) : cct(_cct), env(_env), caller(_caller), http_manager(_http_manager) { rest_obj.init(_src_key); } ~RGWStreamReadHTTPResourceCRF(); int init(const DoutPrefixProvider *dpp) override; int read(const DoutPrefixProvider *dpp, bufferlist *data, uint64_t max, bool *need_retry) override; /* reentrant */ int decode_rest_obj(const DoutPrefixProvider *dpp, std::map<std::string, std::string>& headers, bufferlist& extra_data) override; bool has_attrs() override; void get_attrs(std::map<std::string, std::string> *attrs) override; bool is_done(); virtual bool need_extra_data() { return false; } void set_req(RGWHTTPStreamRWRequest *r) { req = r; } rgw_rest_obj& get_rest_obj() { return rest_obj; } void set_range(uint64_t ofs, uint64_t size) { range.is_set = true; range.ofs = ofs; range.size = size; } }; class RGWStreamWriteHTTPResourceCRF : public RGWStreamWriteResourceCRF { protected: RGWCoroutinesEnv *env; RGWCoroutine *caller; RGWHTTPManager *http_manager; using lock_guard = std::lock_guard<std::mutex>; std::mutex blocked_lock; bool is_blocked; RGWHTTPStreamRWRequest *req{nullptr}; struct multipart_info { bool is_multipart{false}; std::string upload_id; int part_num{0}; uint64_t part_size; } multipart; class WriteDrainNotify : public RGWWriteDrainCB { RGWStreamWriteHTTPResourceCRF *crf; public: explicit WriteDrainNotify(RGWStreamWriteHTTPResourceCRF *_crf) : crf(_crf) {} void notify(uint64_t pending_size) override; } write_drain_notify_cb; public: RGWStreamWriteHTTPResourceCRF(CephContext *_cct, RGWCoroutinesEnv *_env, RGWCoroutine *_caller, RGWHTTPManager *_http_manager) : env(_env), caller(_caller), http_manager(_http_manager), write_drain_notify_cb(this) {} virtual ~RGWStreamWriteHTTPResourceCRF(); int init() override { return 0; } void send_ready(const DoutPrefixProvider *dpp, const rgw_rest_obj& rest_obj) override; int send() override; int write(bufferlist& data, bool *need_retry) override; /* reentrant */ void write_drain_notify(uint64_t pending_size); int drain_writes(bool *need_retry) override; /* reentrant */ virtual void handle_headers(const std::map<std::string, std::string>& headers) {} void set_req(RGWHTTPStreamRWRequest *r) { req = r; } void set_multipart(const std::string& upload_id, int part_num, uint64_t part_size) { multipart.is_multipart = true; multipart.upload_id = upload_id; multipart.part_num = part_num; multipart.part_size = part_size; } }; class RGWStreamSpliceCR : public RGWCoroutine { CephContext *cct; RGWHTTPManager *http_manager; std::string url; std::shared_ptr<RGWStreamReadHTTPResourceCRF> in_crf; std::shared_ptr<RGWStreamWriteHTTPResourceCRF> out_crf; bufferlist bl; bool need_retry{false}; bool sent_attrs{false}; uint64_t total_read{0}; int ret{0}; public: RGWStreamSpliceCR(CephContext *_cct, RGWHTTPManager *_mgr, std::shared_ptr<RGWStreamReadHTTPResourceCRF>& _in_crf, std::shared_ptr<RGWStreamWriteHTTPResourceCRF>& _out_crf); ~RGWStreamSpliceCR(); int operate(const DoutPrefixProvider *dpp) override; };
19,624
32.20643
134
h
null
ceph-main/src/rgw/rgw_crypt.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /** * Crypto filters for Put/Post/Get operations. */ #include <string_view> #include <rgw/rgw_op.h> #include <rgw/rgw_crypt.h> #include <auth/Crypto.h> #include <rgw/rgw_b64.h> #include <rgw/rgw_rest_s3.h> #include "include/ceph_assert.h" #include "crypto/crypto_accel.h" #include "crypto/crypto_plugin.h" #include "rgw/rgw_kms.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/error/error.h" #include "rapidjson/error/en.h" #include <unicode/normalizer2.h> // libicu #include <openssl/evp.h> #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; using namespace rgw; template<typename M> class canonical_char_sorter { private: const DoutPrefixProvider *dpp; const icu::Normalizer2* normalizer; CephContext *cct; public: canonical_char_sorter(const DoutPrefixProvider *dpp, CephContext *cct) : dpp(dpp), cct(cct) { UErrorCode status = U_ZERO_ERROR; normalizer = icu::Normalizer2::getNFCInstance(status); if (U_FAILURE(status)) { ldpp_dout(this->dpp, -1) << "ERROR: can't get nfc instance, error = " << status << dendl; normalizer = 0; } } bool compare_helper (const M *, const M *); bool make_string_canonical(rapidjson::Value &, rapidjson::Document::AllocatorType&); }; template<typename M> bool canonical_char_sorter<M>::compare_helper (const M*a, const M*b) { UErrorCode status = U_ZERO_ERROR; const std::string as{a->name.GetString(), a->name.GetStringLength()}, bs{b->name.GetString(), b->name.GetStringLength()}; icu::UnicodeString aw{icu::UnicodeString::fromUTF8(as)}, bw{icu::UnicodeString::fromUTF8(bs)}; int32_t afl{ aw.countChar32()}, bfl{bw.countChar32()}; std::u32string af, bf; af.resize(afl); bf.resize(bfl); auto *astr{af.c_str()}, *bstr{bf.c_str()}; aw.toUTF32((int32_t*)astr, afl, status); bw.toUTF32((int32_t*)bstr, bfl, status); bool r{af < bf}; return r; } template<typename M> bool canonical_char_sorter<M>::make_string_canonical (rapidjson::Value &v, rapidjson::Document::AllocatorType&a) { UErrorCode status = U_ZERO_ERROR; const std::string as{v.GetString(), v.GetStringLength()}; if (!normalizer) return false; const icu::UnicodeString aw{icu::UnicodeString::fromUTF8(as)}; icu::UnicodeString an{normalizer->normalize(aw, status)}; if (U_FAILURE(status)) { ldpp_dout(this->dpp, 5) << "conversion error; code=" << status << " on string " << as << dendl; return false; } std::string ans; an.toUTF8String(ans); v.SetString(ans.c_str(), ans.length(), a); return true; } typedef rapidjson::GenericMember<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<> > MyMember; template<typename H> bool sort_and_write(rapidjson::Value &d, H &writer, canonical_char_sorter<MyMember>& ccs) { bool r; switch(d.GetType()) { case rapidjson::kObjectType: { struct comparer { canonical_char_sorter<MyMember> &r; comparer(canonical_char_sorter<MyMember> &r) : r(r) {}; bool operator()(const MyMember*a, const MyMember*b) { return r.compare_helper(a,b); } } cmp_functor{ccs}; if (!(r = writer.StartObject())) break; std::vector<MyMember*> q; for (auto &m: d.GetObject()) q.push_back(&m); std::sort(q.begin(), q.end(), cmp_functor); for (auto m: q) { assert(m->name.IsString()); if (!(r = writer.Key(m->name.GetString(), m->name.GetStringLength()))) goto Done; if (!(r = sort_and_write(m->value, writer, ccs))) goto Done; } r = writer.EndObject(); break; } case rapidjson::kArrayType: if (!(r = writer.StartArray())) break; for (auto &v: d.GetArray()) { if (!(r = sort_and_write(v, writer, ccs))) goto Done; } r = writer.EndArray(); break; default: r = d.Accept(writer); break; } Done: return r; } enum struct mec_option { empty = 0, number_ok = 1 }; enum struct mec_error { success = 0, conversion, number }; mec_error make_everything_canonical(rapidjson::Value &d, rapidjson::Document::AllocatorType&a, canonical_char_sorter<MyMember>& ccs, mec_option f = mec_option::empty ) { mec_error r; switch(d.GetType()) { case rapidjson::kObjectType: for (auto &m: d.GetObject()) { assert(m.name.IsString()); if (!ccs.make_string_canonical(m.name, a)) { r = mec_error::conversion; goto Error; } if ((r = make_everything_canonical(m.value, a, ccs, f)) != mec_error::success) goto Error; } break; case rapidjson::kArrayType: for (auto &v: d.GetArray()) { if ((r = make_everything_canonical(v, a, ccs, f)) != mec_error::success) goto Error; } break; case rapidjson::kStringType: if (!ccs.make_string_canonical(d, a)) { r = mec_error::conversion; goto Error; } break; case rapidjson::kNumberType: if (static_cast<int>(f) & static_cast<int>(mec_option::number_ok)) break; r = mec_error::number; goto Error; default: break; } r = mec_error::success; Error: return r; } bool add_object_to_context(rgw_obj &obj, rapidjson::Document &d) { ARN a{obj}; const char aws_s3_arn[] { "aws:s3:arn" }; std::string as{a.to_string()}; rapidjson::Document::AllocatorType &allocator { d.GetAllocator() }; rapidjson::Value name, val; if (!d.IsObject()) return false; if (d.HasMember(aws_s3_arn)) return true; val.SetString(as.c_str(), as.length(), allocator); name.SetString(aws_s3_arn, sizeof aws_s3_arn - 1, allocator); d.AddMember(name, val, allocator); return true; } static inline const std::string & get_tenant_or_id(req_state *s) { const std::string &tenant{ s->user->get_tenant() }; if (!tenant.empty()) return tenant; return s->user->get_id().id; } int make_canonical_context(req_state *s, std::string_view &context, std::string &cooked_context) { rapidjson::Document d; bool b = false; mec_option options { //mec_option::number_ok : SEE BOTTOM OF FILE mec_option::empty }; rgw_obj obj; std::ostringstream oss; canonical_char_sorter<MyMember> ccs{s, s->cct}; obj.bucket.tenant = get_tenant_or_id(s); obj.bucket.name = s->bucket->get_name(); obj.key.name = s->object->get_name(); std::string iline; rapidjson::Document::AllocatorType &allocator { d.GetAllocator() }; try { iline = rgw::from_base64(context); } catch (const std::exception& e) { oss << "bad context: " << e.what(); s->err.message = oss.str(); return -ERR_INVALID_REQUEST; } rapidjson::StringStream isw(iline.c_str()); if (!iline.length()) d.SetObject(); // else if (qflag) SEE BOTTOM OF FILE // d.ParseStream<rapidjson::kParseNumbersAsStringsFlag>(isw); else d.ParseStream<rapidjson::kParseFullPrecisionFlag>(isw); if (isw.Tell() != iline.length()) { oss << "bad context: did not consume all of input: @ " << isw.Tell(); s->err.message = oss.str(); return -ERR_INVALID_REQUEST; } if (d.HasParseError()) { oss << "bad context: parse error: @ " << d.GetErrorOffset() << " " << rapidjson::GetParseError_En(d.GetParseError()); s->err.message = oss.str(); return -ERR_INVALID_REQUEST; } rapidjson::StringBuffer buf; rapidjson::Writer<rapidjson::StringBuffer> writer(buf); if (!add_object_to_context(obj, d)) { ldpp_dout(s, -1) << "ERROR: can't add default value to context" << dendl; s->err.message = "context: internal error adding defaults"; return -ERR_INVALID_REQUEST; } b = make_everything_canonical(d, allocator, ccs, options) == mec_error::success; if (!b) { ldpp_dout(s, -1) << "ERROR: can't make canonical json <" << context << ">" << dendl; s->err.message = "context: can't make canonical"; return -ERR_INVALID_REQUEST; } b = sort_and_write(d, writer, ccs); if (!b) { ldpp_dout(s, 5) << "format error <" << context << ">: partial.results=" << buf.GetString() << dendl; s->err.message = "unable to reformat json"; return -ERR_INVALID_REQUEST; } cooked_context = rgw::to_base64(buf.GetString()); return 0; } CryptoAccelRef get_crypto_accel(const DoutPrefixProvider* dpp, CephContext *cct, const size_t chunk_size, const size_t max_requests) { CryptoAccelRef ca_impl = nullptr; stringstream ss; PluginRegistry *reg = cct->get_plugin_registry(); string crypto_accel_type = cct->_conf->plugin_crypto_accelerator; CryptoPlugin *factory = dynamic_cast<CryptoPlugin*>(reg->get_with_load("crypto", crypto_accel_type)); if (factory == nullptr) { ldpp_dout(dpp, -1) << __func__ << " cannot load crypto accelerator of type " << crypto_accel_type << dendl; return nullptr; } int err = factory->factory(&ca_impl, &ss, chunk_size, max_requests); if (err) { ldpp_dout(dpp, -1) << __func__ << " factory return error " << err << " with description: " << ss.str() << dendl; } return ca_impl; } template <std::size_t KeySizeV, std::size_t IvSizeV> static inline bool evp_sym_transform(const DoutPrefixProvider* dpp, CephContext* const cct, const EVP_CIPHER* const type, unsigned char* const out, const unsigned char* const in, const size_t size, const unsigned char* const iv, const unsigned char* const key, const bool encrypt) { using pctx_t = \ std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>; pctx_t pctx{ EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free }; if (!pctx) { return false; } if (1 != EVP_CipherInit_ex(pctx.get(), type, nullptr, nullptr, nullptr, encrypt)) { ldpp_dout(dpp, 5) << "EVP: failed to 1st initialization stage" << dendl; return false; } // we want to support ciphers that don't use IV at all like AES-256-ECB if constexpr (static_cast<bool>(IvSizeV)) { ceph_assert(EVP_CIPHER_CTX_iv_length(pctx.get()) == IvSizeV); ceph_assert(EVP_CIPHER_CTX_block_size(pctx.get()) == IvSizeV); } ceph_assert(EVP_CIPHER_CTX_key_length(pctx.get()) == KeySizeV); if (1 != EVP_CipherInit_ex(pctx.get(), nullptr, nullptr, key, iv, encrypt)) { ldpp_dout(dpp, 5) << "EVP: failed to 2nd initialization stage" << dendl; return false; } // disable padding if (1 != EVP_CIPHER_CTX_set_padding(pctx.get(), 0)) { ldpp_dout(dpp, 5) << "EVP: cannot disable PKCS padding" << dendl; return false; } // operate! int written = 0; ceph_assert(size <= static_cast<size_t>(std::numeric_limits<int>::max())); if (1 != EVP_CipherUpdate(pctx.get(), out, &written, in, size)) { ldpp_dout(dpp, 5) << "EVP: EVP_CipherUpdate failed" << dendl; return false; } int finally_written = 0; static_assert(sizeof(*out) == 1); if (1 != EVP_CipherFinal_ex(pctx.get(), out + written, &finally_written)) { ldpp_dout(dpp, 5) << "EVP: EVP_CipherFinal_ex failed" << dendl; return false; } // padding is disabled so EVP_CipherFinal_ex should not append anything ceph_assert(finally_written == 0); return (written + finally_written) == static_cast<int>(size); } /** * Encryption in CBC mode. Chunked to 4K blocks. Offset is used as IV for each 4K block. * * * * A. Encryption * 1. Input is split to 4K chunks + remainder in one, smaller chunk * 2. Each full chunk is encrypted separately with CBC chained mode, with initial IV derived from offset * 3. Last chunk is 16*m + n. * 4. 16*m bytes are encrypted with CBC chained mode, with initial IV derived from offset * 5. Last n bytes are xor-ed with pattern obtained by CBC encryption of * last encrypted 16 byte block <16m-16, 16m-15) with IV = {0}. * 6. (Special case) If m == 0 then last n bytes are xor-ed with pattern * obtained by CBC encryption of {0} with IV derived from offset * * B. Decryption * 1. Input is split to 4K chunks + remainder in one, smaller chunk * 2. Each full chunk is decrypted separately with CBC chained mode, with initial IV derived from offset * 3. Last chunk is 16*m + n. * 4. 16*m bytes are decrypted with CBC chained mode, with initial IV derived from offset * 5. Last n bytes are xor-ed with pattern obtained by CBC ENCRYPTION of * last (still encrypted) 16 byte block <16m-16,16m-15) with IV = {0} * 6. (Special case) If m == 0 then last n bytes are xor-ed with pattern * obtained by CBC ENCRYPTION of {0} with IV derived from offset */ class AES_256_CBC : public BlockCrypt { public: static const size_t AES_256_KEYSIZE = 256 / 8; static const size_t AES_256_IVSIZE = 128 / 8; static const size_t CHUNK_SIZE = 4096; static const size_t QAT_MIN_SIZE = 65536; const DoutPrefixProvider* dpp; private: static const uint8_t IV[AES_256_IVSIZE]; CephContext* cct; uint8_t key[AES_256_KEYSIZE]; public: explicit AES_256_CBC(const DoutPrefixProvider* dpp, CephContext* cct): dpp(dpp), cct(cct) { } ~AES_256_CBC() { ::ceph::crypto::zeroize_for_security(key, AES_256_KEYSIZE); } bool set_key(const uint8_t* _key, size_t key_size) { if (key_size != AES_256_KEYSIZE) { return false; } memcpy(key, _key, AES_256_KEYSIZE); return true; } size_t get_block_size() { return CHUNK_SIZE; } bool cbc_transform(unsigned char* out, const unsigned char* in, const size_t size, const unsigned char (&iv)[AES_256_IVSIZE], const unsigned char (&key)[AES_256_KEYSIZE], bool encrypt) { return evp_sym_transform<AES_256_KEYSIZE, AES_256_IVSIZE>( dpp, cct, EVP_aes_256_cbc(), out, in, size, iv, key, encrypt); } bool cbc_transform(unsigned char* out, const unsigned char* in, size_t size, off_t stream_offset, const unsigned char (&key)[AES_256_KEYSIZE], bool encrypt, optional_yield y) { static std::atomic<bool> failed_to_get_crypto(false); CryptoAccelRef crypto_accel; if (! failed_to_get_crypto.load()) { static size_t max_requests = g_ceph_context->_conf->rgw_thread_pool_size; crypto_accel = get_crypto_accel(this->dpp, cct, CHUNK_SIZE, max_requests); if (!crypto_accel) failed_to_get_crypto = true; } bool result = false; static std::string accelerator = cct->_conf->plugin_crypto_accelerator; if (accelerator == "crypto_qat" && crypto_accel != nullptr && size >= QAT_MIN_SIZE) { // now, batch mode is only for QAT plugin size_t iv_num = size / CHUNK_SIZE; if (size % CHUNK_SIZE) ++iv_num; auto iv = new unsigned char[iv_num][AES_256_IVSIZE]; for (size_t offset = 0, i = 0; offset < size; offset += CHUNK_SIZE, i++) { prepare_iv(iv[i], stream_offset + offset); } if (encrypt) { result = crypto_accel->cbc_encrypt_batch(out, in, size, iv, key, y); } else { result = crypto_accel->cbc_decrypt_batch(out, in, size, iv, key, y); } delete[] iv; } if (result == false) { // If QAT don't have free instance, we can fall back to this result = true; unsigned char iv[AES_256_IVSIZE]; for (size_t offset = 0; result && (offset < size); offset += CHUNK_SIZE) { size_t process_size = offset + CHUNK_SIZE <= size ? CHUNK_SIZE : size - offset; prepare_iv(iv, stream_offset + offset); if (crypto_accel != nullptr && accelerator != "crypto_qat") { if (encrypt) { result = crypto_accel->cbc_encrypt(out + offset, in + offset, process_size, iv, key, y); } else { result = crypto_accel->cbc_decrypt(out + offset, in + offset, process_size, iv, key, y); } } else { result = cbc_transform( out + offset, in + offset, process_size, iv, key, encrypt); } } } return result; } bool encrypt(bufferlist& input, off_t in_ofs, size_t size, bufferlist& output, off_t stream_offset, optional_yield y) { bool result = false; size_t aligned_size = size / AES_256_IVSIZE * AES_256_IVSIZE; size_t unaligned_rest_size = size - aligned_size; output.clear(); buffer::ptr buf(aligned_size + AES_256_IVSIZE); unsigned char* buf_raw = reinterpret_cast<unsigned char*>(buf.c_str()); const unsigned char* input_raw = reinterpret_cast<const unsigned char*>(input.c_str()); /* encrypt main bulk of data */ result = cbc_transform(buf_raw, input_raw + in_ofs, aligned_size, stream_offset, key, true, y); if (result && (unaligned_rest_size > 0)) { /* remainder to encrypt */ if (aligned_size % CHUNK_SIZE > 0) { /* use last chunk for unaligned part */ unsigned char iv[AES_256_IVSIZE] = {0}; result = cbc_transform(buf_raw + aligned_size, buf_raw + aligned_size - AES_256_IVSIZE, AES_256_IVSIZE, iv, key, true); } else { /* 0 full blocks in current chunk, use IV as base for unaligned part */ unsigned char iv[AES_256_IVSIZE] = {0}; unsigned char data[AES_256_IVSIZE]; prepare_iv(data, stream_offset + aligned_size); result = cbc_transform(buf_raw + aligned_size, data, AES_256_IVSIZE, iv, key, true); } if (result) { for(size_t i = aligned_size; i < size; i++) { *(buf_raw + i) ^= *(input_raw + in_ofs + i); } } } if (result) { ldpp_dout(this->dpp, 25) << "Encrypted " << size << " bytes"<< dendl; buf.set_length(size); output.append(buf); } else { ldpp_dout(this->dpp, 5) << "Failed to encrypt" << dendl; } return result; } bool decrypt(bufferlist& input, off_t in_ofs, size_t size, bufferlist& output, off_t stream_offset, optional_yield y) { bool result = false; size_t aligned_size = size / AES_256_IVSIZE * AES_256_IVSIZE; size_t unaligned_rest_size = size - aligned_size; output.clear(); buffer::ptr buf(aligned_size + AES_256_IVSIZE); unsigned char* buf_raw = reinterpret_cast<unsigned char*>(buf.c_str()); unsigned char* input_raw = reinterpret_cast<unsigned char*>(input.c_str()); /* decrypt main bulk of data */ result = cbc_transform(buf_raw, input_raw + in_ofs, aligned_size, stream_offset, key, false, y); if (result && unaligned_rest_size > 0) { /* remainder to decrypt */ if (aligned_size % CHUNK_SIZE > 0) { /*use last chunk for unaligned part*/ unsigned char iv[AES_256_IVSIZE] = {0}; result = cbc_transform(buf_raw + aligned_size, input_raw + in_ofs + aligned_size - AES_256_IVSIZE, AES_256_IVSIZE, iv, key, true); } else { /* 0 full blocks in current chunk, use IV as base for unaligned part */ unsigned char iv[AES_256_IVSIZE] = {0}; unsigned char data[AES_256_IVSIZE]; prepare_iv(data, stream_offset + aligned_size); result = cbc_transform(buf_raw + aligned_size, data, AES_256_IVSIZE, iv, key, true); } if (result) { for(size_t i = aligned_size; i < size; i++) { *(buf_raw + i) ^= *(input_raw + in_ofs + i); } } } if (result) { ldpp_dout(this->dpp, 25) << "Decrypted " << size << " bytes"<< dendl; buf.set_length(size); output.append(buf); } else { ldpp_dout(this->dpp, 5) << "Failed to decrypt" << dendl; } return result; } void prepare_iv(unsigned char (&iv)[AES_256_IVSIZE], off_t offset) { off_t index = offset / AES_256_IVSIZE; off_t i = AES_256_IVSIZE - 1; unsigned int val; unsigned int carry = 0; while (i>=0) { val = (index & 0xff) + IV[i] + carry; iv[i] = val; carry = val >> 8; index = index >> 8; i--; } } }; std::unique_ptr<BlockCrypt> AES_256_CBC_create(const DoutPrefixProvider* dpp, CephContext* cct, const uint8_t* key, size_t len) { auto cbc = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(dpp, cct)); cbc->set_key(key, AES_256_KEYSIZE); return cbc; } const uint8_t AES_256_CBC::IV[AES_256_CBC::AES_256_IVSIZE] = { 'a', 'e', 's', '2', '5', '6', 'i', 'v', '_', 'c', 't', 'r', '1', '3', '3', '7' }; bool AES_256_ECB_encrypt(const DoutPrefixProvider* dpp, CephContext* cct, const uint8_t* key, size_t key_size, const uint8_t* data_in, uint8_t* data_out, size_t data_size) { if (key_size == AES_256_KEYSIZE) { return evp_sym_transform<AES_256_KEYSIZE, 0 /* no IV in ECB */>( dpp, cct, EVP_aes_256_ecb(), data_out, data_in, data_size, nullptr /* no IV in ECB */, key, true /* encrypt */); } else { ldpp_dout(dpp, 5) << "Key size must be 256 bits long" << dendl; return false; } } RGWGetObj_BlockDecrypt::RGWGetObj_BlockDecrypt(const DoutPrefixProvider *dpp, CephContext* cct, RGWGetObj_Filter* next, std::unique_ptr<BlockCrypt> crypt, optional_yield y) : RGWGetObj_Filter(next), dpp(dpp), cct(cct), crypt(std::move(crypt)), enc_begin_skip(0), ofs(0), end(0), cache(), y(y) { block_size = this->crypt->get_block_size(); } RGWGetObj_BlockDecrypt::~RGWGetObj_BlockDecrypt() { } int RGWGetObj_BlockDecrypt::read_manifest(const DoutPrefixProvider *dpp, bufferlist& manifest_bl) { parts_len.clear(); RGWObjManifest manifest; if (manifest_bl.length()) { auto miter = manifest_bl.cbegin(); try { decode(manifest, miter); } catch (buffer::error& err) { ldpp_dout(dpp, 0) << "ERROR: couldn't decode manifest" << dendl; return -EIO; } RGWObjManifest::obj_iterator mi; for (mi = manifest.obj_begin(dpp); mi != manifest.obj_end(dpp); ++mi) { if (mi.get_cur_stripe() == 0) { parts_len.push_back(0); } parts_len.back() += mi.get_stripe_size(); } if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) { for (size_t i = 0; i<parts_len.size(); i++) { ldpp_dout(dpp, 20) << "Manifest part " << i << ", size=" << parts_len[i] << dendl; } } } return 0; } int RGWGetObj_BlockDecrypt::fixup_range(off_t& bl_ofs, off_t& bl_end) { off_t inp_ofs = bl_ofs; off_t inp_end = bl_end; if (parts_len.size() > 0) { off_t in_ofs = bl_ofs; off_t in_end = bl_end; size_t i = 0; while (i<parts_len.size() && (in_ofs >= (off_t)parts_len[i])) { in_ofs -= parts_len[i]; i++; } //in_ofs is inside block i size_t j = 0; while (j<(parts_len.size() - 1) && (in_end >= (off_t)parts_len[j])) { in_end -= parts_len[j]; j++; } //in_end is inside part j, OR j is the last part size_t rounded_end = ( in_end & ~(block_size - 1) ) + (block_size - 1); if (rounded_end > parts_len[j]) { rounded_end = parts_len[j] - 1; } enc_begin_skip = in_ofs & (block_size - 1); ofs = bl_ofs - enc_begin_skip; end = bl_end; bl_end += rounded_end - in_end; bl_ofs = std::min(bl_ofs - enc_begin_skip, bl_end); } else { enc_begin_skip = bl_ofs & (block_size - 1); ofs = bl_ofs & ~(block_size - 1); end = bl_end; bl_ofs = bl_ofs & ~(block_size - 1); bl_end = ( bl_end & ~(block_size - 1) ) + (block_size - 1); } ldpp_dout(this->dpp, 20) << "fixup_range [" << inp_ofs << "," << inp_end << "] => [" << bl_ofs << "," << bl_end << "]" << dendl; return 0; } int RGWGetObj_BlockDecrypt::process(bufferlist& in, size_t part_ofs, size_t size) { bufferlist data; if (!crypt->decrypt(in, 0, size, data, part_ofs, y)) { return -ERR_INTERNAL_ERROR; } off_t send_size = size - enc_begin_skip; if (ofs + enc_begin_skip + send_size > end + 1) { send_size = end + 1 - ofs - enc_begin_skip; } int res = next->handle_data(data, enc_begin_skip, send_size); enc_begin_skip = 0; ofs += size; in.splice(0, size); return res; } int RGWGetObj_BlockDecrypt::handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { ldpp_dout(this->dpp, 25) << "Decrypt " << bl_len << " bytes" << dendl; bl.begin(bl_ofs).copy(bl_len, cache); int res = 0; size_t part_ofs = ofs; for (size_t part : parts_len) { if (part_ofs >= part) { part_ofs -= part; } else if (part_ofs + cache.length() >= part) { // flush data up to part boundaries, aligned or not res = process(cache, part_ofs, part - part_ofs); if (res < 0) { return res; } part_ofs = 0; } else { break; } } // write up to block boundaries, aligned only off_t aligned_size = cache.length() & ~(block_size - 1); if (aligned_size > 0) { res = process(cache, part_ofs, aligned_size); } return res; } /** * flush remainder of data to output */ int RGWGetObj_BlockDecrypt::flush() { ldpp_dout(this->dpp, 25) << "Decrypt flushing " << cache.length() << " bytes" << dendl; int res = 0; size_t part_ofs = ofs; for (size_t part : parts_len) { if (part_ofs >= part) { part_ofs -= part; } else if (part_ofs + cache.length() >= part) { // flush data up to part boundaries, aligned or not res = process(cache, part_ofs, part - part_ofs); if (res < 0) { return res; } part_ofs = 0; } else { break; } } // flush up to block boundaries, aligned or not if (cache.length() > 0) { res = process(cache, part_ofs, cache.length()); } return res; } RGWPutObj_BlockEncrypt::RGWPutObj_BlockEncrypt(const DoutPrefixProvider *dpp, CephContext* cct, rgw::sal::DataProcessor *next, std::unique_ptr<BlockCrypt> crypt, optional_yield y) : Pipe(next), dpp(dpp), cct(cct), crypt(std::move(crypt)), block_size(this->crypt->get_block_size()), y(y) { } int RGWPutObj_BlockEncrypt::process(bufferlist&& data, uint64_t logical_offset) { ldpp_dout(this->dpp, 25) << "Encrypt " << data.length() << " bytes" << dendl; // adjust logical offset to beginning of cached data ceph_assert(logical_offset >= cache.length()); logical_offset -= cache.length(); const bool flush = (data.length() == 0); cache.claim_append(data); uint64_t proc_size = cache.length() & ~(block_size - 1); if (flush) { proc_size = cache.length(); } if (proc_size > 0) { bufferlist in, out; cache.splice(0, proc_size, &in); if (!crypt->encrypt(in, 0, proc_size, out, logical_offset, y)) { return -ERR_INTERNAL_ERROR; } int r = Pipe::process(std::move(out), logical_offset); logical_offset += proc_size; if (r < 0) return r; } if (flush) { /*replicate 0-sized handle_data*/ return Pipe::process({}, logical_offset); } return 0; } std::string create_random_key_selector(CephContext * const cct) { char random[AES_256_KEYSIZE]; cct->random()->get_bytes(&random[0], sizeof(random)); return std::string(random, sizeof(random)); } typedef enum { X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM=0, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, X_AMZ_SERVER_SIDE_ENCRYPTION, X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID, X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT, X_AMZ_SERVER_SIDE_ENCRYPTION_LAST } crypt_option_e; struct crypt_option_names { const std::string post_part_name; }; static const crypt_option_names crypt_options[] = { { "x-amz-server-side-encryption-customer-algorithm"}, { "x-amz-server-side-encryption-customer-key"}, { "x-amz-server-side-encryption-customer-key-md5"}, { "x-amz-server-side-encryption"}, { "x-amz-server-side-encryption-aws-kms-key-id"}, { "x-amz-server-side-encryption-context"}, }; struct CryptAttributes { meta_map_t &x_meta_map; CryptAttributes(req_state *s) : x_meta_map(s->info.crypt_attribute_map) { } std::string_view get(crypt_option_e option) { static_assert( X_AMZ_SERVER_SIDE_ENCRYPTION_LAST == sizeof(crypt_options)/sizeof(*crypt_options), "Missing items in crypt_options"); auto hdr { x_meta_map.find(crypt_options[option].post_part_name) }; if (hdr != x_meta_map.end()) { return std::string_view(hdr->second); } else { return std::string_view(); } } }; std::string fetch_bucket_key_id(req_state *s) { auto kek_iter = s->bucket_attrs.find(RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID); if (kek_iter == s->bucket_attrs.end()) return std::string(); std::string a_key { kek_iter->second.to_str() }; // early code appends a nul; pretend that didn't happen auto l { a_key.length() }; if (l > 0 && a_key[l-1] == '\0') { a_key.resize(--l); } return a_key; } const std::string cant_expand_key{ "\uFFFD" }; std::string expand_key_name(req_state *s, const std::string_view&t) { std::string r; size_t i, j; for (i = 0;;) { i = t.find('%', (j = i)); if (i != j) { if (i == std::string_view::npos) r.append( t.substr(j) ); else r.append( t.substr(j, i-j) ); } if (i == std::string_view::npos) { break; } if (t[i+1] == '%') { r.append("%"); i += 2; continue; } if (t.compare(i+1, 9, "bucket_id") == 0) { r.append(s->bucket->get_marker()); i += 10; continue; } if (t.compare(i+1, 8, "owner_id") == 0) { r.append(s->bucket->get_info().owner.id); i += 9; continue; } return cant_expand_key; } return r; } static int get_sse_s3_bucket_key(req_state *s, std::string &key_id) { int res; std::string saved_key; key_id = expand_key_name(s, s->cct->_conf->rgw_crypt_sse_s3_key_template); if (key_id == cant_expand_key) { ldpp_dout(s, 5) << "ERROR: unable to expand key_id " << s->cct->_conf->rgw_crypt_sse_s3_key_template << " on bucket" << dendl; s->err.message = "Server side error - unable to expand key_id"; return -EINVAL; } saved_key = fetch_bucket_key_id(s); if (saved_key != "") { ldpp_dout(s, 5) << "Found KEK ID: " << key_id << dendl; } if (saved_key != key_id) { res = create_sse_s3_bucket_key(s, s->cct, key_id); if (res != 0) { return res; } bufferlist key_id_bl; key_id_bl.append(key_id.c_str(), key_id.length()); for (int count = 0; count < 15; ++count) { rgw::sal::Attrs attrs = s->bucket->get_attrs(); attrs[RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID] = key_id_bl; res = s->bucket->merge_and_store_attrs(s, attrs, s->yield); if (res != -ECANCELED) { break; } res = s->bucket->try_refresh_info(s, nullptr, s->yield); if (res != 0) { break; } } if (res != 0) { ldpp_dout(s, 5) << "ERROR: unable to save new key_id on bucket" << dendl; s->err.message = "Server side error - unable to save key_id"; return res; } } return 0; } int rgw_s3_prepare_encrypt(req_state* s, std::map<std::string, ceph::bufferlist>& attrs, std::unique_ptr<BlockCrypt>* block_crypt, std::map<std::string, std::string>& crypt_http_responses) { int res = 0; CryptAttributes crypt_attributes { s }; crypt_http_responses.clear(); { std::string_view req_sse_ca = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM); if (! req_sse_ca.empty()) { if (req_sse_ca != "AES256") { ldpp_dout(s, 5) << "ERROR: Invalid value for header " << "x-amz-server-side-encryption-customer-algorithm" << dendl; s->err.message = "The requested encryption algorithm is not valid, must be AES256."; return -ERR_INVALID_ENCRYPTION_ALGORITHM; } if (s->cct->_conf->rgw_crypt_require_ssl && !rgw_transport_is_secure(s->cct, *s->info.env)) { ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl; return -ERR_INVALID_REQUEST; } std::string key_bin; try { key_bin = from_base64( crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY) ); } catch (...) { ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_encrypt invalid encryption " << "key which contains character that is not base64 encoded." << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key."; return -EINVAL; } if (key_bin.size() != AES_256_CBC::AES_256_KEYSIZE) { ldpp_dout(s, 5) << "ERROR: invalid encryption key size" << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key."; return -EINVAL; } std::string_view keymd5 = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5); std::string keymd5_bin; try { keymd5_bin = from_base64(keymd5); } catch (...) { ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_encrypt invalid encryption key " << "md5 which contains character that is not base64 encoded." << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key md5."; return -EINVAL; } if (keymd5_bin.size() != CEPH_CRYPTO_MD5_DIGESTSIZE) { ldpp_dout(s, 5) << "ERROR: Invalid key md5 size" << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key md5."; return -EINVAL; } MD5 key_hash; // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes key_hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); unsigned char key_hash_res[CEPH_CRYPTO_MD5_DIGESTSIZE]; key_hash.Update(reinterpret_cast<const unsigned char*>(key_bin.c_str()), key_bin.size()); key_hash.Final(key_hash_res); if (memcmp(key_hash_res, keymd5_bin.c_str(), CEPH_CRYPTO_MD5_DIGESTSIZE) != 0) { ldpp_dout(s, 5) << "ERROR: Invalid key md5 hash" << dendl; s->err.message = "The calculated MD5 hash of the key did not match the hash that was provided."; return -EINVAL; } set_attr(attrs, RGW_ATTR_CRYPT_MODE, "SSE-C-AES256"); set_attr(attrs, RGW_ATTR_CRYPT_KEYMD5, keymd5_bin); if (block_crypt) { auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(key_bin.c_str()), AES_256_KEYSIZE); *block_crypt = std::move(aes); } crypt_http_responses["x-amz-server-side-encryption-customer-algorithm"] = "AES256"; crypt_http_responses["x-amz-server-side-encryption-customer-key-MD5"] = std::string(keymd5); return 0; } else { std::string_view customer_key = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY); if (!customer_key.empty()) { ldpp_dout(s, 5) << "ERROR: SSE-C encryption request is missing the header " << "x-amz-server-side-encryption-customer-algorithm" << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide a valid encryption algorithm."; return -EINVAL; } std::string_view customer_key_md5 = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5); if (!customer_key_md5.empty()) { ldpp_dout(s, 5) << "ERROR: SSE-C encryption request is missing the header " << "x-amz-server-side-encryption-customer-algorithm" << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide a valid encryption algorithm."; return -EINVAL; } } /* AMAZON server side encryption with KMS (key management service) */ std::string_view req_sse = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION); if (! req_sse.empty()) { if (s->cct->_conf->rgw_crypt_require_ssl && !rgw_transport_is_secure(s->cct, *s->info.env)) { ldpp_dout(s, 5) << "ERROR: insecure request, rgw_crypt_require_ssl is set" << dendl; return -ERR_INVALID_REQUEST; } if (req_sse == "aws:kms") { std::string_view context = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT); std::string cooked_context; if ((res = make_canonical_context(s, context, cooked_context))) return res; std::string_view key_id = crypt_attributes.get(X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID); if (key_id.empty()) { ldpp_dout(s, 5) << "ERROR: not provide a valid key id" << dendl; s->err.message = "Server Side Encryption with KMS managed key requires " "HTTP header x-amz-server-side-encryption-aws-kms-key-id"; return -EINVAL; } /* try to retrieve actual key */ std::string key_selector = create_random_key_selector(s->cct); set_attr(attrs, RGW_ATTR_CRYPT_MODE, "SSE-KMS"); set_attr(attrs, RGW_ATTR_CRYPT_KEYID, key_id); set_attr(attrs, RGW_ATTR_CRYPT_KEYSEL, key_selector); set_attr(attrs, RGW_ATTR_CRYPT_CONTEXT, cooked_context); std::string actual_key; res = make_actual_key_from_kms(s, s->cct, attrs, actual_key); if (res != 0) { ldpp_dout(s, 5) << "ERROR: failed to retrieve actual key from key_id: " << key_id << dendl; s->err.message = "Failed to retrieve the actual key, kms-keyid: " + std::string(key_id); return res; } if (actual_key.size() != AES_256_KEYSIZE) { ldpp_dout(s, 5) << "ERROR: key obtained from key_id:" << key_id << " is not 256 bit size" << dendl; s->err.message = "KMS provided an invalid key for the given kms-keyid."; return -EINVAL; } if (block_crypt) { auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE); *block_crypt = std::move(aes); } ::ceph::crypto::zeroize_for_security(actual_key.data(), actual_key.length()); crypt_http_responses["x-amz-server-side-encryption"] = "aws:kms"; crypt_http_responses["x-amz-server-side-encryption-aws-kms-key-id"] = std::string(key_id); crypt_http_responses["x-amz-server-side-encryption-context"] = std::move(cooked_context); return 0; } else if (req_sse == "AES256") { /* SSE-S3: fall through to logic to look for vault or test key */ } else { ldpp_dout(s, 5) << "ERROR: Invalid value for header x-amz-server-side-encryption" << dendl; s->err.message = "Server Side Encryption with KMS managed key requires " "HTTP header x-amz-server-side-encryption : aws:kms or AES256"; return -EINVAL; } } else { /*no encryption*/ return 0; } /* from here on we are only handling SSE-S3 (req_sse=="AES256") */ if (s->cct->_conf->rgw_crypt_sse_s3_backend == "vault") { ldpp_dout(s, 5) << "RGW_ATTR_BUCKET_ENCRYPTION ALGO: " << req_sse << dendl; std::string_view context = ""; std::string cooked_context; if ((res = make_canonical_context(s, context, cooked_context))) return res; std::string key_id; res = get_sse_s3_bucket_key(s, key_id); if (res != 0) { return res; } std::string key_selector = create_random_key_selector(s->cct); set_attr(attrs, RGW_ATTR_CRYPT_KEYSEL, key_selector); set_attr(attrs, RGW_ATTR_CRYPT_CONTEXT, cooked_context); set_attr(attrs, RGW_ATTR_CRYPT_MODE, "AES256"); set_attr(attrs, RGW_ATTR_CRYPT_KEYID, key_id); std::string actual_key; res = make_actual_key_from_sse_s3(s, s->cct, attrs, actual_key); if (res != 0) { ldpp_dout(s, 5) << "ERROR: failed to retrieve actual key from key_id: " << key_id << dendl; s->err.message = "Failed to retrieve the actual key"; return res; } if (actual_key.size() != AES_256_KEYSIZE) { ldpp_dout(s, 5) << "ERROR: key obtained from key_id:" << key_id << " is not 256 bit size" << dendl; s->err.message = "SSE-S3 provided an invalid key for the given keyid."; return -EINVAL; } if (block_crypt) { auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE); *block_crypt = std::move(aes); } ::ceph::crypto::zeroize_for_security(actual_key.data(), actual_key.length()); crypt_http_responses["x-amz-server-side-encryption"] = "AES256"; return 0; } /* SSE-S3 and no backend, check if there is a test key */ if (s->cct->_conf->rgw_crypt_default_encryption_key != "") { std::string master_encryption_key; try { master_encryption_key = from_base64(s->cct->_conf->rgw_crypt_default_encryption_key); } catch (...) { ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_encrypt invalid default encryption key " << "which contains character that is not base64 encoded." << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key."; return -EINVAL; } if (master_encryption_key.size() != 256 / 8) { ldpp_dout(s, 0) << "ERROR: failed to decode 'rgw crypt default encryption key' to 256 bit string" << dendl; /* not an error to return; missing encryption does not inhibit processing */ return 0; } set_attr(attrs, RGW_ATTR_CRYPT_MODE, "RGW-AUTO"); std::string key_selector = create_random_key_selector(s->cct); set_attr(attrs, RGW_ATTR_CRYPT_KEYSEL, key_selector); uint8_t actual_key[AES_256_KEYSIZE]; if (AES_256_ECB_encrypt(s, s->cct, reinterpret_cast<const uint8_t*>(master_encryption_key.c_str()), AES_256_KEYSIZE, reinterpret_cast<const uint8_t*>(key_selector.c_str()), actual_key, AES_256_KEYSIZE) != true) { ::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key)); return -EIO; } if (block_crypt) { auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(actual_key), AES_256_KEYSIZE); *block_crypt = std::move(aes); } ::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key)); return 0; } s->err.message = "Request specifies Server Side Encryption " "but server configuration does not support this."; return -EINVAL; } } int rgw_s3_prepare_decrypt(req_state* s, map<string, bufferlist>& attrs, std::unique_ptr<BlockCrypt>* block_crypt, std::map<std::string, std::string>& crypt_http_responses) { int res = 0; std::string stored_mode = get_str_attribute(attrs, RGW_ATTR_CRYPT_MODE); ldpp_dout(s, 15) << "Encryption mode: " << stored_mode << dendl; const char *req_sse = s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION", NULL); if (nullptr != req_sse && (s->op == OP_GET || s->op == OP_HEAD)) { return -ERR_INVALID_REQUEST; } if (stored_mode == "SSE-C-AES256") { if (s->cct->_conf->rgw_crypt_require_ssl && !rgw_transport_is_secure(s->cct, *s->info.env)) { ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl; return -ERR_INVALID_REQUEST; } const char *req_cust_alg = s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM", NULL); if (nullptr == req_cust_alg) { ldpp_dout(s, 5) << "ERROR: Request for SSE-C encrypted object missing " << "x-amz-server-side-encryption-customer-algorithm" << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide a valid encryption algorithm."; return -EINVAL; } else if (strcmp(req_cust_alg, "AES256") != 0) { ldpp_dout(s, 5) << "ERROR: The requested encryption algorithm is not valid, must be AES256." << dendl; s->err.message = "The requested encryption algorithm is not valid, must be AES256."; return -ERR_INVALID_ENCRYPTION_ALGORITHM; } std::string key_bin; try { key_bin = from_base64(s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY", "")); } catch (...) { ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_decrypt invalid encryption key " << "which contains character that is not base64 encoded." << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key."; return -EINVAL; } if (key_bin.size() != AES_256_CBC::AES_256_KEYSIZE) { ldpp_dout(s, 5) << "ERROR: Invalid encryption key size" << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key."; return -EINVAL; } std::string keymd5 = s->info.env->get("HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5", ""); std::string keymd5_bin; try { keymd5_bin = from_base64(keymd5); } catch (...) { ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_decrypt invalid encryption key md5 " << "which contains character that is not base64 encoded." << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key md5."; return -EINVAL; } if (keymd5_bin.size() != CEPH_CRYPTO_MD5_DIGESTSIZE) { ldpp_dout(s, 5) << "ERROR: Invalid key md5 size " << dendl; s->err.message = "Requests specifying Server Side Encryption with Customer " "provided keys must provide an appropriate secret key md5."; return -EINVAL; } MD5 key_hash; // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes key_hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); uint8_t key_hash_res[CEPH_CRYPTO_MD5_DIGESTSIZE]; key_hash.Update(reinterpret_cast<const unsigned char*>(key_bin.c_str()), key_bin.size()); key_hash.Final(key_hash_res); if ((memcmp(key_hash_res, keymd5_bin.c_str(), CEPH_CRYPTO_MD5_DIGESTSIZE) != 0) || (get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYMD5) != keymd5_bin)) { s->err.message = "The calculated MD5 hash of the key did not match the hash that was provided."; return -EINVAL; } auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(key_bin.c_str()), AES_256_CBC::AES_256_KEYSIZE); if (block_crypt) *block_crypt = std::move(aes); crypt_http_responses["x-amz-server-side-encryption-customer-algorithm"] = "AES256"; crypt_http_responses["x-amz-server-side-encryption-customer-key-MD5"] = keymd5; return 0; } if (stored_mode == "SSE-KMS") { if (s->cct->_conf->rgw_crypt_require_ssl && !rgw_transport_is_secure(s->cct, *s->info.env)) { ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl; return -ERR_INVALID_REQUEST; } /* try to retrieve actual key */ std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID); std::string actual_key; res = reconstitute_actual_key_from_kms(s, s->cct, attrs, actual_key); if (res != 0) { ldpp_dout(s, 10) << "ERROR: failed to retrieve actual key from key_id: " << key_id << dendl; s->err.message = "Failed to retrieve the actual key, kms-keyid: " + key_id; return res; } if (actual_key.size() != AES_256_KEYSIZE) { ldpp_dout(s, 0) << "ERROR: key obtained from key_id:" << key_id << " is not 256 bit size" << dendl; s->err.message = "KMS provided an invalid key for the given kms-keyid."; return -EINVAL; } auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE); actual_key.replace(0, actual_key.length(), actual_key.length(), '\000'); if (block_crypt) *block_crypt = std::move(aes); crypt_http_responses["x-amz-server-side-encryption"] = "aws:kms"; crypt_http_responses["x-amz-server-side-encryption-aws-kms-key-id"] = key_id; return 0; } if (stored_mode == "RGW-AUTO") { std::string master_encryption_key; try { master_encryption_key = from_base64(std::string(s->cct->_conf->rgw_crypt_default_encryption_key)); } catch (...) { ldpp_dout(s, 5) << "ERROR: rgw_s3_prepare_decrypt invalid default encryption key " << "which contains character that is not base64 encoded." << dendl; s->err.message = "The default encryption key is not valid base64."; return -EINVAL; } if (master_encryption_key.size() != 256 / 8) { ldpp_dout(s, 0) << "ERROR: failed to decode 'rgw crypt default encryption key' to 256 bit string" << dendl; return -EIO; } std::string attr_key_selector = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYSEL); if (attr_key_selector.size() != AES_256_CBC::AES_256_KEYSIZE) { ldpp_dout(s, 0) << "ERROR: missing or invalid " RGW_ATTR_CRYPT_KEYSEL << dendl; return -EIO; } uint8_t actual_key[AES_256_KEYSIZE]; if (AES_256_ECB_encrypt(s, s->cct, reinterpret_cast<const uint8_t*>(master_encryption_key.c_str()), AES_256_KEYSIZE, reinterpret_cast<const uint8_t*>(attr_key_selector.c_str()), actual_key, AES_256_KEYSIZE) != true) { ::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key)); return -EIO; } auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(actual_key, AES_256_KEYSIZE); ::ceph::crypto::zeroize_for_security(actual_key, sizeof(actual_key)); if (block_crypt) *block_crypt = std::move(aes); return 0; } /* SSE-S3 */ if (stored_mode == "AES256") { if (s->cct->_conf->rgw_crypt_require_ssl && !rgw_transport_is_secure(s->cct, *s->info.env)) { ldpp_dout(s, 5) << "ERROR: Insecure request, rgw_crypt_require_ssl is set" << dendl; return -ERR_INVALID_REQUEST; } /* try to retrieve actual key */ std::string key_id = get_str_attribute(attrs, RGW_ATTR_CRYPT_KEYID); std::string actual_key; res = reconstitute_actual_key_from_sse_s3(s, s->cct, attrs, actual_key); if (res != 0) { ldpp_dout(s, 10) << "ERROR: failed to retrieve actual key" << dendl; s->err.message = "Failed to retrieve the actual key"; return res; } if (actual_key.size() != AES_256_KEYSIZE) { ldpp_dout(s, 0) << "ERROR: key obtained " << "is not 256 bit size" << dendl; s->err.message = "SSE-S3 provided an invalid key for the given keyid."; return -EINVAL; } auto aes = std::unique_ptr<AES_256_CBC>(new AES_256_CBC(s, s->cct)); aes->set_key(reinterpret_cast<const uint8_t*>(actual_key.c_str()), AES_256_KEYSIZE); actual_key.replace(0, actual_key.length(), actual_key.length(), '\000'); if (block_crypt) *block_crypt = std::move(aes); crypt_http_responses["x-amz-server-side-encryption"] = "AES256"; return 0; } /*no decryption*/ return 0; } int rgw_remove_sse_s3_bucket_key(req_state *s) { int res; auto key_id { expand_key_name(s, s->cct->_conf->rgw_crypt_sse_s3_key_template) }; auto saved_key { fetch_bucket_key_id(s) }; size_t i; if (key_id == cant_expand_key) { ldpp_dout(s, 5) << "ERROR: unable to expand key_id " << s->cct->_conf->rgw_crypt_sse_s3_key_template << " on bucket" << dendl; s->err.message = "Server side error - unable to expand key_id"; return -EINVAL; } if (saved_key == "") { return 0; } else if (saved_key != key_id) { ldpp_dout(s, 5) << "Found but will not delete strange KEK ID: " << saved_key << dendl; return 0; } i = s->cct->_conf->rgw_crypt_sse_s3_key_template.find("%bucket_id"); if (i == std::string_view::npos) { ldpp_dout(s, 5) << "Kept valid KEK ID: " << saved_key << dendl; return 0; } ldpp_dout(s, 5) << "Removing valid KEK ID: " << saved_key << dendl; res = remove_sse_s3_bucket_key(s, s->cct, saved_key); if (res != 0) { ldpp_dout(s, 0) << "ERROR: Unable to remove KEK ID: " << saved_key << " got " << res << dendl; } return res; } /********************************************************************* * "BOTTOM OF FILE" * I've left some commented out lines above. They are there for * a reason, which I will explain. The "canonical" json constructed * by the code above as a crypto context must take a json object and * turn it into a unique determinstic fixed form. For most json * types this is easy. The hardest problem that is handled above is * detailing with unicode strings; they must be turned into * NFC form and sorted in a fixed order. Numbers, however, * are another story. Json makes no distinction between integers * and floating point, and both types have their problems. * Integers can overflow, so very large numbers are a problem. * Floating point is even worse; not all floating point numbers * can be represented accurately in c++ data types, and there * are many quirks regarding how overflow, underflow, and loss * of significance are handled. * * In this version of the code, I took the simplest answer, I * reject all numbers altogether. This is not ideal, but it's * the only choice that is guaranteed to be future compatible. * AWS S3 does not guarantee to support numbers at all; but it * actually converts all numbers into strings right off. * This has the interesting property that 7 and 007 are different, * but that 007 and "007" are the same. I would rather * treat numbers as a string of digits and have logic * to produce the "most compact" equivalent form. This can * fix all the overflow/underflow problems, but it requires * fixing the json parser part, and I put that problem off. * * The commented code above indicates places in this code that * will need to be revised depending on future work in this area. * Removing those comments makes that work harder. * February 25, 2021 *********************************************************************/
57,311
35.434838
157
cc
null
ceph-main/src/rgw/rgw_crypt.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /** * Crypto filters for Put/Post/Get operations. */ #pragma once #include <string_view> #include <rgw/rgw_op.h> #include <rgw/rgw_rest.h> #include <rgw/rgw_rest_s3.h> #include "rgw_putobj.h" #include "common/async/yield_context.h" /** * \brief Interface for block encryption methods * * Encrypts and decrypts data. * Operations are performed in context of larger stream being divided into blocks. * Each block can be processed independently, but only as a whole. * Part block cannot be properly processed. * Each request must start on block-aligned offset. * Each request should have length that is multiply of block size. * Request with unaligned length is only acceptable for last part of stream. */ class BlockCrypt { public: BlockCrypt(){}; virtual ~BlockCrypt(){}; /** * Determines size of encryption block. * This is usually multiply of key size. * It determines size of chunks that should be passed to \ref encrypt and \ref decrypt. */ virtual size_t get_block_size() = 0; /** * Encrypts data. * Argument \ref stream_offset shows where in generalized stream chunk is located. * Input for encryption is \ref input buffer, with relevant data in range <in_ofs, in_ofs+size). * \ref input and \output may not be the same buffer. * * \params * input - source buffer of data * in_ofs - offset of chunk inside input * size - size of chunk, must be chunk-aligned unless last part is processed * output - destination buffer to encrypt to * stream_offset - location of <in_ofs,in_ofs+size) chunk in data stream, must be chunk-aligned * \return true iff successfully encrypted */ virtual bool encrypt(bufferlist& input, off_t in_ofs, size_t size, bufferlist& output, off_t stream_offset, optional_yield y) = 0; /** * Decrypts data. * Argument \ref stream_offset shows where in generalized stream chunk is located. * Input for decryption is \ref input buffer, with relevant data in range <in_ofs, in_ofs+size). * \ref input and \output may not be the same buffer. * * \params * input - source buffer of data * in_ofs - offset of chunk inside input * size - size of chunk, must be chunk-aligned unless last part is processed * output - destination buffer to encrypt to * stream_offset - location of <in_ofs,in_ofs+size) chunk in data stream, must be chunk-aligned * \return true iff successfully encrypted */ virtual bool decrypt(bufferlist& input, off_t in_ofs, size_t size, bufferlist& output, off_t stream_offset, optional_yield y) = 0; }; static const size_t AES_256_KEYSIZE = 256 / 8; bool AES_256_ECB_encrypt(const DoutPrefixProvider* dpp, CephContext* cct, const uint8_t* key, size_t key_size, const uint8_t* data_in, uint8_t* data_out, size_t data_size); class RGWGetObj_BlockDecrypt : public RGWGetObj_Filter { const DoutPrefixProvider *dpp; CephContext* cct; std::unique_ptr<BlockCrypt> crypt; /**< already configured stateless BlockCrypt for operations when enough data is accumulated */ off_t enc_begin_skip; /**< amount of data to skip from beginning of received data */ off_t ofs; /**< stream offset of data we expect to show up next through \ref handle_data */ off_t end; /**< stream offset of last byte that is requested */ bufferlist cache; /**< stores extra data that could not (yet) be processed by BlockCrypt */ size_t block_size; /**< snapshot of \ref BlockCrypt.get_block_size() */ optional_yield y; int process(bufferlist& cipher, size_t part_ofs, size_t size); protected: std::vector<size_t> parts_len; /**< size of parts of multipart object, parsed from manifest */ public: RGWGetObj_BlockDecrypt(const DoutPrefixProvider *dpp, CephContext* cct, RGWGetObj_Filter* next, std::unique_ptr<BlockCrypt> crypt, optional_yield y); virtual ~RGWGetObj_BlockDecrypt(); virtual int fixup_range(off_t& bl_ofs, off_t& bl_end) override; virtual int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override; virtual int flush() override; int read_manifest(const DoutPrefixProvider *dpp, bufferlist& manifest_bl); }; /* RGWGetObj_BlockDecrypt */ class RGWPutObj_BlockEncrypt : public rgw::putobj::Pipe { const DoutPrefixProvider *dpp; CephContext* cct; std::unique_ptr<BlockCrypt> crypt; /**< already configured stateless BlockCrypt for operations when enough data is accumulated */ bufferlist cache; /**< stores extra data that could not (yet) be processed by BlockCrypt */ const size_t block_size; /**< snapshot of \ref BlockCrypt.get_block_size() */ optional_yield y; public: RGWPutObj_BlockEncrypt(const DoutPrefixProvider *dpp, CephContext* cct, rgw::sal::DataProcessor *next, std::unique_ptr<BlockCrypt> crypt, optional_yield y); int process(bufferlist&& data, uint64_t logical_offset) override; }; /* RGWPutObj_BlockEncrypt */ int rgw_s3_prepare_encrypt(req_state* s, std::map<std::string, ceph::bufferlist>& attrs, std::unique_ptr<BlockCrypt>* block_crypt, std::map<std::string, std::string>& crypt_http_responses); int rgw_s3_prepare_decrypt(req_state* s, std::map<std::string, ceph::bufferlist>& attrs, std::unique_ptr<BlockCrypt>* block_crypt, std::map<std::string, std::string>& crypt_http_responses); static inline void set_attr(std::map<std::string, bufferlist>& attrs, const char* key, std::string_view value) { bufferlist bl; bl.append(value.data(), value.size()); attrs[key] = std::move(bl); } static inline std::string get_str_attribute(std::map<std::string, bufferlist>& attrs, const char *name) { auto iter = attrs.find(name); if (iter == attrs.end()) { return {}; } return iter->second.to_str(); } int rgw_remove_sse_s3_bucket_key(req_state *s);
6,873
37.188889
98
h
null
ceph-main/src/rgw/rgw_crypt_sanitize.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * rgw_crypt_sanitize.cc * * Created on: Mar 3, 2017 * Author: adam */ #include "rgw_common.h" #include "rgw_crypt_sanitize.h" #include "boost/algorithm/string/predicate.hpp" namespace rgw { namespace crypt_sanitize { const char* HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY = "HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY"; const char* x_amz_server_side_encryption_customer_key = "x-amz-server-side-encryption-customer-key"; const char* dollar_x_amz_server_side_encryption_customer_key = "$x-amz-server-side-encryption-customer-key"; const char* suppression_message = "=suppressed due to key presence="; std::ostream& operator<<(std::ostream& out, const env& e) { if (g_ceph_context->_conf->rgw_crypt_suppress_logs) { if (boost::algorithm::iequals( e.name, HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY)) { out << suppression_message; return out; } if (boost::algorithm::iequals(e.name, "QUERY_STRING") && boost::algorithm::ifind_first( e.value, x_amz_server_side_encryption_customer_key)) { out << suppression_message; return out; } } out << e.value; return out; } std::ostream& operator<<(std::ostream& out, const x_meta_map& x) { if (g_ceph_context->_conf->rgw_crypt_suppress_logs && boost::algorithm::iequals(x.name, x_amz_server_side_encryption_customer_key)) { out << suppression_message; return out; } out << x.value; return out; } std::ostream& operator<<(std::ostream& out, const s3_policy& x) { if (g_ceph_context->_conf->rgw_crypt_suppress_logs && boost::algorithm::iequals(x.name, dollar_x_amz_server_side_encryption_customer_key)) { out << suppression_message; return out; } out << x.value; return out; } std::ostream& operator<<(std::ostream& out, const auth& x) { if (g_ceph_context->_conf->rgw_crypt_suppress_logs && x.s->info.env->get(HTTP_X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, nullptr) != nullptr) { out << suppression_message; return out; } out << x.value; return out; } std::ostream& operator<<(std::ostream& out, const log_content& x) { if (g_ceph_context->_conf->rgw_crypt_suppress_logs && boost::algorithm::ifind_first(x.buf, x_amz_server_side_encryption_customer_key)) { out << suppression_message; return out; } out << x.buf; return out; } } }
2,505
27.157303
110
cc
null
ceph-main/src/rgw/rgw_crypt_sanitize.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string_view> #include "rgw_common.h" namespace rgw { namespace crypt_sanitize { /* * Temporary container for suppressing printing if variable contains secret key. */ struct env { std::string_view name; std::string_view value; env(std::string_view name, std::string_view value) : name(name), value(value) {} }; /* * Temporary container for suppressing printing if aws meta attributes contains secret key. */ struct x_meta_map { std::string_view name; std::string_view value; x_meta_map(std::string_view name, std::string_view value) : name(name), value(value) {} }; /* * Temporary container for suppressing printing if s3_policy calculation variable contains secret key. */ struct s3_policy { std::string_view name; std::string_view value; s3_policy(std::string_view name, std::string_view value) : name(name), value(value) {} }; /* * Temporary container for suppressing printing if auth string contains secret key. */ struct auth { const req_state* const s; std::string_view value; auth(const req_state* const s, std::string_view value) : s(s), value(value) {} }; /* * Temporary container for suppressing printing if log made from civetweb may contain secret key. */ struct log_content { const std::string_view buf; explicit log_content(const std::string_view buf) : buf(buf) {} }; std::ostream& operator<<(std::ostream& out, const env& e); std::ostream& operator<<(std::ostream& out, const x_meta_map& x); std::ostream& operator<<(std::ostream& out, const s3_policy& x); std::ostream& operator<<(std::ostream& out, const auth& x); std::ostream& operator<<(std::ostream& out, const log_content& x); } }
1,789
24.942029
102
h
null
ceph-main/src/rgw/rgw_d3n_cacherequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <fcntl.h> #include <stdlib.h> #include <aio.h> #include "include/rados/librados.hpp" #include "include/Context.h" #include "common/async/completion.h" #include <errno.h> #include "common/error_code.h" #include "common/errno.h" #include "rgw_aio.h" #include "rgw_cache.h" struct D3nGetObjData { std::mutex d3n_lock; }; struct D3nL1CacheRequest { ~D3nL1CacheRequest() { lsubdout(g_ceph_context, rgw_datacache, 30) << "D3nDataCache: " << __func__ << "(): Read From Cache, complete" << dendl; } // unique_ptr with custom deleter for struct aiocb struct libaio_aiocb_deleter { void operator()(struct aiocb* c) { if(c->aio_fildes > 0) { if( ::close(c->aio_fildes) != 0) { lsubdout(g_ceph_context, rgw_datacache, 2) << "D3nDataCache: " << __func__ << "(): Error - can't close file, errno=" << -errno << dendl; } } delete c; } }; using unique_aio_cb_ptr = std::unique_ptr<struct aiocb, libaio_aiocb_deleter>; struct AsyncFileReadOp { bufferlist result; unique_aio_cb_ptr aio_cb; using Signature = void(boost::system::error_code, bufferlist); using Completion = ceph::async::Completion<Signature, AsyncFileReadOp>; int init_async_read(const DoutPrefixProvider *dpp, const std::string& location, off_t read_ofs, off_t read_len, void* arg) { ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): location=" << location << dendl; aio_cb.reset(new struct aiocb); memset(aio_cb.get(), 0, sizeof(struct aiocb)); aio_cb->aio_fildes = TEMP_FAILURE_RETRY(::open(location.c_str(), O_RDONLY|O_CLOEXEC|O_BINARY)); if(aio_cb->aio_fildes < 0) { int err = errno; ldpp_dout(dpp, 1) << "ERROR: D3nDataCache: " << __func__ << "(): can't open " << location << " : " << cpp_strerror(err) << dendl; return -err; } if (g_conf()->rgw_d3n_l1_fadvise != POSIX_FADV_NORMAL) posix_fadvise(aio_cb->aio_fildes, 0, 0, g_conf()->rgw_d3n_l1_fadvise); bufferptr bp(read_len); aio_cb->aio_buf = bp.c_str(); result.append(std::move(bp)); aio_cb->aio_nbytes = read_len; aio_cb->aio_offset = read_ofs; aio_cb->aio_sigevent.sigev_notify = SIGEV_THREAD; aio_cb->aio_sigevent.sigev_notify_function = libaio_cb_aio_dispatch; aio_cb->aio_sigevent.sigev_notify_attributes = nullptr; aio_cb->aio_sigevent.sigev_value.sival_ptr = arg; return 0; } static void libaio_cb_aio_dispatch(sigval sigval) { lsubdout(g_ceph_context, rgw_datacache, 20) << "D3nDataCache: " << __func__ << "()" << dendl; auto p = std::unique_ptr<Completion>{static_cast<Completion*>(sigval.sival_ptr)}; auto op = std::move(p->user_data); const int ret = -aio_error(op.aio_cb.get()); boost::system::error_code ec; if (ret < 0) { ec.assign(-ret, boost::system::system_category()); } ceph::async::dispatch(std::move(p), ec, std::move(op.result)); } template <typename Executor1, typename CompletionHandler> static auto create(const Executor1& ex1, CompletionHandler&& handler) { auto p = Completion::create(ex1, std::move(handler)); return p; } }; template <typename ExecutionContext, typename CompletionToken> auto async_read(const DoutPrefixProvider *dpp, ExecutionContext& ctx, const std::string& location, off_t read_ofs, off_t read_len, CompletionToken&& token) { using Op = AsyncFileReadOp; using Signature = typename Op::Signature; boost::asio::async_completion<CompletionToken, Signature> init(token); auto p = Op::create(ctx.get_executor(), init.completion_handler); auto& op = p->user_data; ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): location=" << location << dendl; int ret = op.init_async_read(dpp, location, read_ofs, read_len, p.get()); if(0 == ret) { ret = ::aio_read(op.aio_cb.get()); } ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): ::aio_read(), ret=" << ret << dendl; if(ret < 0) { auto ec = boost::system::error_code{-ret, boost::system::system_category()}; ceph::async::post(std::move(p), ec, bufferlist{}); } else { // coverity[leaked_storage:SUPPRESS] (void)p.release(); } return init.result.get(); } struct d3n_libaio_handler { rgw::Aio* throttle = nullptr; rgw::AioResult& r; // read callback void operator()(boost::system::error_code ec, bufferlist bl) const { r.result = -ec.value(); r.data = std::move(bl); throttle->put(r); } }; void file_aio_read_abstract(const DoutPrefixProvider *dpp, boost::asio::io_context& context, yield_context yield, std::string& cache_location, off_t read_ofs, off_t read_len, rgw::Aio* aio, rgw::AioResult& r) { using namespace boost::asio; async_completion<yield_context, void()> init(yield); auto ex = get_associated_executor(init.completion_handler); ldpp_dout(dpp, 20) << "D3nDataCache: " << __func__ << "(): oid=" << r.obj.oid << dendl; async_read(dpp, context, cache_location+"/"+url_encode(r.obj.oid, true), read_ofs, read_len, bind_executor(ex, d3n_libaio_handler{aio, r})); } };
5,402
36.006849
146
h
null
ceph-main/src/rgw/rgw_dencoder.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_common.h" #include "rgw_rados.h" #include "rgw_zone.h" #include "rgw_log.h" #include "rgw_acl.h" #include "rgw_acl_s3.h" #include "rgw_cache.h" #include "rgw_meta_sync_status.h" #include "rgw_data_sync.h" #include "rgw_multi.h" #include "rgw_bucket_encryption.h" #include "common/Formatter.h" using namespace std; static string shadow_ns = RGW_OBJ_NS_SHADOW; void obj_version::generate_test_instances(list<obj_version*>& o) { obj_version *v = new obj_version; v->ver = 5; v->tag = "tag"; o.push_back(v); o.push_back(new obj_version); } void RGWBucketEncryptionConfig::generate_test_instances(std::list<RGWBucketEncryptionConfig*>& o) { auto *bc = new RGWBucketEncryptionConfig("aws:kms", "some:key", true); o.push_back(bc); bc = new RGWBucketEncryptionConfig("AES256"); o.push_back(bc); o.push_back(new RGWBucketEncryptionConfig); }
981
22.380952
97
cc
null
ceph-main/src/rgw/rgw_dmclock.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * Copyright (C) 2019 SUSE LLC * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "dmclock/src/dmclock_server.h" namespace rgw::dmclock { // TODO: implement read vs write enum class client_id { admin, //< /admin apis auth, //< swift auth, sts data, //< PutObj, GetObj metadata, //< bucket operations, object metadata count }; // TODO move these to dmclock/types or so in submodule using crimson::dmclock::Cost; using crimson::dmclock::ClientInfo; enum class scheduler_t { none, throttler, dmclock }; inline scheduler_t get_scheduler_t(CephContext* const cct) { const auto scheduler_type = cct->_conf.get_val<std::string>("rgw_scheduler_type"); if (scheduler_type == "dmclock") return scheduler_t::dmclock; else if (scheduler_type == "throttler") return scheduler_t::throttler; else return scheduler_t::none; } } // namespace rgw::dmclock
1,430
26
84
h
null
ceph-main/src/rgw/rgw_dmclock_async_scheduler.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "common/async/completion.h" #include "rgw_dmclock_async_scheduler.h" #include "rgw_dmclock_scheduler.h" namespace rgw::dmclock { AsyncScheduler::~AsyncScheduler() { cancel(); if (observer) { cct->_conf.remove_observer(this); } } const char** AsyncScheduler::get_tracked_conf_keys() const { if (observer) { return observer->get_tracked_conf_keys(); } static const char* keys[] = { "rgw_max_concurrent_requests", nullptr }; return keys; } void AsyncScheduler::handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) { if (observer) { observer->handle_conf_change(conf, changed); } if (changed.count("rgw_max_concurrent_requests")) { auto new_max = conf.get_val<int64_t>("rgw_max_concurrent_requests"); max_requests = new_max > 0 ? new_max : std::numeric_limits<int64_t>::max(); } queue.update_client_infos(); schedule(crimson::dmclock::TimeZero); } int AsyncScheduler::schedule_request_impl(const client_id& client, const ReqParams& params, const Time& time, const Cost& cost, optional_yield yield_ctx) { ceph_assert(yield_ctx); auto &yield = yield_ctx.get_yield_context(); boost::system::error_code ec; async_request(client, params, time, cost, yield[ec]); if (ec){ if (ec == boost::system::errc::resource_unavailable_try_again) return -EAGAIN; else return -ec.value(); } return 0; } void AsyncScheduler::request_complete() { --outstanding_requests; if(auto c = counters(client_id::count)){ c->inc(throttle_counters::l_outstanding, -1); } schedule(crimson::dmclock::TimeZero); } void AsyncScheduler::cancel() { ClientSums sums; queue.remove_by_req_filter([&] (RequestRef&& request) { inc(sums, request->client, request->cost); auto c = static_cast<Completion*>(request.release()); Completion::dispatch(std::unique_ptr<Completion>{c}, boost::asio::error::operation_aborted, PhaseType::priority); return true; }); timer.cancel(); for (size_t i = 0; i < client_count; i++) { if (auto c = counters(static_cast<client_id>(i))) { on_cancel(c, sums[i]); } } } void AsyncScheduler::cancel(const client_id& client) { ClientSum sum; queue.remove_by_client(client, false, [&] (RequestRef&& request) { sum.count++; sum.cost += request->cost; auto c = static_cast<Completion*>(request.release()); Completion::dispatch(std::unique_ptr<Completion>{c}, boost::asio::error::operation_aborted, PhaseType::priority); }); if (auto c = counters(client)) { on_cancel(c, sum); } schedule(crimson::dmclock::TimeZero); } void AsyncScheduler::schedule(const Time& time) { timer.expires_at(Clock::from_double(time)); timer.async_wait([this] (boost::system::error_code ec) { // process requests unless the wait was canceled. note that a canceled // wait may execute after this AsyncScheduler destructs if (ec != boost::asio::error::operation_aborted) { process(get_time()); } }); } void AsyncScheduler::process(const Time& now) { // must run in the executor. we should only invoke completion handlers if the // executor is running assert(get_executor().running_in_this_thread()); ClientSums rsums, psums; while (outstanding_requests < max_requests) { auto pull = queue.pull_request(now); if (pull.is_none()) { // no pending requests, cancel the timer timer.cancel(); break; } if (pull.is_future()) { // update the timer based on the future time schedule(pull.getTime()); break; } ++outstanding_requests; if(auto c = counters(client_id::count)){ c->inc(throttle_counters::l_outstanding); } // complete the request auto& r = pull.get_retn(); auto client = r.client; auto phase = r.phase; auto started = r.request->started; auto cost = r.request->cost; auto c = static_cast<Completion*>(r.request.release()); Completion::post(std::unique_ptr<Completion>{c}, boost::system::error_code{}, phase); if (auto c = counters(client)) { auto lat = Clock::from_double(now) - Clock::from_double(started); if (phase == PhaseType::reservation) { inc(rsums, client, cost); c->tinc(queue_counters::l_res_latency, lat); } else { inc(psums, client, cost); c->tinc(queue_counters::l_prio_latency, lat); } } } if (outstanding_requests >= max_requests) { if(auto c = counters(client_id::count)){ c->inc(throttle_counters::l_throttle); } } for (size_t i = 0; i < client_count; i++) { if (auto c = counters(static_cast<client_id>(i))) { on_process(c, rsums[i], psums[i]); } } } } // namespace rgw::dmclock
5,178
27.146739
79
cc
null
ceph-main/src/rgw/rgw_dmclock_async_scheduler.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2018 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "common/async/completion.h" #include <boost/asio.hpp> #include "rgw_dmclock_scheduler.h" #include "rgw_dmclock_scheduler_ctx.h" namespace rgw::dmclock { namespace async = ceph::async; /* * A dmclock request scheduling service for use with boost::asio. * * An asynchronous dmclock priority queue, where scheduled requests complete * on a boost::asio executor. */ class AsyncScheduler : public md_config_obs_t, public Scheduler { public: template <typename ...Args> // args forwarded to PullPriorityQueue ctor AsyncScheduler(CephContext *cct, boost::asio::io_context& context, GetClientCounters&& counters, md_config_obs_t *observer, Args&& ...args); ~AsyncScheduler(); using executor_type = boost::asio::io_context::executor_type; /// return the default executor for async_request() callbacks executor_type get_executor() noexcept { return timer.get_executor(); } /// submit an async request for dmclock scheduling. the given completion /// handler will be invoked with (error_code, PhaseType) when the request /// is ready or canceled. on success, this grants a throttle unit that must /// be returned with a call to request_complete() template <typename CompletionToken> auto async_request(const client_id& client, const ReqParams& params, const Time& time, Cost cost, CompletionToken&& token); /// returns a throttle unit granted by async_request() void request_complete() override; /// cancel all queued requests, invoking their completion handlers with an /// operation_aborted error and default-constructed result void cancel(); /// cancel all queued requests for a given client, invoking their completion /// handler with an operation_aborted error and default-constructed result void cancel(const client_id& client); const char** get_tracked_conf_keys() const override; void handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) override; private: int schedule_request_impl(const client_id& client, const ReqParams& params, const Time& time, const Cost& cost, optional_yield yield_ctx) override; static constexpr bool IsDelayed = false; using Queue = crimson::dmclock::PullPriorityQueue<client_id, Request, IsDelayed>; using RequestRef = typename Queue::RequestRef; Queue queue; //< dmclock priority queue using Signature = void(boost::system::error_code, PhaseType); using Completion = async::Completion<Signature, async::AsBase<Request>>; using Clock = ceph::coarse_real_clock; using Timer = boost::asio::basic_waitable_timer<Clock, boost::asio::wait_traits<Clock>, executor_type>; Timer timer; //< timer for the next scheduled request CephContext *const cct; md_config_obs_t *const observer; //< observer to update ClientInfoFunc GetClientCounters counters; //< provides per-client perf counters /// max request throttle std::atomic<int64_t> max_requests; std::atomic<int64_t> outstanding_requests = 0; /// set a timer to process the next request void schedule(const Time& time); /// process ready requests, then schedule the next pending request void process(const Time& now); }; template <typename ...Args> AsyncScheduler::AsyncScheduler(CephContext *cct, boost::asio::io_context& context, GetClientCounters&& counters, md_config_obs_t *observer, Args&& ...args) : queue(std::forward<Args>(args)...), timer(context), cct(cct), observer(observer), counters(std::move(counters)), max_requests(cct->_conf.get_val<int64_t>("rgw_max_concurrent_requests")) { if (max_requests <= 0) { max_requests = std::numeric_limits<int64_t>::max(); } if (observer) { cct->_conf.add_observer(this); } } template <typename CompletionToken> auto AsyncScheduler::async_request(const client_id& client, const ReqParams& params, const Time& time, Cost cost, CompletionToken&& token) { boost::asio::async_completion<CompletionToken, Signature> init(token); auto ex1 = get_executor(); auto& handler = init.completion_handler; // allocate the Request and add it to the queue auto completion = Completion::create(ex1, std::move(handler), Request{client, time, cost}); // cast to unique_ptr<Request> auto req = RequestRef{std::move(completion)}; int r = queue.add_request(std::move(req), client, params, time, cost); if (r == 0) { // schedule an immediate call to process() on the executor schedule(crimson::dmclock::TimeZero); if (auto c = counters(client)) { c->inc(queue_counters::l_qlen); c->inc(queue_counters::l_cost, cost); } } else { // post the error code boost::system::error_code ec(r, boost::system::system_category()); // cast back to Completion auto completion = static_cast<Completion*>(req.release()); async::post(std::unique_ptr<Completion>{completion}, ec, PhaseType::priority); if (auto c = counters(client)) { c->inc(queue_counters::l_limit); c->inc(queue_counters::l_limit_cost, cost); } } return init.result.get(); } class SimpleThrottler : public md_config_obs_t, public dmclock::Scheduler { public: SimpleThrottler(CephContext *cct) : max_requests(cct->_conf.get_val<int64_t>("rgw_max_concurrent_requests")), counters(cct, "simple-throttler") { if (max_requests <= 0) { max_requests = std::numeric_limits<int64_t>::max(); } cct->_conf.add_observer(this); } const char** get_tracked_conf_keys() const override { static const char* keys[] = { "rgw_max_concurrent_requests", nullptr }; return keys; } void handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) override { if (changed.count("rgw_max_concurrent_requests")) { auto new_max = conf.get_val<int64_t>("rgw_max_concurrent_requests"); max_requests = new_max > 0 ? new_max : std::numeric_limits<int64_t>::max(); } } void request_complete() override { --outstanding_requests; if (auto c = counters(); c != nullptr) { c->inc(throttle_counters::l_outstanding, -1); } } private: int schedule_request_impl(const client_id&, const ReqParams&, const Time&, const Cost&, optional_yield) override { if (outstanding_requests++ >= max_requests) { if (auto c = counters(); c != nullptr) { c->inc(throttle_counters::l_outstanding); c->inc(throttle_counters::l_throttle); } return -EAGAIN; } return 0 ; } std::atomic<int64_t> max_requests; std::atomic<int64_t> outstanding_requests = 0; ThrottleCounters counters; }; } // namespace rgw::dmclock
7,424
33.059633
83
h
null
ceph-main/src/rgw/rgw_dmclock_scheduler.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * (C) 2019 SUSE LLC * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "common/ceph_time.h" #include "common/ceph_context.h" #include "common/config.h" #include "common/async/yield_context.h" #include "rgw_dmclock.h" namespace rgw::dmclock { using crimson::dmclock::ReqParams; using crimson::dmclock::PhaseType; using crimson::dmclock::AtLimit; using crimson::dmclock::Time; using crimson::dmclock::get_time; /// function to provide client counters using GetClientCounters = std::function<PerfCounters*(client_id)>; struct Request { client_id client; Time started; Cost cost; }; enum class ReqState { Wait, Ready, Cancelled }; template <typename F> class Completer { public: Completer(F &&f): f(std::move(f)) {} // Default constructor is needed as we need to create an empty completer // that'll be move assigned later in process request Completer() = default; ~Completer() { if (f) { f(); } } Completer(const Completer&) = delete; Completer& operator=(const Completer&) = delete; Completer(Completer&& other) = default; Completer& operator=(Completer&& other) = default; private: F f; }; using SchedulerCompleter = Completer<std::function<void()>>; class Scheduler { public: auto schedule_request(const client_id& client, const ReqParams& params, const Time& time, const Cost& cost, optional_yield yield) { int r = schedule_request_impl(client,params,time,cost,yield); return std::make_pair(r,SchedulerCompleter(std::bind(&Scheduler::request_complete,this))); } virtual void request_complete() {}; virtual ~Scheduler() {}; private: virtual int schedule_request_impl(const client_id&, const ReqParams&, const Time&, const Cost&, optional_yield) = 0; }; } // namespace rgw::dmclock
2,173
23.988506
94
h
null
ceph-main/src/rgw/rgw_dmclock_scheduler_ctx.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * (C) 2019 SUSE Linux LLC * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "rgw_dmclock_scheduler_ctx.h" namespace rgw::dmclock { ClientConfig::ClientConfig(CephContext *cct) { update(cct->_conf); } ClientInfo* ClientConfig::operator()(client_id client) { return &clients[static_cast<size_t>(client)]; } const char** ClientConfig::get_tracked_conf_keys() const { static const char* keys[] = { "rgw_dmclock_admin_res", "rgw_dmclock_admin_wgt", "rgw_dmclock_admin_lim", "rgw_dmclock_auth_res", "rgw_dmclock_auth_wgt", "rgw_dmclock_auth_lim", "rgw_dmclock_data_res", "rgw_dmclock_data_wgt", "rgw_dmclock_data_lim", "rgw_dmclock_metadata_res", "rgw_dmclock_metadata_wgt", "rgw_dmclock_metadata_lim", "rgw_max_concurrent_requests", nullptr }; return keys; } void ClientConfig::update(const ConfigProxy& conf) { clients.clear(); static_assert(0 == static_cast<int>(client_id::admin)); clients.emplace_back(conf.get_val<double>("rgw_dmclock_admin_res"), conf.get_val<double>("rgw_dmclock_admin_wgt"), conf.get_val<double>("rgw_dmclock_admin_lim")); static_assert(1 == static_cast<int>(client_id::auth)); clients.emplace_back(conf.get_val<double>("rgw_dmclock_auth_res"), conf.get_val<double>("rgw_dmclock_auth_wgt"), conf.get_val<double>("rgw_dmclock_auth_lim")); static_assert(2 == static_cast<int>(client_id::data)); clients.emplace_back(conf.get_val<double>("rgw_dmclock_data_res"), conf.get_val<double>("rgw_dmclock_data_wgt"), conf.get_val<double>("rgw_dmclock_data_lim")); static_assert(3 == static_cast<int>(client_id::metadata)); clients.emplace_back(conf.get_val<double>("rgw_dmclock_metadata_res"), conf.get_val<double>("rgw_dmclock_metadata_wgt"), conf.get_val<double>("rgw_dmclock_metadata_lim")); } void ClientConfig::handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) { update(conf); } ClientCounters::ClientCounters(CephContext *cct) { clients[static_cast<size_t>(client_id::admin)] = queue_counters::build(cct, "dmclock-admin"); clients[static_cast<size_t>(client_id::auth)] = queue_counters::build(cct, "dmclock-auth"); clients[static_cast<size_t>(client_id::data)] = queue_counters::build(cct, "dmclock-data"); clients[static_cast<size_t>(client_id::metadata)] = queue_counters::build(cct, "dmclock-metadata"); clients[static_cast<size_t>(client_id::count)] = throttle_counters::build(cct, "dmclock-scheduler"); } void inc(ClientSums& sums, client_id client, Cost cost) { auto& sum = sums[static_cast<size_t>(client)]; sum.count++; sum.cost += cost; } void on_cancel(PerfCounters *c, const ClientSum& sum) { if (sum.count) { c->dec(queue_counters::l_qlen, sum.count); c->inc(queue_counters::l_cancel, sum.count); } if (sum.cost) { c->dec(queue_counters::l_cost, sum.cost); c->inc(queue_counters::l_cancel_cost, sum.cost); } } void on_process(PerfCounters* c, const ClientSum& rsum, const ClientSum& psum) { if (rsum.count) { c->inc(queue_counters::l_res, rsum.count); } if (rsum.cost) { c->inc(queue_counters::l_res_cost, rsum.cost); } if (psum.count) { c->inc(queue_counters::l_prio, psum.count); } if (psum.cost) { c->inc(queue_counters::l_prio_cost, psum.cost); } if (rsum.count + psum.count) { c->dec(queue_counters::l_qlen, rsum.count + psum.count); } if (rsum.cost + psum.cost) { c->dec(queue_counters::l_cost, rsum.cost + psum.cost); } } } // namespace rgw::dmclock namespace queue_counters { PerfCountersRef build(CephContext *cct, const std::string& name) { if (!cct->_conf->throttler_perf_counter) { return {}; } PerfCountersBuilder b(cct, name, l_first, l_last); b.add_u64(l_qlen, "qlen", "Queue size"); b.add_u64(l_cost, "cost", "Cost of queued requests"); b.add_u64_counter(l_res, "res", "Requests satisfied by reservation"); b.add_u64_counter(l_res_cost, "res_cost", "Cost satisfied by reservation"); b.add_u64_counter(l_prio, "prio", "Requests satisfied by priority"); b.add_u64_counter(l_prio_cost, "prio_cost", "Cost satisfied by priority"); b.add_u64_counter(l_limit, "limit", "Requests rejected by limit"); b.add_u64_counter(l_limit_cost, "limit_cost", "Cost rejected by limit"); b.add_u64_counter(l_cancel, "cancel", "Cancels"); b.add_u64_counter(l_cancel_cost, "cancel_cost", "Canceled cost"); b.add_time_avg(l_res_latency, "res latency", "Reservation latency"); b.add_time_avg(l_prio_latency, "prio latency", "Priority latency"); auto logger = PerfCountersRef{ b.create_perf_counters(), cct }; cct->get_perfcounters_collection()->add(logger.get()); return logger; } } // namespace queue_counters namespace throttle_counters { PerfCountersRef build(CephContext *cct, const std::string& name) { if (!cct->_conf->throttler_perf_counter) { return {}; } PerfCountersBuilder b(cct, name, l_first, l_last); b.add_u64(l_throttle, "throttle", "Requests throttled"); b.add_u64(l_outstanding, "outstanding", "Outstanding Requests"); auto logger = PerfCountersRef{ b.create_perf_counters(), cct }; cct->get_perfcounters_collection()->add(logger.get()); return logger; } } // namespace throttle_counters
5,839
31.625698
78
cc
null
ceph-main/src/rgw/rgw_dmclock_scheduler_ctx.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "common/perf_counters.h" #include "common/ceph_context.h" #include "common/config.h" #include "rgw_dmclock.h" namespace queue_counters { enum { l_first = 427150, l_qlen, l_cost, l_res, l_res_cost, l_prio, l_prio_cost, l_limit, l_limit_cost, l_cancel, l_cancel_cost, l_res_latency, l_prio_latency, l_last, }; PerfCountersRef build(CephContext *cct, const std::string& name); } // namespace queue_counters namespace throttle_counters { enum { l_first = 437219, l_throttle, l_outstanding, l_last }; PerfCountersRef build(CephContext *cct, const std::string& name); } // namespace throttle namespace rgw::dmclock { // the last client counter would be for global scheduler stats static constexpr auto counter_size = static_cast<size_t>(client_id::count) + 1; /// array of per-client counters to serve as GetClientCounters class ClientCounters { std::array<PerfCountersRef, counter_size> clients; public: ClientCounters(CephContext *cct); PerfCounters* operator()(client_id client) const { return clients[static_cast<size_t>(client)].get(); } }; class ThrottleCounters { PerfCountersRef counters; public: ThrottleCounters(CephContext* const cct,const std::string& name): counters(throttle_counters::build(cct, name)) {} PerfCounters* operator()() const { return counters.get(); } }; struct ClientSum { uint64_t count{0}; Cost cost{0}; }; constexpr auto client_count = static_cast<size_t>(client_id::count); using ClientSums = std::array<ClientSum, client_count>; void inc(ClientSums& sums, client_id client, Cost cost); void on_cancel(PerfCounters *c, const ClientSum& sum); void on_process(PerfCounters* c, const ClientSum& rsum, const ClientSum& psum); class ClientConfig : public md_config_obs_t { std::vector<ClientInfo> clients; void update(const ConfigProxy &conf); public: ClientConfig(CephContext *cct); ClientInfo* operator()(client_id client); const char** get_tracked_conf_keys() const override; void handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) override; }; class SchedulerCtx { public: SchedulerCtx(CephContext* const cct) : sched_t(get_scheduler_t(cct)) { if(sched_t == scheduler_t::dmclock) { dmc_client_config = std::make_shared<ClientConfig>(cct); // we don't have a move only cref std::function yet dmc_client_counters = std::make_optional<ClientCounters>(cct); } } // We need to construct a std::function from a NonCopyable object ClientCounters& get_dmc_client_counters() { return dmc_client_counters.value(); } ClientConfig* const get_dmc_client_config() const { return dmc_client_config.get(); } private: scheduler_t sched_t; std::shared_ptr<ClientConfig> dmc_client_config {nullptr}; std::optional<ClientCounters> dmc_client_counters {std::nullopt}; }; } // namespace rgw::dmclock
3,159
25.333333
87
h
null
ceph-main/src/rgw/rgw_dmclock_sync_scheduler.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_dmclock_scheduler.h" #include "rgw_dmclock_sync_scheduler.h" #include "rgw_dmclock_scheduler_ctx.h" namespace rgw::dmclock { SyncScheduler::~SyncScheduler() { cancel(); } int SyncScheduler::add_request(const client_id& client, const ReqParams& params, const Time& time, Cost cost) { std::mutex req_mtx; std::condition_variable req_cv; ReqState rstate {ReqState::Wait}; auto req = SyncRequest{client, time, cost, req_mtx, req_cv, rstate, counters}; int r = queue.add_request_time(req, client, params, time, cost); if (r == 0) { if (auto c = counters(client)) { c->inc(queue_counters::l_qlen); c->inc(queue_counters::l_cost, cost); } queue.request_completed(); // Perform a blocking wait until the request callback is called { std::unique_lock lock{req_mtx}; req_cv.wait(lock, [&rstate] {return rstate != ReqState::Wait;}); } if (rstate == ReqState::Cancelled) { //FIXME: decide on error code for cancelled request r = -ECONNABORTED; } } else { // post the error code if (auto c = counters(client)) { c->inc(queue_counters::l_limit); c->inc(queue_counters::l_limit_cost, cost); } } return r; } void SyncScheduler::handle_request_cb(const client_id &c, std::unique_ptr<SyncRequest> req, PhaseType phase, Cost cost) { { std::lock_guard<std::mutex> lg(req->req_mtx); req->req_state = ReqState::Ready; req->req_cv.notify_one(); } if (auto ctr = req->counters(c)) { auto lat = Clock::from_double(get_time()) - Clock::from_double(req->started); if (phase == PhaseType::reservation){ ctr->tinc(queue_counters::l_res_latency, lat); ctr->inc(queue_counters::l_res); if (cost) ctr->inc(queue_counters::l_res_cost); } else if (phase == PhaseType::priority){ ctr->tinc(queue_counters::l_prio_latency, lat); ctr->inc(queue_counters::l_prio); if (cost) ctr->inc(queue_counters::l_prio_cost); } ctr->dec(queue_counters::l_qlen); if (cost) ctr->dec(queue_counters::l_cost); } } void SyncScheduler::cancel(const client_id& client) { ClientSum sum; queue.remove_by_client(client, false, [&](RequestRef&& request) { sum.count++; sum.cost += request->cost; { std::lock_guard <std::mutex> lg(request->req_mtx); request->req_state = ReqState::Cancelled; request->req_cv.notify_one(); } }); if (auto c = counters(client)) { on_cancel(c, sum); } queue.request_completed(); } void SyncScheduler::cancel() { ClientSums sums; queue.remove_by_req_filter([&](RequestRef&& request) -> bool { inc(sums, request->client, request->cost); { std::lock_guard<std::mutex> lg(request->req_mtx); request->req_state = ReqState::Cancelled; request->req_cv.notify_one(); } return true; }); for (size_t i = 0; i < client_count; i++) { if (auto c = counters(static_cast<client_id>(i))) { on_cancel(c, sums[i]); } } } } // namespace rgw::dmclock
3,340
27.313559
81
cc
null
ceph-main/src/rgw/rgw_dmclock_sync_scheduler.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2018 SUSE Linux Gmbh * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include "rgw_dmclock_scheduler.h" #include "rgw_dmclock_scheduler_ctx.h" namespace rgw::dmclock { // For a blocking SyncRequest we hold a reference to a cv and the caller must // ensure the lifetime struct SyncRequest : public Request { std::mutex& req_mtx; std::condition_variable& req_cv; ReqState& req_state; GetClientCounters& counters; explicit SyncRequest(client_id _id, Time started, Cost cost, std::mutex& mtx, std::condition_variable& _cv, ReqState& _state, GetClientCounters& counters): Request{_id, started, cost}, req_mtx(mtx), req_cv(_cv), req_state(_state), counters(counters) {}; }; class SyncScheduler: public Scheduler { public: template <typename ...Args> SyncScheduler(CephContext *cct, GetClientCounters&& counters, Args&& ...args); ~SyncScheduler(); // submit a blocking request for dmclock scheduling, this function waits until // the request is ready. int add_request(const client_id& client, const ReqParams& params, const Time& time, Cost cost); void cancel(); void cancel(const client_id& client); static void handle_request_cb(const client_id& c, std::unique_ptr<SyncRequest> req, PhaseType phase, Cost cost); private: int schedule_request_impl(const client_id& client, const ReqParams& params, const Time& time, const Cost& cost, optional_yield _y [[maybe_unused]]) override { return add_request(client, params, time, cost); } static constexpr bool IsDelayed = false; using Queue = crimson::dmclock::PushPriorityQueue<client_id, SyncRequest, IsDelayed>; using RequestRef = typename Queue::RequestRef; using Clock = ceph::coarse_real_clock; Queue queue; CephContext const *cct; GetClientCounters counters; //< provides per-client perf counters }; template <typename ...Args> SyncScheduler::SyncScheduler(CephContext *cct, GetClientCounters&& counters, Args&& ...args): queue(std::forward<Args>(args)...), cct(cct), counters(std::move(counters)) {} } // namespace rgw::dmclock
2,478
30.782051
101
h
null
ceph-main/src/rgw/rgw_env.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_common.h" #include "rgw_log.h" #include <string> #include <map> #include "include/ceph_assert.h" #include "rgw_crypt_sanitize.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; void RGWEnv::init(CephContext *cct) { conf.init(cct); } void RGWEnv::set(std::string name, std::string val) { env_map[std::move(name)] = std::move(val); } void RGWEnv::init(CephContext *cct, char **envp) { const char *p; env_map.clear(); for (int i=0; (p = envp[i]); ++i) { string s(p); int pos = s.find('='); if (pos <= 0) // should never be 0 continue; string name = s.substr(0, pos); string val = s.substr(pos + 1); env_map[name] = val; } init(cct); } const char *rgw_conf_get(const map<string, string, ltstr_nocase>& conf_map, const char *name, const char *def_val) { auto iter = conf_map.find(name); if (iter == conf_map.end()) return def_val; return iter->second.c_str(); } boost::optional<const std::string&> rgw_conf_get_optional(const map<string, string, ltstr_nocase>& conf_map, const std::string& name) { auto iter = conf_map.find(name); if (iter == conf_map.end()) return boost::none; return boost::optional<const std::string&>(iter->second); } const char *RGWEnv::get(const char *name, const char *def_val) const { return rgw_conf_get(env_map, name, def_val); } boost::optional<const std::string&> RGWEnv::get_optional(const std::string& name) const { return rgw_conf_get_optional(env_map, name); } int rgw_conf_get_int(const map<string, string, ltstr_nocase>& conf_map, const char *name, int def_val) { auto iter = conf_map.find(name); if (iter == conf_map.end()) return def_val; const char *s = iter->second.c_str(); return atoi(s); } int RGWEnv::get_int(const char *name, int def_val) const { return rgw_conf_get_int(env_map, name, def_val); } bool rgw_conf_get_bool(const map<string, string, ltstr_nocase>& conf_map, const char *name, bool def_val) { auto iter = conf_map.find(name); if (iter == conf_map.end()) return def_val; const char *s = iter->second.c_str(); return rgw_str_to_bool(s, def_val); } bool RGWEnv::get_bool(const char *name, bool def_val) { return rgw_conf_get_bool(env_map, name, def_val); } size_t RGWEnv::get_size(const char *name, size_t def_val) const { const auto iter = env_map.find(name); if (iter == env_map.end()) return def_val; size_t sz; try{ sz = stoull(iter->second); } catch(...){ /* it is very unlikely that we'll ever encounter out_of_range, but let's return the default eitherway */ sz = def_val; } return sz; } bool RGWEnv::exists(const char *name) const { return env_map.find(name)!= env_map.end(); } bool RGWEnv::exists_prefix(const char *prefix) const { if (env_map.empty() || prefix == NULL) return false; const auto iter = env_map.lower_bound(prefix); if (iter == env_map.end()) return false; return (strncmp(iter->first.c_str(), prefix, strlen(prefix)) == 0); } void RGWEnv::remove(const char *name) { map<string, string, ltstr_nocase>::iterator iter = env_map.find(name); if (iter != env_map.end()) env_map.erase(iter); } void RGWConf::init(CephContext *cct) { enable_ops_log = cct->_conf->rgw_enable_ops_log; enable_usage_log = cct->_conf->rgw_enable_usage_log; defer_to_bucket_acls = 0; // default if (cct->_conf->rgw_defer_to_bucket_acls == "recurse") { defer_to_bucket_acls = RGW_DEFER_TO_BUCKET_ACLS_RECURSE; } else if (cct->_conf->rgw_defer_to_bucket_acls == "full_control") { defer_to_bucket_acls = RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL; } }
3,767
22.698113
133
cc
null
ceph-main/src/rgw/rgw_es_main.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <list> #include <string> #include <iostream> #include "global/global_init.h" #include "global/global_context.h" #include "common/ceph_argparse.h" #include "common/ceph_json.h" #include "rgw_es_query.h" using namespace std; int main(int argc, char *argv[]) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); common_init_finish(g_ceph_context); string expr; if (argc > 1) { expr = argv[1]; } else { expr = "age >= 30"; } ESQueryCompiler es_query(expr, nullptr, "x-amz-meta-"); map<string, string, ltstr_nocase> aliases = { { "key", "name" }, { "etag", "meta.etag" }, { "size", "meta.size" }, { "mtime", "meta.mtime" }, { "lastmodified", "meta.mtime" }, { "contenttype", "meta.contenttype" }, }; es_query.set_field_aliases(&aliases); map<string, ESEntityTypeMap::EntityType> generic_map = { {"bucket", ESEntityTypeMap::ES_ENTITY_STR}, {"name", ESEntityTypeMap::ES_ENTITY_STR}, {"instance", ESEntityTypeMap::ES_ENTITY_STR}, {"meta.etag", ESEntityTypeMap::ES_ENTITY_STR}, {"meta.contenttype", ESEntityTypeMap::ES_ENTITY_STR}, {"meta.mtime", ESEntityTypeMap::ES_ENTITY_DATE}, {"meta.size", ESEntityTypeMap::ES_ENTITY_INT} }; ESEntityTypeMap gm(generic_map); es_query.set_generic_type_map(&gm); map<string, ESEntityTypeMap::EntityType> custom_map = { {"str", ESEntityTypeMap::ES_ENTITY_STR}, {"int", ESEntityTypeMap::ES_ENTITY_INT}, {"date", ESEntityTypeMap::ES_ENTITY_DATE} }; ESEntityTypeMap em(custom_map); es_query.set_custom_type_map(&em); string err; bool valid = es_query.compile(&err); if (!valid) { cout << "failed to compile query: " << err << std::endl; return EINVAL; } JSONFormatter f; encode_json("root", es_query, &f); f.flush(cout); return 0; }
2,598
32.753247
112
cc
null
ceph-main/src/rgw/rgw_es_query.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <list> #include <map> #include <string> #include <iostream> #include <boost/algorithm/string.hpp> #include "common/ceph_json.h" #include "rgw_common.h" #include "rgw_es_query.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; bool pop_front(list<string>& l, string *s) { if (l.empty()) { return false; } *s = l.front(); l.pop_front(); return true; } map<string, int> operator_map = { { "or", 1 }, { "and", 2 }, { "<", 3 }, { "<=", 3 }, { "==", 3 }, { "!=", 3 }, { ">=", 3 }, { ">", 3 }, }; bool is_operator(const string& s) { return (operator_map.find(s) != operator_map.end()); } int operand_value(const string& op) { auto i = operator_map.find(op); if (i == operator_map.end()) { return 0; } return i->second; } int check_precedence(const string& op1, const string& op2) { return operand_value(op1) - operand_value(op2); } static bool infix_to_prefix(list<string>& source, list<string> *out) { list<string> operator_stack; list<string> operand_stack; operator_stack.push_front("("); source.push_back(")"); for (string& entity : source) { if (entity == "(") { operator_stack.push_front(entity); } else if (entity == ")") { string popped_operator; if (!pop_front(operator_stack, &popped_operator)) { return false; } while (popped_operator != "(") { operand_stack.push_front(popped_operator); if (!pop_front(operator_stack, &popped_operator)) { return false; } } } else if (is_operator(entity)) { string popped_operator; if (!pop_front(operator_stack, &popped_operator)) { return false; } int precedence = check_precedence(popped_operator, entity); while (precedence >= 0) { operand_stack.push_front(popped_operator); if (!pop_front(operator_stack, &popped_operator)) { return false; } precedence = check_precedence(popped_operator, entity); } operator_stack.push_front(popped_operator); operator_stack.push_front(entity); } else { operand_stack.push_front(entity); } } if (!operator_stack.empty()) { return false; } out->swap(operand_stack); return true; } class ESQueryNode { protected: ESQueryCompiler *compiler; public: ESQueryNode(ESQueryCompiler *_compiler) : compiler(_compiler) {} virtual ~ESQueryNode() {} virtual bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) = 0; virtual void dump(Formatter *f) const = 0; }; static bool alloc_node(ESQueryCompiler *compiler, ESQueryStack *s, ESQueryNode **pnode, string *perr); class ESQueryNode_Bool : public ESQueryNode { string op; ESQueryNode *first{nullptr}; ESQueryNode *second{nullptr}; public: explicit ESQueryNode_Bool(ESQueryCompiler *compiler) : ESQueryNode(compiler) {} ESQueryNode_Bool(ESQueryCompiler *compiler, const string& _op, ESQueryNode *_first, ESQueryNode *_second) :ESQueryNode(compiler), op(_op), first(_first), second(_second) {} bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override { bool valid = s->pop(&op); if (!valid) { *perr = "incorrect expression"; return false; } valid = alloc_node(compiler, s, &first, perr) && alloc_node(compiler, s, &second, perr); if (!valid) { return false; } *pnode = this; return true; } virtual ~ESQueryNode_Bool() { delete first; delete second; } void dump(Formatter *f) const override { f->open_object_section("bool"); const char *section = (op == "and" ? "must" : "should"); f->open_array_section(section); encode_json("entry", *first, f); encode_json("entry", *second, f); f->close_section(); f->close_section(); } }; class ESQueryNodeLeafVal { public: ESQueryNodeLeafVal() = default; virtual ~ESQueryNodeLeafVal() {} virtual bool init(const string& str_val, string *perr) = 0; virtual void encode_json(const string& field, Formatter *f) const = 0; }; class ESQueryNodeLeafVal_Str : public ESQueryNodeLeafVal { string val; public: ESQueryNodeLeafVal_Str() {} bool init(const string& str_val, string *perr) override { val = str_val; return true; } void encode_json(const string& field, Formatter *f) const override { ::encode_json(field.c_str(), val.c_str(), f); } }; class ESQueryNodeLeafVal_Int : public ESQueryNodeLeafVal { int64_t val{0}; public: ESQueryNodeLeafVal_Int() {} bool init(const string& str_val, string *perr) override { string err; val = strict_strtoll(str_val.c_str(), 10, &err); if (!err.empty()) { *perr = string("failed to parse integer: ") + err; return false; } return true; } void encode_json(const string& field, Formatter *f) const override { ::encode_json(field.c_str(), val, f); } }; class ESQueryNodeLeafVal_Date : public ESQueryNodeLeafVal { ceph::real_time val; public: ESQueryNodeLeafVal_Date() {} bool init(const string& str_val, string *perr) override { if (parse_time(str_val.c_str(), &val) < 0) { *perr = string("failed to parse date: ") + str_val; return false; } return true; } void encode_json(const string& field, Formatter *f) const override { string s; rgw_to_iso8601(val, &s); ::encode_json(field.c_str(), s, f); } }; class ESQueryNode_Op : public ESQueryNode { protected: string op; string field; string str_val; ESQueryNodeLeafVal *val{nullptr}; ESEntityTypeMap::EntityType entity_type{ESEntityTypeMap::ES_ENTITY_NONE}; bool allow_restricted{false}; bool val_from_str(string *perr) { switch (entity_type) { case ESEntityTypeMap::ES_ENTITY_DATE: val = new ESQueryNodeLeafVal_Date; break; case ESEntityTypeMap::ES_ENTITY_INT: val = new ESQueryNodeLeafVal_Int; break; default: val = new ESQueryNodeLeafVal_Str; } return val->init(str_val, perr); } bool do_init(ESQueryNode **pnode, string *perr) { field = compiler->unalias_field(field); ESQueryNode *effective_node; if (!handle_nested(&effective_node, perr)) { return false; } if (!val_from_str(perr)) { return false; } *pnode = effective_node; return true; } public: ESQueryNode_Op(ESQueryCompiler *compiler) : ESQueryNode(compiler) {} ~ESQueryNode_Op() { delete val; } virtual bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override { bool valid = s->pop(&op) && s->pop(&str_val) && s->pop(&field); if (!valid) { *perr = "invalid expression"; return false; } return do_init(pnode, perr); } bool handle_nested(ESQueryNode **pnode, string *perr); void set_allow_restricted(bool allow) { allow_restricted = allow; } virtual void dump(Formatter *f) const override = 0; }; class ESQueryNode_Op_Equal : public ESQueryNode_Op { public: explicit ESQueryNode_Op_Equal(ESQueryCompiler *compiler) : ESQueryNode_Op(compiler) {} ESQueryNode_Op_Equal(ESQueryCompiler *compiler, const string& f, const string& v) : ESQueryNode_Op(compiler) { op = "=="; field = f; str_val = v; } bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override { if (op.empty()) { return ESQueryNode_Op::init(s, pnode, perr); } return do_init(pnode, perr); } virtual void dump(Formatter *f) const override { f->open_object_section("term"); val->encode_json(field, f); f->close_section(); } }; class ESQueryNode_Op_NotEqual : public ESQueryNode_Op { public: explicit ESQueryNode_Op_NotEqual(ESQueryCompiler *compiler) : ESQueryNode_Op(compiler) {} ESQueryNode_Op_NotEqual(ESQueryCompiler *compiler, const string& f, const string& v) : ESQueryNode_Op(compiler) { op = "!="; field = f; str_val = v; } bool init(ESQueryStack *s, ESQueryNode **pnode, string *perr) override { if (op.empty()) { return ESQueryNode_Op::init(s, pnode, perr); } return do_init(pnode, perr); } virtual void dump(Formatter *f) const override { f->open_object_section("bool"); f->open_object_section("must_not"); f->open_object_section("term"); val->encode_json(field, f); f->close_section(); f->close_section(); f->close_section(); } }; class ESQueryNode_Op_Range : public ESQueryNode_Op { string range_str; public: ESQueryNode_Op_Range(ESQueryCompiler *compiler, const string& rs) : ESQueryNode_Op(compiler), range_str(rs) {} virtual void dump(Formatter *f) const override { f->open_object_section("range"); f->open_object_section(field.c_str()); val->encode_json(range_str, f); f->close_section(); f->close_section(); } }; class ESQueryNode_Op_Nested_Parent : public ESQueryNode_Op { public: ESQueryNode_Op_Nested_Parent(ESQueryCompiler *compiler) : ESQueryNode_Op(compiler) {} virtual string get_custom_leaf_field_name() = 0; }; template <class T> class ESQueryNode_Op_Nested : public ESQueryNode_Op_Nested_Parent { string name; ESQueryNode *next; public: ESQueryNode_Op_Nested(ESQueryCompiler *compiler, const string& _name, ESQueryNode *_next) : ESQueryNode_Op_Nested_Parent(compiler), name(_name), next(_next) {} ~ESQueryNode_Op_Nested() { delete next; } virtual void dump(Formatter *f) const override { f->open_object_section("nested"); string s = string("meta.custom-") + type_str(); encode_json("path", s.c_str(), f); f->open_object_section("query"); f->open_object_section("bool"); f->open_array_section("must"); f->open_object_section("entry"); f->open_object_section("match"); string n = s + ".name"; encode_json(n.c_str(), name.c_str(), f); f->close_section(); f->close_section(); encode_json("entry", *next, f); f->close_section(); f->close_section(); f->close_section(); f->close_section(); } string type_str() const; string get_custom_leaf_field_name() override { return string("meta.custom-") + type_str() + ".value"; } }; template<> string ESQueryNode_Op_Nested<string>::type_str() const { return "string"; } template<> string ESQueryNode_Op_Nested<int64_t>::type_str() const { return "int"; } template<> string ESQueryNode_Op_Nested<ceph::real_time>::type_str() const { return "date"; } bool ESQueryNode_Op::handle_nested(ESQueryNode **pnode, string *perr) { string field_name = field; const string& custom_prefix = compiler->get_custom_prefix(); if (!boost::algorithm::starts_with(field_name, custom_prefix)) { *pnode = this; auto m = compiler->get_generic_type_map(); if (m) { bool found = m->find(field_name, &entity_type) && (allow_restricted || !compiler->is_restricted(field_name)); if (!found) { *perr = string("unexpected generic field '") + field_name + "'"; } return found; } *perr = "query parser does not support generic types"; return false; } field_name = field_name.substr(custom_prefix.size()); auto m = compiler->get_custom_type_map(); if (m) { m->find(field_name, &entity_type); /* ignoring returned bool, for now just treat it as string */ } ESQueryNode_Op_Nested_Parent *new_node; switch (entity_type) { case ESEntityTypeMap::ES_ENTITY_INT: new_node = new ESQueryNode_Op_Nested<int64_t>(compiler, field_name, this); break; case ESEntityTypeMap::ES_ENTITY_DATE: new_node = new ESQueryNode_Op_Nested<ceph::real_time>(compiler, field_name, this); break; default: new_node = new ESQueryNode_Op_Nested<string>(compiler, field_name, this); } field = new_node->get_custom_leaf_field_name(); *pnode = new_node; return true; } static bool is_bool_op(const string& str) { return (str == "or" || str == "and"); } static bool alloc_node(ESQueryCompiler *compiler, ESQueryStack *s, ESQueryNode **pnode, string *perr) { string op; bool valid = s->peek(&op); if (!valid) { *perr = "incorrect expression"; return false; } ESQueryNode *node; if (is_bool_op(op)) { node = new ESQueryNode_Bool(compiler); } else if (op == "==") { node = new ESQueryNode_Op_Equal(compiler); } else if (op == "!=") { node = new ESQueryNode_Op_NotEqual(compiler); } else { static map<string, string> range_op_map = { { "<", "lt"}, { "<=", "lte"}, { ">=", "gte"}, { ">", "gt"}, }; auto iter = range_op_map.find(op); if (iter == range_op_map.end()) { *perr = string("invalid operator: ") + op; return false; } node = new ESQueryNode_Op_Range(compiler, iter->second); } if (!node->init(s, pnode, perr)) { delete node; return false; } return true; } bool is_key_char(char c) { switch (c) { case '(': case ')': case '<': case '>': case '!': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return false; }; return (isascii(c) > 0); } static bool is_op_char(char c) { switch (c) { case '!': case '<': case '=': case '>': return true; }; return false; } static bool is_val_char(char c) { if (isspace(c)) { return false; } return (c != ')'); } void ESInfixQueryParser::skip_whitespace(const char *str, int size, int& pos) { while (pos < size && isspace(str[pos])) { ++pos; } } bool ESInfixQueryParser::get_next_token(bool (*filter)(char)) { skip_whitespace(str, size, pos); int token_start = pos; while (pos < size && filter(str[pos])) { ++pos; } if (pos == token_start) { return false; } string token = string(str + token_start, pos - token_start); args.push_back(token); return true; } bool ESInfixQueryParser::parse_condition() { /* * condition: <key> <operator> <val> * * whereas key: needs to conform to http header field restrictions * operator: one of the following: < <= == != >= > * val: ascii, terminated by either space or ')' (or end of string) */ /* parse key */ bool valid = get_next_token(is_key_char) && get_next_token(is_op_char) && get_next_token(is_val_char); if (!valid) { return false; } return true; } bool ESInfixQueryParser::parse_and_or() { skip_whitespace(str, size, pos); if (pos + 3 <= size && strncmp(str + pos, "and", 3) == 0) { pos += 3; args.push_back("and"); return true; } if (pos + 2 <= size && strncmp(str + pos, "or", 2) == 0) { pos += 2; args.push_back("or"); return true; } return false; } bool ESInfixQueryParser::parse_specific_char(const char *pchar) { skip_whitespace(str, size, pos); if (pos >= size) { return false; } if (str[pos] != *pchar) { return false; } args.push_back(pchar); ++pos; return true; } bool ESInfixQueryParser::parse_open_bracket() { return parse_specific_char("("); } bool ESInfixQueryParser::parse_close_bracket() { return parse_specific_char(")"); } bool ESInfixQueryParser::parse(list<string> *result) { /* * expression: [(]<condition>[[and/or]<condition>][)][and/or]... */ while (pos < size) { parse_open_bracket(); if (!parse_condition()) { return false; } parse_close_bracket(); parse_and_or(); } result->swap(args); return true; } bool ESQueryCompiler::convert(list<string>& infix, string *perr) { list<string> prefix; if (!infix_to_prefix(infix, &prefix)) { *perr = "invalid query"; return false; } stack.assign(prefix); if (!alloc_node(this, &stack, &query_root, perr)) { return false; } if (!stack.done()) { *perr = "invalid query"; return false; } return true; } ESQueryCompiler::~ESQueryCompiler() { delete query_root; } bool ESQueryCompiler::compile(string *perr) { list<string> infix; if (!parser.parse(&infix)) { *perr = "failed to parse query"; return false; } if (!convert(infix, perr)) { return false; } for (auto& c : eq_conds) { ESQueryNode_Op_Equal *eq_node = new ESQueryNode_Op_Equal(this, c.first, c.second); eq_node->set_allow_restricted(true); /* can access restricted fields */ ESQueryNode *effective_node; if (!eq_node->init(nullptr, &effective_node, perr)) { delete eq_node; return false; } query_root = new ESQueryNode_Bool(this, "and", effective_node, query_root); } return true; } void ESQueryCompiler::dump(Formatter *f) const { encode_json("query", *query_root, f); }
16,899
23.246772
174
cc
null
ceph-main/src/rgw/rgw_es_query.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_string.h" class ESQueryStack { std::list<std::string> l; std::list<std::string>::iterator iter; public: explicit ESQueryStack(std::list<std::string>& src) { assign(src); } ESQueryStack() {} void assign(std::list<std::string>& src) { l.swap(src); iter = l.begin(); } bool peek(std::string *dest) { if (done()) { return false; } *dest = *iter; return true; } bool pop(std::string *dest) { bool valid = peek(dest); if (!valid) { return false; } ++iter; return true; } bool done() { return (iter == l.end()); } }; class ESInfixQueryParser { std::string query; int size; const char *str; int pos{0}; std::list<std::string> args; void skip_whitespace(const char *str, int size, int& pos); bool get_next_token(bool (*filter)(char)); bool parse_condition(); bool parse_and_or(); bool parse_specific_char(const char *pchar); bool parse_open_bracket(); bool parse_close_bracket(); public: explicit ESInfixQueryParser(const std::string& _query) : query(_query), size(query.size()), str(query.c_str()) {} bool parse(std::list<std::string> *result); }; class ESQueryNode; struct ESEntityTypeMap { enum EntityType { ES_ENTITY_NONE = 0, ES_ENTITY_STR = 1, ES_ENTITY_INT = 2, ES_ENTITY_DATE = 3, }; std::map<std::string, EntityType> m; explicit ESEntityTypeMap(std::map<std::string, EntityType>& _m) : m(_m) {} bool find(const std::string& entity, EntityType *ptype) { auto i = m.find(entity); if (i != m.end()) { *ptype = i->second; return true; } *ptype = ES_ENTITY_NONE; return false; } }; class ESQueryCompiler { ESInfixQueryParser parser; ESQueryStack stack; ESQueryNode *query_root{nullptr}; std::string custom_prefix; bool convert(std::list<std::string>& infix, std::string *perr); std::list<std::pair<std::string, std::string> > eq_conds; ESEntityTypeMap *generic_type_map{nullptr}; ESEntityTypeMap *custom_type_map{nullptr}; std::map<std::string, std::string, ltstr_nocase> *field_aliases = nullptr; std::set<std::string> *restricted_fields = nullptr; public: ESQueryCompiler(const std::string& query, std::list<std::pair<std::string, std::string> > *prepend_eq_conds, const std::string& _custom_prefix) : parser(query), custom_prefix(_custom_prefix) { if (prepend_eq_conds) { eq_conds = std::move(*prepend_eq_conds); } } ~ESQueryCompiler(); bool compile(std::string *perr); void dump(Formatter *f) const; void set_generic_type_map(ESEntityTypeMap *entity_map) { generic_type_map = entity_map; } ESEntityTypeMap *get_generic_type_map() { return generic_type_map; } const std::string& get_custom_prefix() { return custom_prefix; } void set_custom_type_map(ESEntityTypeMap *entity_map) { custom_type_map = entity_map; } ESEntityTypeMap *get_custom_type_map() { return custom_type_map; } void set_field_aliases(std::map<std::string, std::string, ltstr_nocase> *fa) { field_aliases = fa; } std::string unalias_field(const std::string& field) { if (!field_aliases) { return field; } auto i = field_aliases->find(field); if (i == field_aliases->end()) { return field; } return i->second; } void set_restricted_fields(std::set<std::string> *rf) { restricted_fields = rf; } bool is_restricted(const std::string& f) { return (restricted_fields && restricted_fields->find(f) != restricted_fields->end()); } };
3,705
21.460606
115
h
null
ceph-main/src/rgw/rgw_file.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "include/compat.h" #include "include/rados/rgw_file.h" #include <sys/types.h> #include <sys/stat.h> #include "rgw_lib.h" #include "rgw_resolve.h" #include "rgw_op.h" #include "rgw_rest.h" #include "rgw_acl.h" #include "rgw_acl_s3.h" #include "rgw_frontend.h" #include "rgw_request.h" #include "rgw_process.h" #include "rgw_rest_user.h" #include "rgw_rest_s3.h" #include "rgw_os_lib.h" #include "rgw_auth_s3.h" #include "rgw_user.h" #include "rgw_bucket.h" #include "rgw_zone.h" #include "rgw_file.h" #include "rgw_lib_frontend.h" #include "rgw_perf_counters.h" #include "common/errno.h" #include "services/svc_zone.h" #include <atomic> #define dout_subsys ceph_subsys_rgw using namespace std; using namespace rgw; namespace rgw { const string RGWFileHandle::root_name = "/"; std::atomic<uint32_t> RGWLibFS::fs_inst_counter; uint32_t RGWLibFS::write_completion_interval_s = 10; ceph::timer<ceph::mono_clock> RGWLibFS::write_timer{ ceph::construct_suspended}; inline int valid_fs_bucket_name(const string& name) { int rc = valid_s3_bucket_name(name, false /* relaxed */); if (rc != 0) { if (name.size() > 255) return -ENAMETOOLONG; return -EINVAL; } return 0; } inline int valid_fs_object_name(const string& name) { int rc = valid_s3_object_name(name); if (rc != 0) { if (name.size() > 1024) return -ENAMETOOLONG; return -EINVAL; } return 0; } class XattrHash { public: std::size_t operator()(const rgw_xattrstr& att) const noexcept { return XXH64(att.val, att.len, 5882300); } }; class XattrEqual { public: bool operator()(const rgw_xattrstr& lhs, const rgw_xattrstr& rhs) const { return ((lhs.len == rhs.len) && (strncmp(lhs.val, rhs.val, lhs.len) == 0)); } }; /* well-known attributes */ static const std::unordered_set< rgw_xattrstr, XattrHash, XattrEqual> rgw_exposed_attrs = { rgw_xattrstr{const_cast<char*>(RGW_ATTR_ETAG), sizeof(RGW_ATTR_ETAG)-1} }; static inline bool is_exposed_attr(const rgw_xattrstr& k) { return (rgw_exposed_attrs.find(k) != rgw_exposed_attrs.end()); } LookupFHResult RGWLibFS::stat_bucket(RGWFileHandle* parent, const char *path, RGWLibFS::BucketStats& bs, uint32_t flags) { LookupFHResult fhr{nullptr, 0}; std::string bucket_name{path}; RGWStatBucketRequest req(cct, user->clone(), bucket_name, bs); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc == 0) && (req.get_ret() == 0) && (req.matched())) { fhr = lookup_fh(parent, path, (flags & RGWFileHandle::FLAG_LOCKED)| RGWFileHandle::FLAG_CREATE| RGWFileHandle::FLAG_BUCKET); if (get<0>(fhr)) { RGWFileHandle* rgw_fh = get<0>(fhr); if (! (flags & RGWFileHandle::FLAG_LOCKED)) { rgw_fh->mtx.lock(); } rgw_fh->set_times(req.get_ctime()); /* restore attributes */ auto ux_key = req.get_attr(RGW_ATTR_UNIX_KEY1); auto ux_attrs = req.get_attr(RGW_ATTR_UNIX1); if (ux_key && ux_attrs) { DecodeAttrsResult dar = rgw_fh->decode_attrs(ux_key, ux_attrs); if (get<0>(dar) || get<1>(dar)) { update_fh(rgw_fh); } } if (! (flags & RGWFileHandle::FLAG_LOCKED)) { rgw_fh->mtx.unlock(); } } } return fhr; } LookupFHResult RGWLibFS::fake_leaf(RGWFileHandle* parent, const char *path, enum rgw_fh_type type, struct stat *st, uint32_t st_mask, uint32_t flags) { /* synthesize a minimal handle from parent, path, type, and st */ using std::get; flags |= RGWFileHandle::FLAG_CREATE; switch (type) { case RGW_FS_TYPE_DIRECTORY: flags |= RGWFileHandle::FLAG_DIRECTORY; break; default: /* file */ break; }; LookupFHResult fhr = lookup_fh(parent, path, flags); if (get<0>(fhr)) { RGWFileHandle* rgw_fh = get<0>(fhr); if (st) { lock_guard guard(rgw_fh->mtx); if (st_mask & RGW_SETATTR_SIZE) { rgw_fh->set_size(st->st_size); } if (st_mask & RGW_SETATTR_MTIME) { rgw_fh->set_times(st->st_mtim); } } /* st */ } /* rgw_fh */ return fhr; } /* RGWLibFS::fake_leaf */ LookupFHResult RGWLibFS::stat_leaf(RGWFileHandle* parent, const char *path, enum rgw_fh_type type, uint32_t flags) { /* find either-of <object_name>, <object_name/>, only one of * which should exist; atomicity? */ using std::get; LookupFHResult fhr{nullptr, 0}; /* XXX the need for two round-trip operations to identify file or * directory leaf objects is unecessary--the current proposed * mechanism to avoid this is to store leaf object names with an * object locator w/o trailing slash */ std::string obj_path = parent->format_child_name(path, false); for (auto ix : { 0, 1, 2 }) { switch (ix) { case 0: { /* type hint */ if (type == RGW_FS_TYPE_DIRECTORY) continue; RGWStatObjRequest req(cct, user->clone(), parent->bucket_name(), obj_path, RGWStatObjRequest::FLAG_NONE); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc == 0) && (req.get_ret() == 0)) { fhr = lookup_fh(parent, path, RGWFileHandle::FLAG_CREATE); if (get<0>(fhr)) { RGWFileHandle* rgw_fh = get<0>(fhr); lock_guard guard(rgw_fh->mtx); rgw_fh->set_size(req.get_size()); rgw_fh->set_times(req.get_mtime()); /* restore attributes */ auto ux_key = req.get_attr(RGW_ATTR_UNIX_KEY1); auto ux_attrs = req.get_attr(RGW_ATTR_UNIX1); rgw_fh->set_etag(*(req.get_attr(RGW_ATTR_ETAG))); rgw_fh->set_acls(*(req.get_attr(RGW_ATTR_ACL))); if (!(flags & RGWFileHandle::FLAG_IN_CB) && ux_key && ux_attrs) { DecodeAttrsResult dar = rgw_fh->decode_attrs(ux_key, ux_attrs); if (get<0>(dar) || get<1>(dar)) { update_fh(rgw_fh); } } } goto done; } } break; case 1: { /* try dir form */ /* type hint */ if (type == RGW_FS_TYPE_FILE) continue; obj_path += "/"; RGWStatObjRequest req(cct, user->clone(), parent->bucket_name(), obj_path, RGWStatObjRequest::FLAG_NONE); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc == 0) && (req.get_ret() == 0)) { fhr = lookup_fh(parent, path, RGWFileHandle::FLAG_DIRECTORY); if (get<0>(fhr)) { RGWFileHandle* rgw_fh = get<0>(fhr); lock_guard guard(rgw_fh->mtx); rgw_fh->set_size(req.get_size()); rgw_fh->set_times(req.get_mtime()); /* restore attributes */ auto ux_key = req.get_attr(RGW_ATTR_UNIX_KEY1); auto ux_attrs = req.get_attr(RGW_ATTR_UNIX1); rgw_fh->set_etag(*(req.get_attr(RGW_ATTR_ETAG))); rgw_fh->set_acls(*(req.get_attr(RGW_ATTR_ACL))); if (!(flags & RGWFileHandle::FLAG_IN_CB) && ux_key && ux_attrs) { DecodeAttrsResult dar = rgw_fh->decode_attrs(ux_key, ux_attrs); if (get<0>(dar) || get<1>(dar)) { update_fh(rgw_fh); } } } goto done; } } break; case 2: { std::string object_name{path}; RGWStatLeafRequest req(cct, user->clone(), parent, object_name); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc == 0) && (req.get_ret() == 0)) { if (req.matched) { /* we need rgw object's key name equal to file name, if * not return NULL */ if ((flags & RGWFileHandle::FLAG_EXACT_MATCH) && !req.exact_matched) { lsubdout(get_context(), rgw, 15) << __func__ << ": stat leaf not exact match file name = " << path << dendl; goto done; } fhr = lookup_fh(parent, path, RGWFileHandle::FLAG_CREATE| ((req.is_dir) ? RGWFileHandle::FLAG_DIRECTORY : RGWFileHandle::FLAG_NONE)); /* XXX we don't have an object--in general, there need not * be one (just a path segment in some other object). In * actual leaf an object exists, but we'd need another round * trip to get attrs */ if (get<0>(fhr)) { /* for now use the parent object's mtime */ RGWFileHandle* rgw_fh = get<0>(fhr); lock_guard guard(rgw_fh->mtx); rgw_fh->set_mtime(parent->get_mtime()); } } } } break; default: /* not reached */ break; } } done: return fhr; } /* RGWLibFS::stat_leaf */ int RGWLibFS::read(RGWFileHandle* rgw_fh, uint64_t offset, size_t length, size_t* bytes_read, void* buffer, uint32_t flags) { if (! rgw_fh->is_file()) return -EINVAL; if (rgw_fh->deleted()) return -ESTALE; RGWReadRequest req(get_context(), user->clone(), rgw_fh, offset, length, buffer); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc == 0) && ((rc = req.get_ret()) == 0)) { lock_guard guard(rgw_fh->mtx); rgw_fh->set_atime(real_clock::to_timespec(real_clock::now())); *bytes_read = req.nread; } return rc; } int RGWLibFS::readlink(RGWFileHandle* rgw_fh, uint64_t offset, size_t length, size_t* bytes_read, void* buffer, uint32_t flags) { if (! rgw_fh->is_link()) return -EINVAL; if (rgw_fh->deleted()) return -ESTALE; RGWReadRequest req(get_context(), user->clone(), rgw_fh, offset, length, buffer); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc == 0) && ((rc = req.get_ret()) == 0)) { lock_guard(rgw_fh->mtx); rgw_fh->set_atime(real_clock::to_timespec(real_clock::now())); *bytes_read = req.nread; } return rc; } int RGWLibFS::unlink(RGWFileHandle* rgw_fh, const char* name, uint32_t flags) { int rc = 0; BucketStats bs; RGWFileHandle* parent = nullptr; RGWFileHandle* bkt_fh = nullptr; if (unlikely(flags & RGWFileHandle::FLAG_UNLINK_THIS)) { /* LOCKED */ parent = rgw_fh->get_parent(); } else { /* atomicity */ parent = rgw_fh; LookupFHResult fhr = lookup_fh(parent, name, RGWFileHandle::FLAG_LOCK); rgw_fh = get<0>(fhr); /* LOCKED */ } if (parent->is_root()) { /* a bucket may have an object storing Unix attributes, check * for and delete it */ LookupFHResult fhr; fhr = stat_bucket(parent, name, bs, (rgw_fh) ? RGWFileHandle::FLAG_LOCKED : RGWFileHandle::FLAG_NONE); bkt_fh = get<0>(fhr); if (unlikely(! bkt_fh)) { /* implies !rgw_fh, so also !LOCKED */ return -ENOENT; } if (bs.num_entries > 1) { unref(bkt_fh); /* return stat_bucket ref */ if (likely(!! rgw_fh)) { /* return lock and ref from * lookup_fh (or caller in the * special case of * RGWFileHandle::FLAG_UNLINK_THIS) */ rgw_fh->mtx.unlock(); unref(rgw_fh); } return -ENOTEMPTY; } else { /* delete object w/key "<bucket>/" (uxattrs), if any */ string oname{"/"}; RGWDeleteObjRequest req(cct, user->clone(), bkt_fh->bucket_name(), oname); rc = g_rgwlib->get_fe()->execute_req(&req); /* don't care if ENOENT */ unref(bkt_fh); } string bname{name}; RGWDeleteBucketRequest req(cct, user->clone(), bname); rc = g_rgwlib->get_fe()->execute_req(&req); if (! rc) { rc = req.get_ret(); } } else { /* * leaf object */ if (! rgw_fh) { /* XXX for now, peform a hard lookup to deduce the type of * object to be deleted ("foo" vs. "foo/")--also, ensures * atomicity at this endpoint */ struct rgw_file_handle *fh; rc = rgw_lookup(get_fs(), parent->get_fh(), name, &fh, nullptr /* st */, 0 /* mask */, RGW_LOOKUP_FLAG_NONE); if (!! rc) return rc; /* rgw_fh ref+ */ rgw_fh = get_rgwfh(fh); rgw_fh->mtx.lock(); /* LOCKED */ } std::string oname = rgw_fh->relative_object_name(); if (rgw_fh->is_dir()) { /* for the duration of our cache timer, trust positive * child cache */ if (rgw_fh->has_children()) { rgw_fh->mtx.unlock(); unref(rgw_fh); return(-ENOTEMPTY); } oname += "/"; } RGWDeleteObjRequest req(cct, user->clone(), parent->bucket_name(), oname); rc = g_rgwlib->get_fe()->execute_req(&req); if (! rc) { rc = req.get_ret(); } } /* ENOENT when raced with other s3 gateway */ if (! rc || rc == -ENOENT) { rgw_fh->flags |= RGWFileHandle::FLAG_DELETED; fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh, RGWFileHandle::FHCache::FLAG_LOCK); } if (! rc) { real_time t = real_clock::now(); parent->set_mtime(real_clock::to_timespec(t)); parent->set_ctime(real_clock::to_timespec(t)); } rgw_fh->mtx.unlock(); unref(rgw_fh); return rc; } /* RGWLibFS::unlink */ int RGWLibFS::rename(RGWFileHandle* src_fh, RGWFileHandle* dst_fh, const char *_src_name, const char *_dst_name) { /* XXX initial implementation: try-copy, and delete if copy * succeeds */ int rc = -EINVAL; real_time t; std::string src_name{_src_name}; std::string dst_name{_dst_name}; /* atomicity */ LookupFHResult fhr = lookup_fh(src_fh, _src_name, RGWFileHandle::FLAG_LOCK); RGWFileHandle* rgw_fh = get<0>(fhr); /* should not happen */ if (! rgw_fh) { ldout(get_context(), 0) << __func__ << " BUG no such src renaming path=" << src_name << dendl; goto out; } /* forbid renaming of directories (unreasonable at scale) */ if (rgw_fh->is_dir()) { ldout(get_context(), 12) << __func__ << " rejecting attempt to rename directory path=" << rgw_fh->full_object_name() << dendl; rc = -EPERM; goto unlock; } /* forbid renaming open files (violates intent, for now) */ if (rgw_fh->is_open()) { ldout(get_context(), 12) << __func__ << " rejecting attempt to rename open file path=" << rgw_fh->full_object_name() << dendl; rc = -EPERM; goto unlock; } t = real_clock::now(); for (int ix : {0, 1}) { switch (ix) { case 0: { RGWCopyObjRequest req(cct, user->clone(), src_fh, dst_fh, src_name, dst_name); int rc = g_rgwlib->get_fe()->execute_req(&req); if ((rc != 0) || ((rc = req.get_ret()) != 0)) { ldout(get_context(), 1) << __func__ << " rename step 0 failed src=" << src_fh->full_object_name() << " " << src_name << " dst=" << dst_fh->full_object_name() << " " << dst_name << "rc " << rc << dendl; goto unlock; } ldout(get_context(), 12) << __func__ << " rename step 0 success src=" << src_fh->full_object_name() << " " << src_name << " dst=" << dst_fh->full_object_name() << " " << dst_name << " rc " << rc << dendl; /* update dst change id */ dst_fh->set_times(t); } break; case 1: { rc = this->unlink(rgw_fh /* LOCKED */, _src_name, RGWFileHandle::FLAG_UNLINK_THIS); /* !LOCKED, -ref */ if (! rc) { ldout(get_context(), 12) << __func__ << " rename step 1 success src=" << src_fh->full_object_name() << " " << src_name << " dst=" << dst_fh->full_object_name() << " " << dst_name << " rc " << rc << dendl; /* update src change id */ src_fh->set_times(t); } else { ldout(get_context(), 1) << __func__ << " rename step 1 failed src=" << src_fh->full_object_name() << " " << src_name << " dst=" << dst_fh->full_object_name() << " " << dst_name << " rc " << rc << dendl; } } goto out; default: ceph_abort(); } /* switch */ } /* ix */ unlock: rgw_fh->mtx.unlock(); /* !LOCKED */ unref(rgw_fh); /* -ref */ out: return rc; } /* RGWLibFS::rename */ MkObjResult RGWLibFS::mkdir(RGWFileHandle* parent, const char *name, struct stat *st, uint32_t mask, uint32_t flags) { int rc, rc2; rgw_file_handle *lfh; rc = rgw_lookup(get_fs(), parent->get_fh(), name, &lfh, nullptr /* st */, 0 /* mask */, RGW_LOOKUP_FLAG_NONE); if (! rc) { /* conflict! */ rc = rgw_fh_rele(get_fs(), lfh, RGW_FH_RELE_FLAG_NONE); // ignore return code return MkObjResult{nullptr, -EEXIST}; } MkObjResult mkr{nullptr, -EINVAL}; LookupFHResult fhr; RGWFileHandle* rgw_fh = nullptr; buffer::list ux_key, ux_attrs; fhr = lookup_fh(parent, name, RGWFileHandle::FLAG_CREATE| RGWFileHandle::FLAG_DIRECTORY| RGWFileHandle::FLAG_LOCK); rgw_fh = get<0>(fhr); if (rgw_fh) { rgw_fh->create_stat(st, mask); rgw_fh->set_times(real_clock::now()); /* save attrs */ rgw_fh->encode_attrs(ux_key, ux_attrs); if (st) rgw_fh->stat(st, RGWFileHandle::FLAG_LOCKED); get<0>(mkr) = rgw_fh; } else { get<1>(mkr) = -EIO; return mkr; } if (parent->is_root()) { /* bucket */ string bname{name}; /* enforce S3 name restrictions */ rc = valid_fs_bucket_name(bname); if (rc != 0) { rgw_fh->flags |= RGWFileHandle::FLAG_DELETED; fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh, RGWFileHandle::FHCache::FLAG_LOCK); rgw_fh->mtx.unlock(); unref(rgw_fh); get<0>(mkr) = nullptr; get<1>(mkr) = rc; return mkr; } RGWCreateBucketRequest req(get_context(), user->clone(), bname); /* save attrs */ req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); } else { /* create an object representing the directory */ buffer::list bl; string dir_name = parent->format_child_name(name, true); /* need valid S3 name (characters, length <= 1024, etc) */ rc = valid_fs_object_name(dir_name); if (rc != 0) { rgw_fh->flags |= RGWFileHandle::FLAG_DELETED; fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh, RGWFileHandle::FHCache::FLAG_LOCK); rgw_fh->mtx.unlock(); unref(rgw_fh); get<0>(mkr) = nullptr; get<1>(mkr) = rc; return mkr; } RGWPutObjRequest req(get_context(), user->clone(), parent->bucket_name(), dir_name, bl); /* save attrs */ req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); } if (! ((rc == 0) && (rc2 == 0))) { /* op failed */ rgw_fh->flags |= RGWFileHandle::FLAG_DELETED; rgw_fh->mtx.unlock(); /* !LOCKED */ unref(rgw_fh); get<0>(mkr) = nullptr; /* fixup rc */ if (!rc) rc = rc2; } else { real_time t = real_clock::now(); parent->set_mtime(real_clock::to_timespec(t)); parent->set_ctime(real_clock::to_timespec(t)); rgw_fh->mtx.unlock(); /* !LOCKED */ } get<1>(mkr) = rc; return mkr; } /* RGWLibFS::mkdir */ MkObjResult RGWLibFS::create(RGWFileHandle* parent, const char *name, struct stat *st, uint32_t mask, uint32_t flags) { int rc, rc2; using std::get; rgw_file_handle *lfh; rc = rgw_lookup(get_fs(), parent->get_fh(), name, &lfh, nullptr /* st */, 0 /* mask */, RGW_LOOKUP_FLAG_NONE); if (! rc) { /* conflict! */ rc = rgw_fh_rele(get_fs(), lfh, RGW_FH_RELE_FLAG_NONE); // ignore return code return MkObjResult{nullptr, -EEXIST}; } /* expand and check name */ std::string obj_name = parent->format_child_name(name, false); rc = valid_fs_object_name(obj_name); if (rc != 0) { return MkObjResult{nullptr, rc}; } /* create it */ buffer::list bl; RGWPutObjRequest req(cct, user->clone(), parent->bucket_name(), obj_name, bl); MkObjResult mkr{nullptr, -EINVAL}; rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); if ((rc == 0) && (rc2 == 0)) { /* XXX atomicity */ LookupFHResult fhr = lookup_fh(parent, name, RGWFileHandle::FLAG_CREATE | RGWFileHandle::FLAG_LOCK); RGWFileHandle* rgw_fh = get<0>(fhr); if (rgw_fh) { if (get<1>(fhr) & RGWFileHandle::FLAG_CREATE) { /* fill in stat data */ real_time t = real_clock::now(); rgw_fh->create_stat(st, mask); rgw_fh->set_times(t); parent->set_mtime(real_clock::to_timespec(t)); parent->set_ctime(real_clock::to_timespec(t)); } if (st) (void) rgw_fh->stat(st, RGWFileHandle::FLAG_LOCKED); rgw_fh->set_etag(*(req.get_attr(RGW_ATTR_ETAG))); rgw_fh->set_acls(*(req.get_attr(RGW_ATTR_ACL))); get<0>(mkr) = rgw_fh; rgw_fh->file_ondisk_version = 0; // inital version rgw_fh->mtx.unlock(); } else rc = -EIO; } get<1>(mkr) = rc; /* case like : quota exceed will be considered as fail too*/ if(rc2 < 0) get<1>(mkr) = rc2; return mkr; } /* RGWLibFS::create */ MkObjResult RGWLibFS::symlink(RGWFileHandle* parent, const char *name, const char* link_path, struct stat *st, uint32_t mask, uint32_t flags) { int rc, rc2; using std::get; rgw_file_handle *lfh; rc = rgw_lookup(get_fs(), parent->get_fh(), name, &lfh, nullptr /* st */, 0 /* mask */, RGW_LOOKUP_FLAG_NONE); if (! rc) { /* conflict! */ rc = rgw_fh_rele(get_fs(), lfh, RGW_FH_RELE_FLAG_NONE); // ignore return code return MkObjResult{nullptr, -EEXIST}; } MkObjResult mkr{nullptr, -EINVAL}; LookupFHResult fhr; RGWFileHandle* rgw_fh = nullptr; buffer::list ux_key, ux_attrs; fhr = lookup_fh(parent, name, RGWFileHandle::FLAG_CREATE| RGWFileHandle::FLAG_SYMBOLIC_LINK| RGWFileHandle::FLAG_LOCK); rgw_fh = get<0>(fhr); if (rgw_fh) { rgw_fh->create_stat(st, mask); rgw_fh->set_times(real_clock::now()); /* save attrs */ rgw_fh->encode_attrs(ux_key, ux_attrs); if (st) rgw_fh->stat(st); get<0>(mkr) = rgw_fh; } else { get<1>(mkr) = -EIO; return mkr; } /* need valid S3 name (characters, length <= 1024, etc) */ rc = valid_fs_object_name(name); if (rc != 0) { rgw_fh->flags |= RGWFileHandle::FLAG_DELETED; fh_cache.remove(rgw_fh->fh.fh_hk.object, rgw_fh, RGWFileHandle::FHCache::FLAG_LOCK); rgw_fh->mtx.unlock(); unref(rgw_fh); get<0>(mkr) = nullptr; get<1>(mkr) = rc; return mkr; } string obj_name = std::string(name); /* create an object representing the directory */ buffer::list bl; /* XXXX */ #if 0 bl.push_back( buffer::create_static(len, static_cast<char*>(buffer))); #else bl.push_back( buffer::copy(link_path, strlen(link_path))); #endif RGWPutObjRequest req(get_context(), user->clone(), parent->bucket_name(), obj_name, bl); /* save attrs */ req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); if (! ((rc == 0) && (rc2 == 0))) { /* op failed */ rgw_fh->flags |= RGWFileHandle::FLAG_DELETED; rgw_fh->mtx.unlock(); /* !LOCKED */ unref(rgw_fh); get<0>(mkr) = nullptr; /* fixup rc */ if (!rc) rc = rc2; } else { real_time t = real_clock::now(); parent->set_mtime(real_clock::to_timespec(t)); parent->set_ctime(real_clock::to_timespec(t)); rgw_fh->mtx.unlock(); /* !LOCKED */ } get<1>(mkr) = rc; return mkr; } /* RGWLibFS::symlink */ int RGWLibFS::getattr(RGWFileHandle* rgw_fh, struct stat* st) { switch(rgw_fh->fh.fh_type) { case RGW_FS_TYPE_FILE: { if (rgw_fh->deleted()) return -ESTALE; } break; default: break; }; /* if rgw_fh is a directory, mtime will be advanced */ return rgw_fh->stat(st); } /* RGWLibFS::getattr */ int RGWLibFS::setattr(RGWFileHandle* rgw_fh, struct stat* st, uint32_t mask, uint32_t flags) { int rc, rc2; buffer::list ux_key, ux_attrs; buffer::list etag = rgw_fh->get_etag(); buffer::list acls = rgw_fh->get_acls(); lock_guard guard(rgw_fh->mtx); switch(rgw_fh->fh.fh_type) { case RGW_FS_TYPE_FILE: { if (rgw_fh->deleted()) return -ESTALE; } break; default: break; }; string obj_name{rgw_fh->relative_object_name()}; if (rgw_fh->is_dir() && (likely(! rgw_fh->is_bucket()))) { obj_name += "/"; } RGWSetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name); rgw_fh->create_stat(st, mask); rgw_fh->encode_attrs(ux_key, ux_attrs); /* save attrs */ req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); req.emplace_attr(RGW_ATTR_ETAG, std::move(etag)); req.emplace_attr(RGW_ATTR_ACL, std::move(acls)); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); if (rc == -ENOENT) { /* special case: materialize placeholder dir */ buffer::list bl; RGWPutObjRequest req(get_context(), user->clone(), rgw_fh->bucket_name(), obj_name, bl); rgw_fh->encode_attrs(ux_key, ux_attrs); /* because std::moved */ /* save attrs */ req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); } if ((rc != 0) || (rc2 != 0)) { return -EIO; } rgw_fh->set_ctime(real_clock::to_timespec(real_clock::now())); return 0; } /* RGWLibFS::setattr */ static inline std::string prefix_xattr_keystr(const rgw_xattrstr& key) { std::string keystr; keystr.reserve(sizeof(RGW_ATTR_META_PREFIX) + key.len); keystr += string{RGW_ATTR_META_PREFIX}; keystr += string{key.val, key.len}; return keystr; } static inline std::string_view unprefix_xattr_keystr(const std::string& key) { std::string_view svk{key}; auto pos = svk.find(RGW_ATTR_META_PREFIX); if (pos == std::string_view::npos) { return std::string_view{""}; } else if (pos == 0) { svk.remove_prefix(sizeof(RGW_ATTR_META_PREFIX)-1); } return svk; } int RGWLibFS::getxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist *attrs, rgw_getxattr_cb cb, void *cb_arg, uint32_t flags) { /* cannot store on fs_root, should not on buckets? */ if ((rgw_fh->is_bucket()) || (rgw_fh->is_root())) { return -EINVAL; } int rc, rc2, rc3; string obj_name{rgw_fh->relative_object_name2()}; RGWGetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name); for (uint32_t ix = 0; ix < attrs->xattr_cnt; ++ix) { auto& xattr = attrs->xattrs[ix]; /* pass exposed attr keys as given, else prefix */ std::string k = is_exposed_attr(xattr.key) ? std::string{xattr.key.val, xattr.key.len} : prefix_xattr_keystr(xattr.key); req.emplace_key(std::move(k)); } if (ldlog_p1(get_context(), ceph_subsys_rgw, 15)) { lsubdout(get_context(), rgw, 15) << __func__ << " get keys for: " << rgw_fh->object_name() << " keys:" << dendl; for (const auto& attr: req.get_attrs()) { lsubdout(get_context(), rgw, 15) << "\tkey: " << attr.first << dendl; } } rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); rc3 = ((rc == 0) && (rc2 == 0)) ? 0 : -EIO; /* call back w/xattr data */ if (rc3 == 0) { const auto& attrs = req.get_attrs(); for (const auto& attr : attrs) { if (!attr.second.has_value()) continue; const auto& k = attr.first; const auto& v = attr.second.value(); /* return exposed attr keys as given, else unprefix -- * yes, we could have memoized the exposed check, but * to be efficient it would need to be saved with * RGWGetAttrs::attrs, I think */ std::string_view svk = is_exposed_attr(rgw_xattrstr{const_cast<char*>(k.c_str()), uint32_t(k.length())}) ? k : unprefix_xattr_keystr(k); /* skip entries not matching prefix */ if (svk.empty()) continue; rgw_xattrstr xattr_k = { const_cast<char*>(svk.data()), uint32_t(svk.length())}; rgw_xattrstr xattr_v = {const_cast<char*>(const_cast<buffer::list&>(v).c_str()), uint32_t(v.length())}; rgw_xattr xattr = { xattr_k, xattr_v }; rgw_xattrlist xattrlist = { &xattr, 1 }; cb(&xattrlist, cb_arg, RGW_GETXATTR_FLAG_NONE); } } return rc3; } /* RGWLibFS::getxattrs */ int RGWLibFS::lsxattrs( RGWFileHandle* rgw_fh, rgw_xattrstr *filter_prefix, rgw_getxattr_cb cb, void *cb_arg, uint32_t flags) { /* cannot store on fs_root, should not on buckets? */ if ((rgw_fh->is_bucket()) || (rgw_fh->is_root())) { return -EINVAL; } int rc, rc2, rc3; string obj_name{rgw_fh->relative_object_name2()}; RGWGetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); rc3 = ((rc == 0) && (rc2 == 0)) ? 0 : -EIO; /* call back w/xattr data--check for eof */ if (rc3 == 0) { const auto& keys = req.get_attrs(); for (const auto& k : keys) { /* return exposed attr keys as given, else unprefix */ std::string_view svk = is_exposed_attr(rgw_xattrstr{const_cast<char*>(k.first.c_str()), uint32_t(k.first.length())}) ? k.first : unprefix_xattr_keystr(k.first); /* skip entries not matching prefix */ if (svk.empty()) continue; rgw_xattrstr xattr_k = { const_cast<char*>(svk.data()), uint32_t(svk.length())}; rgw_xattrstr xattr_v = { nullptr, 0 }; rgw_xattr xattr = { xattr_k, xattr_v }; rgw_xattrlist xattrlist = { &xattr, 1 }; auto cbr = cb(&xattrlist, cb_arg, RGW_LSXATTR_FLAG_NONE); if (cbr & RGW_LSXATTR_FLAG_STOP) break; } } return rc3; } /* RGWLibFS::lsxattrs */ int RGWLibFS::setxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist *attrs, uint32_t flags) { /* cannot store on fs_root, should not on buckets? */ if ((rgw_fh->is_bucket()) || (rgw_fh->is_root())) { return -EINVAL; } int rc, rc2; string obj_name{rgw_fh->relative_object_name2()}; RGWSetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name); for (uint32_t ix = 0; ix < attrs->xattr_cnt; ++ix) { auto& xattr = attrs->xattrs[ix]; buffer::list attr_bl; /* don't allow storing at RGW_ATTR_META_PREFIX */ if (! (xattr.key.len > 0)) continue; /* reject lexical match with any exposed attr */ if (is_exposed_attr(xattr.key)) continue; string k = prefix_xattr_keystr(xattr.key); attr_bl.append(xattr.val.val, xattr.val.len); req.emplace_attr(k.c_str(), std::move(attr_bl)); } /* don't send null requests */ if (! (req.get_attrs().size() > 0)) { return -EINVAL; } rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); return (((rc == 0) && (rc2 == 0)) ? 0 : -EIO); } /* RGWLibFS::setxattrs */ int RGWLibFS::rmxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs, uint32_t flags) { /* cannot store on fs_root, should not on buckets? */ if ((rgw_fh->is_bucket()) || (rgw_fh->is_root())) { return -EINVAL; } int rc, rc2; string obj_name{rgw_fh->relative_object_name2()}; RGWRMAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name); for (uint32_t ix = 0; ix < attrs->xattr_cnt; ++ix) { auto& xattr = attrs->xattrs[ix]; /* don't allow storing at RGW_ATTR_META_PREFIX */ if (! (xattr.key.len > 0)) { continue; } string k = prefix_xattr_keystr(xattr.key); req.emplace_key(std::move(k)); } /* don't send null requests */ if (! (req.get_attrs().size() > 0)) { return -EINVAL; } rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); return (((rc == 0) && (rc2 == 0)) ? 0 : -EIO); } /* RGWLibFS::rmxattrs */ /* called with rgw_fh->mtx held */ void RGWLibFS::update_fh(RGWFileHandle *rgw_fh) { int rc, rc2; string obj_name{rgw_fh->relative_object_name()}; buffer::list ux_key, ux_attrs; if (rgw_fh->is_dir() && (likely(! rgw_fh->is_bucket()))) { obj_name += "/"; } lsubdout(get_context(), rgw, 17) << __func__ << " update old versioned fh : " << obj_name << dendl; RGWSetAttrsRequest req(cct, user->clone(), rgw_fh->bucket_name(), obj_name); rgw_fh->encode_attrs(ux_key, ux_attrs, false); req.emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); req.emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); rc = g_rgwlib->get_fe()->execute_req(&req); rc2 = req.get_ret(); if ((rc != 0) || (rc2 != 0)) { lsubdout(get_context(), rgw, 17) << __func__ << " update fh failed : " << obj_name << dendl; } } /* RGWLibFS::update_fh */ void RGWLibFS::close() { state.flags |= FLAG_CLOSED; class ObjUnref { RGWLibFS* fs; public: explicit ObjUnref(RGWLibFS* _fs) : fs(_fs) {} void operator()(RGWFileHandle* fh) const { lsubdout(fs->get_context(), rgw, 5) << __PRETTY_FUNCTION__ << fh->name << " before ObjUnref refs=" << fh->get_refcnt() << dendl; fs->unref(fh); } }; /* force cache drain, forces objects to evict */ fh_cache.drain(ObjUnref(this), RGWFileHandle::FHCache::FLAG_LOCK); g_rgwlib->get_fe()->get_process()->unregister_fs(this); rele(); } /* RGWLibFS::close */ inline std::ostream& operator<<(std::ostream &os, fh_key const &fhk) { os << "<fh_key: bucket="; os << fhk.fh_hk.bucket; os << "; object="; os << fhk.fh_hk.object; os << ">"; return os; } inline std::ostream& operator<<(std::ostream &os, struct timespec const &ts) { os << "<timespec: tv_sec="; os << ts.tv_sec; os << "; tv_nsec="; os << ts.tv_nsec; os << ">"; return os; } std::ostream& operator<<(std::ostream &os, RGWLibFS::event const &ev) { os << "<event:"; switch (ev.t) { case RGWLibFS::event::type::READDIR: os << "type=READDIR;"; break; default: os << "type=UNKNOWN;"; break; }; os << "fid=" << ev.fhk.fh_hk.bucket << ":" << ev.fhk.fh_hk.object << ";ts=" << ev.ts << ">"; return os; } void RGWLibFS::gc() { using std::get; using directory = RGWFileHandle::directory; /* dirent invalidate timeout--basically, the upper-bound on * inconsistency with the S3 namespace */ auto expire_s = get_context()->_conf->rgw_nfs_namespace_expire_secs; /* max events to gc in one cycle */ uint32_t max_ev = get_context()->_conf->rgw_nfs_max_gc; struct timespec now, expire_ts; event_vector ve; bool stop = false; std::deque<event> &events = state.events; do { (void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); lsubdout(get_context(), rgw, 15) << "GC: top of expire loop" << " now=" << now << " expire_s=" << expire_s << dendl; { lock_guard guard(state.mtx); /* LOCKED */ lsubdout(get_context(), rgw, 15) << "GC: processing" << " count=" << events.size() << " events" << dendl; /* just return if no events */ if (events.empty()) { return; } uint32_t _max_ev = (events.size() < 500) ? max_ev : (events.size() / 4); for (uint32_t ix = 0; (ix < _max_ev) && (events.size() > 0); ++ix) { event& ev = events.front(); expire_ts = ev.ts; expire_ts.tv_sec += expire_s; if (expire_ts > now) { stop = true; break; } ve.push_back(ev); events.pop_front(); } } /* anon */ /* !LOCKED */ for (auto& ev : ve) { lsubdout(get_context(), rgw, 15) << "try-expire ev: " << ev << dendl; if (likely(ev.t == event::type::READDIR)) { RGWFileHandle* rgw_fh = lookup_handle(ev.fhk.fh_hk); lsubdout(get_context(), rgw, 15) << "ev rgw_fh: " << rgw_fh << dendl; if (rgw_fh) { RGWFileHandle::directory* d; if (unlikely(! rgw_fh->is_dir())) { lsubdout(get_context(), rgw, 0) << __func__ << " BUG non-directory found with READDIR event " << "(" << rgw_fh->bucket_name() << "," << rgw_fh->object_name() << ")" << dendl; goto rele; } /* maybe clear state */ d = get<directory>(&rgw_fh->variant_type); if (d) { struct timespec ev_ts = ev.ts; lock_guard guard(rgw_fh->mtx); struct timespec d_last_readdir = d->last_readdir; if (unlikely(ev_ts < d_last_readdir)) { /* readdir cycle in progress, don't invalidate */ lsubdout(get_context(), rgw, 15) << "GC: delay expiration for " << rgw_fh->object_name() << " ev.ts=" << ev_ts << " last_readdir=" << d_last_readdir << dendl; continue; } else { lsubdout(get_context(), rgw, 15) << "GC: expiring " << rgw_fh->object_name() << dendl; rgw_fh->clear_state(); rgw_fh->invalidate(); } } rele: unref(rgw_fh); } /* rgw_fh */ } /* event::type::READDIR */ } /* ev */ ve.clear(); } while (! (stop || shutdown)); } /* RGWLibFS::gc */ std::ostream& operator<<(std::ostream &os, RGWFileHandle const &rgw_fh) { const auto& fhk = rgw_fh.get_key(); const auto& fh = const_cast<RGWFileHandle&>(rgw_fh).get_fh(); os << "<RGWFileHandle:"; os << "addr=" << &rgw_fh << ";"; switch (fh->fh_type) { case RGW_FS_TYPE_DIRECTORY: os << "type=DIRECTORY;"; break; case RGW_FS_TYPE_FILE: os << "type=FILE;"; break; default: os << "type=UNKNOWN;"; break; }; os << "fid=" << fhk.fh_hk.bucket << ":" << fhk.fh_hk.object << ";"; os << "name=" << rgw_fh.object_name() << ";"; os << "refcnt=" << rgw_fh.get_refcnt() << ";"; os << ">"; return os; } RGWFileHandle::~RGWFileHandle() { /* !recycle case, handle may STILL be in handle table, BUT * the partition lock is not held in this path */ if (fh_hook.is_linked()) { fs->fh_cache.remove(fh.fh_hk.object, this, FHCache::FLAG_LOCK); } /* cond-unref parent */ if (parent && (! parent->is_mount())) { /* safe because if parent->unref causes its deletion, * there are a) by refcnt, no other objects/paths pointing * to it and b) by the semantics of valid iteration of * fh_lru (observed, e.g., by cohort_lru<T,...>::drain()) * no unsafe iterators reaching it either--n.b., this constraint * is binding oncode which may in future attempt to e.g., * cause the eviction of objects in LRU order */ (void) get_fs()->unref(parent); } } fh_key RGWFileHandle::make_fhk(const std::string& name) { std::string tenant = get_fs()->get_user()->user_id.to_str(); if (depth == 0) { /* S3 bucket -- assert mount-at-bucket case reaches here */ return fh_key(name, name, tenant); } else { std::string key_name = make_key_name(name.c_str()); return fh_key(fhk.fh_hk.bucket, key_name.c_str(), tenant); } } void RGWFileHandle::encode_attrs(ceph::buffer::list& ux_key1, ceph::buffer::list& ux_attrs1, bool inc_ov) { using ceph::encode; fh_key fhk(this->fh.fh_hk); encode(fhk, ux_key1); bool need_ondisk_version = (fh.fh_type == RGW_FS_TYPE_FILE || fh.fh_type == RGW_FS_TYPE_SYMBOLIC_LINK); if (need_ondisk_version && file_ondisk_version < 0) { file_ondisk_version = 0; } encode(*this, ux_attrs1); if (need_ondisk_version && inc_ov) { file_ondisk_version++; } } /* RGWFileHandle::encode_attrs */ DecodeAttrsResult RGWFileHandle::decode_attrs(const ceph::buffer::list* ux_key1, const ceph::buffer::list* ux_attrs1) { using ceph::decode; DecodeAttrsResult dar { false, false }; fh_key fhk; auto bl_iter_key1 = ux_key1->cbegin(); decode(fhk, bl_iter_key1); get<0>(dar) = true; // decode to a temporary file handle which may not be // copied to the current file handle if its file_ondisk_version // is not newer RGWFileHandle tmp_fh(fs); tmp_fh.fh.fh_type = fh.fh_type; auto bl_iter_unix1 = ux_attrs1->cbegin(); decode(tmp_fh, bl_iter_unix1); fh.fh_type = tmp_fh.fh.fh_type; // for file handles that represent files and whose file_ondisk_version // is newer, no updates are need, otherwise, go updating the current // file handle if (!((fh.fh_type == RGW_FS_TYPE_FILE || fh.fh_type == RGW_FS_TYPE_SYMBOLIC_LINK) && file_ondisk_version >= tmp_fh.file_ondisk_version)) { // make sure the following "encode" always encode a greater version file_ondisk_version = tmp_fh.file_ondisk_version + 1; state.dev = tmp_fh.state.dev; state.size = tmp_fh.state.size; state.nlink = tmp_fh.state.nlink; state.owner_uid = tmp_fh.state.owner_uid; state.owner_gid = tmp_fh.state.owner_gid; state.unix_mode = tmp_fh.state.unix_mode; state.ctime = tmp_fh.state.ctime; state.mtime = tmp_fh.state.mtime; state.atime = tmp_fh.state.atime; state.version = tmp_fh.state.version; } if (this->state.version < 2) { get<1>(dar) = true; } return dar; } /* RGWFileHandle::decode_attrs */ bool RGWFileHandle::reclaim(const cohort::lru::ObjectFactory* newobj_fac) { lsubdout(fs->get_context(), rgw, 17) << __func__ << " " << *this << dendl; auto factory = dynamic_cast<const RGWFileHandle::Factory*>(newobj_fac); if (factory == nullptr) { return false; } /* make sure the reclaiming object is the same partiton with newobject factory, * then we can recycle the object, and replace with newobject */ if (!fs->fh_cache.is_same_partition(factory->fhk.fh_hk.object, fh.fh_hk.object)) { return false; } /* in the non-delete case, handle may still be in handle table */ if (fh_hook.is_linked()) { /* in this case, we are being called from a context which holds * the partition lock */ fs->fh_cache.remove(fh.fh_hk.object, this, FHCache::FLAG_NONE); } return true; } /* RGWFileHandle::reclaim */ bool RGWFileHandle::has_children() const { if (unlikely(! is_dir())) return false; RGWRMdirCheck req(fs->get_context(), g_rgwlib->get_driver()->get_user(fs->get_user()->user_id), this); int rc = g_rgwlib->get_fe()->execute_req(&req); if (! rc) { return req.valid && req.has_children; } return false; } std::ostream& operator<<(std::ostream &os, RGWFileHandle::readdir_offset const &offset) { using boost::get; if (unlikely(!! get<uint64_t*>(&offset))) { uint64_t* ioff = get<uint64_t*>(offset); os << *ioff; } else os << get<const char*>(offset); return os; } int RGWFileHandle::readdir(rgw_readdir_cb rcb, void *cb_arg, readdir_offset offset, bool *eof, uint32_t flags) { using event = RGWLibFS::event; using boost::get; int rc = 0; struct timespec now; CephContext* cct = fs->get_context(); lsubdout(cct, rgw, 10) << __func__ << " readdir called on " << object_name() << dendl; directory* d = get<directory>(&variant_type); if (d) { (void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); /* !LOCKED */ lock_guard guard(mtx); d->last_readdir = now; } bool initial_off; char* mk{nullptr}; if (likely(!! get<const char*>(&offset))) { mk = const_cast<char*>(get<const char*>(offset)); initial_off = !mk; } else { initial_off = (*get<uint64_t*>(offset) == 0); } if (is_root()) { RGWListBucketsRequest req(cct, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id), this, rcb, cb_arg, offset); rc = g_rgwlib->get_fe()->execute_req(&req); if (! rc) { (void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); /* !LOCKED */ lock_guard guard(mtx); state.atime = now; if (initial_off) set_nlink(2); inc_nlink(req.d_count); *eof = req.eof(); } } else { RGWReaddirRequest req(cct, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id), this, rcb, cb_arg, offset); rc = g_rgwlib->get_fe()->execute_req(&req); if (! rc) { (void) clock_gettime(CLOCK_MONOTONIC_COARSE, &now); /* !LOCKED */ lock_guard guard(mtx); state.atime = now; if (initial_off) set_nlink(2); inc_nlink(req.d_count); *eof = req.eof(); } } event ev(event::type::READDIR, get_key(), state.atime); lock_guard sguard(fs->state.mtx); fs->state.push_event(ev); lsubdout(fs->get_context(), rgw, 15) << __func__ << " final link count=" << state.nlink << dendl; return rc; } /* RGWFileHandle::readdir */ int RGWFileHandle::write(uint64_t off, size_t len, size_t *bytes_written, void *buffer) { using std::get; using WriteCompletion = RGWLibFS::WriteCompletion; lock_guard guard(mtx); int rc = 0; file* f = get<file>(&variant_type); if (! f) return -EISDIR; if (deleted()) { lsubdout(fs->get_context(), rgw, 5) << __func__ << " write attempted on deleted object " << this->object_name() << dendl; /* zap write transaction, if any */ if (f->write_req) { delete f->write_req; f->write_req = nullptr; } return -ESTALE; } if (! f->write_req) { /* guard--we do not support (e.g., COW-backed) partial writes */ if (off != 0) { lsubdout(fs->get_context(), rgw, 5) << __func__ << " " << object_name() << " non-0 initial write position " << off << " (mounting with -o sync required)" << dendl; return -EIO; } const RGWProcessEnv& penv = g_rgwlib->get_fe()->get_process()->get_env(); /* start */ std::string object_name = relative_object_name(); f->write_req = new RGWWriteRequest(g_rgwlib->get_driver(), penv, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id), this, bucket_name(), object_name); rc = g_rgwlib->get_fe()->start_req(f->write_req); if (rc < 0) { lsubdout(fs->get_context(), rgw, 5) << __func__ << this->object_name() << " write start failed " << off << " (" << rc << ")" << dendl; /* zap failed write transaction */ delete f->write_req; f->write_req = nullptr; return -EIO; } else { if (stateless_open()) { /* start write timer */ f->write_req->timer_id = RGWLibFS::write_timer.add_event( std::chrono::seconds(RGWLibFS::write_completion_interval_s), WriteCompletion(*this)); } } } int overlap = 0; if ((static_cast<off_t>(off) < f->write_req->real_ofs) && ((f->write_req->real_ofs - off) <= len)) { overlap = f->write_req->real_ofs - off; off = f->write_req->real_ofs; buffer = static_cast<char*>(buffer) + overlap; len -= overlap; } buffer::list bl; /* XXXX */ #if 0 bl.push_back( buffer::create_static(len, static_cast<char*>(buffer))); #else bl.push_back( buffer::copy(static_cast<char*>(buffer), len)); #endif f->write_req->put_data(off, bl); rc = f->write_req->exec_continue(); if (rc == 0) { size_t min_size = off + len; if (min_size > get_size()) set_size(min_size); if (stateless_open()) { /* bump write timer */ RGWLibFS::write_timer.adjust_event( f->write_req->timer_id, std::chrono::seconds(10)); } } else { /* continuation failed (e.g., non-contiguous write position) */ lsubdout(fs->get_context(), rgw, 5) << __func__ << object_name() << " failed write at position " << off << " (fails write transaction) " << dendl; /* zap failed write transaction */ delete f->write_req; f->write_req = nullptr; rc = -EIO; } *bytes_written = (rc == 0) ? (len + overlap) : 0; return rc; } /* RGWFileHandle::write */ int RGWFileHandle::write_finish(uint32_t flags) { unique_lock guard{mtx, std::defer_lock}; int rc = 0; if (! (flags & FLAG_LOCKED)) { guard.lock(); } file* f = get<file>(&variant_type); if (f && (f->write_req)) { lsubdout(fs->get_context(), rgw, 10) << __func__ << " finishing write trans on " << object_name() << dendl; rc = g_rgwlib->get_fe()->finish_req(f->write_req); if (! rc) { rc = f->write_req->get_ret(); } delete f->write_req; f->write_req = nullptr; } return rc; } /* RGWFileHandle::write_finish */ int RGWFileHandle::close() { lock_guard guard(mtx); int rc = write_finish(FLAG_LOCKED); flags &= ~FLAG_OPEN; flags &= ~FLAG_STATELESS_OPEN; return rc; } /* RGWFileHandle::close */ RGWFileHandle::file::~file() { delete write_req; } void RGWFileHandle::clear_state() { directory* d = get<directory>(&variant_type); if (d) { state.nlink = 2; d->last_marker = rgw_obj_key{}; } } void RGWFileHandle::advance_mtime(uint32_t flags) { /* intended for use on directories, fast-forward mtime so as to * ensure a new, higher value for the change attribute */ unique_lock uniq(mtx, std::defer_lock); if (likely(! (flags & RGWFileHandle::FLAG_LOCKED))) { uniq.lock(); } /* advance mtime only if stored mtime is older than the * configured namespace expiration */ auto now = real_clock::now(); auto cmptime = state.mtime; cmptime.tv_sec += fs->get_context()->_conf->rgw_nfs_namespace_expire_secs; if (cmptime < real_clock::to_timespec(now)) { /* sets ctime as well as mtime, to avoid masking updates should * ctime inexplicably hold a higher value */ set_times(now); } } void RGWFileHandle::invalidate() { RGWLibFS *fs = get_fs(); if (fs->invalidate_cb) { fs->invalidate_cb(fs->invalidate_arg, get_key().fh_hk); } } int RGWWriteRequest::exec_start() { req_state* state = get_state(); /* Object needs a bucket from this point */ state->object->set_bucket(state->bucket.get()); auto compression_type = get_driver()->get_compression_type(state->bucket->get_placement_rule()); /* not obviously supportable */ ceph_assert(! dlo_manifest); ceph_assert(! slo_info); perfcounter->inc(l_rgw_put); op_ret = -EINVAL; if (state->object->empty()) { ldout(state->cct, 0) << __func__ << " called on empty object" << dendl; goto done; } op_ret = get_params(null_yield); if (op_ret < 0) goto done; op_ret = get_system_versioning_params(state, &olh_epoch, &version_id); if (op_ret < 0) { goto done; } /* user-supplied MD5 check skipped (not supplied) */ /* early quota check skipped--we don't have size yet */ /* skipping user-supplied etag--we might have one in future, but * like data it and other attrs would arrive after open */ aio.emplace(state->cct->_conf->rgw_put_obj_min_window_size); if (state->bucket->versioning_enabled()) { if (!version_id.empty()) { state->object->set_instance(version_id); } else { state->object->gen_rand_obj_instance_name(); version_id = state->object->get_instance(); } } processor = get_driver()->get_atomic_writer(this, state->yield, state->object.get(), state->bucket_owner.get_id(), &state->dest_placement, 0, state->req_id); op_ret = processor->prepare(state->yield); if (op_ret < 0) { ldout(state->cct, 20) << "processor->prepare() returned ret=" << op_ret << dendl; goto done; } filter = &*processor; if (compression_type != "none") { plugin = Compressor::create(state->cct, compression_type); if (! plugin) { ldout(state->cct, 1) << "Cannot load plugin for rgw_compression_type " << compression_type << dendl; } else { compressor.emplace(state->cct, plugin, filter); filter = &*compressor; } } done: return op_ret; } /* exec_start */ int RGWWriteRequest::exec_continue() { req_state* state = get_state(); op_ret = 0; /* check guards (e.g., contig write) */ if (eio) { ldout(state->cct, 5) << " chunks arrived in wrong order" << " (mounting with -o sync required)" << dendl; return -EIO; } op_ret = state->bucket->check_quota(this, quota, real_ofs, null_yield, true); /* max_size exceed */ if (op_ret < 0) return -EIO; size_t len = data.length(); if (! len) return 0; hash.Update((const unsigned char *)data.c_str(), data.length()); op_ret = filter->process(std::move(data), ofs); if (op_ret < 0) { goto done; } bytes_written += len; done: return op_ret; } /* exec_continue */ int RGWWriteRequest::exec_finish() { buffer::list bl, aclbl, ux_key, ux_attrs; map<string, string>::iterator iter; char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1]; unsigned char m[CEPH_CRYPTO_MD5_DIGESTSIZE]; req_state* state = get_state(); size_t osize = rgw_fh->get_size(); struct timespec octime = rgw_fh->get_ctime(); struct timespec omtime = rgw_fh->get_mtime(); real_time appx_t = real_clock::now(); state->obj_size = bytes_written; perfcounter->inc(l_rgw_put_b, state->obj_size); // flush data in filters op_ret = filter->process({}, state->obj_size); if (op_ret < 0) { goto done; } op_ret = state->bucket->check_quota(this, quota, state->obj_size, null_yield, true); /* max_size exceed */ if (op_ret < 0) { goto done; } hash.Final(m); if (compressor && compressor->is_compressed()) { bufferlist tmp; RGWCompressionInfo cs_info; cs_info.compression_type = plugin->get_type_name(); cs_info.orig_size = state->obj_size; cs_info.blocks = std::move(compressor->get_compression_blocks()); encode(cs_info, tmp); attrs[RGW_ATTR_COMPRESSION] = tmp; ldpp_dout(this, 20) << "storing " << RGW_ATTR_COMPRESSION << " with type=" << cs_info.compression_type << ", orig_size=" << cs_info.orig_size << ", blocks=" << cs_info.blocks.size() << dendl; } buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5); etag = calc_md5; bl.append(etag.c_str(), etag.size() + 1); emplace_attr(RGW_ATTR_ETAG, std::move(bl)); policy.encode(aclbl); emplace_attr(RGW_ATTR_ACL, std::move(aclbl)); /* unix attrs */ rgw_fh->set_mtime(real_clock::to_timespec(appx_t)); rgw_fh->set_ctime(real_clock::to_timespec(appx_t)); rgw_fh->set_size(bytes_written); rgw_fh->encode_attrs(ux_key, ux_attrs); emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); emplace_attr(RGW_ATTR_UNIX1, std::move(ux_attrs)); for (iter = state->generic_attrs.begin(); iter != state->generic_attrs.end(); ++iter) { buffer::list& attrbl = attrs[iter->first]; const string& val = iter->second; attrbl.append(val.c_str(), val.size() + 1); } op_ret = rgw_get_request_metadata(this, state->cct, state->info, attrs); if (op_ret < 0) { goto done; } encode_delete_at_attr(delete_at, attrs); /* Add a custom metadata to expose the information whether an object * is an SLO or not. Appending the attribute must be performed AFTER * processing any input from user in order to prohibit overwriting. */ if (unlikely(!! slo_info)) { buffer::list slo_userindicator_bl; using ceph::encode; encode("True", slo_userindicator_bl); emplace_attr(RGW_ATTR_SLO_UINDICATOR, std::move(slo_userindicator_bl)); } op_ret = processor->complete(state->obj_size, etag, &mtime, real_time(), attrs, (delete_at ? *delete_at : real_time()), if_match, if_nomatch, nullptr, nullptr, nullptr, state->yield); if (op_ret != 0) { /* revert attr updates */ rgw_fh->set_mtime(omtime); rgw_fh->set_ctime(octime); rgw_fh->set_size(osize); } done: perfcounter->tinc(l_rgw_put_lat, state->time_elapsed()); return op_ret; } /* exec_finish */ } /* namespace rgw */ /* librgw */ extern "C" { void rgwfile_version(int *major, int *minor, int *extra) { if (major) *major = LIBRGW_FILE_VER_MAJOR; if (minor) *minor = LIBRGW_FILE_VER_MINOR; if (extra) *extra = LIBRGW_FILE_VER_EXTRA; } /* attach rgw namespace */ int rgw_mount(librgw_t rgw, const char *uid, const char *acc_key, const char *sec_key, struct rgw_fs **rgw_fs, uint32_t flags) { int rc = 0; /* stash access data for "mount" */ RGWLibFS* new_fs = new RGWLibFS(static_cast<CephContext*>(rgw), uid, acc_key, sec_key, "/"); ceph_assert(new_fs); const DoutPrefix dp(g_rgwlib->get_driver()->ctx(), dout_subsys, "rgw mount: "); rc = new_fs->authorize(&dp, g_rgwlib->get_driver()); if (rc != 0) { delete new_fs; return -EINVAL; } /* register fs for shared gc */ g_rgwlib->get_fe()->get_process()->register_fs(new_fs); struct rgw_fs *fs = new_fs->get_fs(); fs->rgw = rgw; /* XXX we no longer assume "/" is unique, but we aren't tracking the * roots atm */ *rgw_fs = fs; return 0; } int rgw_mount2(librgw_t rgw, const char *uid, const char *acc_key, const char *sec_key, const char *root, struct rgw_fs **rgw_fs, uint32_t flags) { int rc = 0; /* if the config has no value for path/root, choose "/" */ RGWLibFS* new_fs{nullptr}; if(root && (!strcmp(root, ""))) { /* stash access data for "mount" */ new_fs = new RGWLibFS( static_cast<CephContext*>(rgw), uid, acc_key, sec_key, "/"); } else { /* stash access data for "mount" */ new_fs = new RGWLibFS( static_cast<CephContext*>(rgw), uid, acc_key, sec_key, root); } ceph_assert(new_fs); /* should we be using ceph_assert? */ const DoutPrefix dp(g_rgwlib->get_driver()->ctx(), dout_subsys, "rgw mount2: "); rc = new_fs->authorize(&dp, g_rgwlib->get_driver()); if (rc != 0) { delete new_fs; return -EINVAL; } /* register fs for shared gc */ g_rgwlib->get_fe()->get_process()->register_fs(new_fs); struct rgw_fs *fs = new_fs->get_fs(); fs->rgw = rgw; /* XXX we no longer assume "/" is unique, but we aren't tracking the * roots atm */ *rgw_fs = fs; return 0; } /* register invalidate callbacks */ int rgw_register_invalidate(struct rgw_fs *rgw_fs, rgw_fh_callback_t cb, void *arg, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); return fs->register_invalidate(cb, arg, flags); } /* detach rgw namespace */ int rgw_umount(struct rgw_fs *rgw_fs, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); fs->close(); return 0; } /* get filesystem attributes */ int rgw_statfs(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, struct rgw_statvfs *vfs_st, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); struct rados_cluster_stat_t stats; RGWGetClusterStatReq req(fs->get_context(), g_rgwlib->get_driver()->get_user(fs->get_user()->user_id), stats); int rc = g_rgwlib->get_fe()->execute_req(&req); if (rc < 0) { lderr(fs->get_context()) << "ERROR: getting total cluster usage" << cpp_strerror(-rc) << dendl; return rc; } //Set block size to 1M. constexpr uint32_t CEPH_BLOCK_SHIFT = 20; vfs_st->f_bsize = 1 << CEPH_BLOCK_SHIFT; vfs_st->f_frsize = 1 << CEPH_BLOCK_SHIFT; vfs_st->f_blocks = stats.kb >> (CEPH_BLOCK_SHIFT - 10); vfs_st->f_bfree = stats.kb_avail >> (CEPH_BLOCK_SHIFT - 10); vfs_st->f_bavail = stats.kb_avail >> (CEPH_BLOCK_SHIFT - 10); vfs_st->f_files = stats.num_objects; vfs_st->f_ffree = -1; vfs_st->f_fsid[0] = fs->get_fsid(); vfs_st->f_fsid[1] = fs->get_fsid(); vfs_st->f_flag = 0; vfs_st->f_namemax = 4096; return 0; } /* generic create -- create an empty regular file */ int rgw_create(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char *name, struct stat *st, uint32_t mask, struct rgw_file_handle **fh, uint32_t posix_flags, uint32_t flags) { using std::get; RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* parent = get_rgwfh(parent_fh); if ((! parent) || (parent->is_root()) || (parent->is_file())) { /* bad parent */ return -EINVAL; } MkObjResult fhr = fs->create(parent, name, st, mask, flags); RGWFileHandle *nfh = get<0>(fhr); // nullptr if !success if (nfh) *fh = nfh->get_fh(); return get<1>(fhr); } /* rgw_create */ /* create a symbolic link */ int rgw_symlink(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char *name, const char *link_path, struct stat *st, uint32_t mask, struct rgw_file_handle **fh, uint32_t posix_flags, uint32_t flags) { using std::get; RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* parent = get_rgwfh(parent_fh); if ((! parent) || (parent->is_root()) || (parent->is_file())) { /* bad parent */ return -EINVAL; } MkObjResult fhr = fs->symlink(parent, name, link_path, st, mask, flags); RGWFileHandle *nfh = get<0>(fhr); // nullptr if !success if (nfh) *fh = nfh->get_fh(); return get<1>(fhr); } /* rgw_symlink */ /* create a new directory */ int rgw_mkdir(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char *name, struct stat *st, uint32_t mask, struct rgw_file_handle **fh, uint32_t flags) { using std::get; RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* parent = get_rgwfh(parent_fh); if (! parent) { /* bad parent */ return -EINVAL; } MkObjResult fhr = fs->mkdir(parent, name, st, mask, flags); RGWFileHandle *nfh = get<0>(fhr); // nullptr if !success if (nfh) *fh = nfh->get_fh(); return get<1>(fhr); } /* rgw_mkdir */ /* rename object */ int rgw_rename(struct rgw_fs *rgw_fs, struct rgw_file_handle *src, const char* src_name, struct rgw_file_handle *dst, const char* dst_name, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* src_fh = get_rgwfh(src); RGWFileHandle* dst_fh = get_rgwfh(dst); return fs->rename(src_fh, dst_fh, src_name, dst_name); } /* remove file or directory */ int rgw_unlink(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char *name, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* parent = get_rgwfh(parent_fh); return fs->unlink(parent, name); } /* lookup object by name (POSIX style) */ int rgw_lookup(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char* path, struct rgw_file_handle **fh, struct stat *st, uint32_t mask, uint32_t flags) { //CephContext* cct = static_cast<CephContext*>(rgw_fs->rgw); RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* parent = get_rgwfh(parent_fh); if ((! parent) || (! parent->is_dir())) { /* bad parent */ return -EINVAL; } RGWFileHandle* rgw_fh; LookupFHResult fhr; if (parent->is_root()) { /* special: parent lookup--note lack of ref()! */ if (unlikely((strcmp(path, "..") == 0) || (strcmp(path, "/") == 0))) { rgw_fh = parent; } else { RGWLibFS::BucketStats bstat; fhr = fs->stat_bucket(parent, path, bstat, RGWFileHandle::FLAG_NONE); rgw_fh = get<0>(fhr); if (! rgw_fh) return -ENOENT; } } else { /* special: after readdir--note extra ref()! */ if (unlikely((strcmp(path, "..") == 0))) { rgw_fh = parent; lsubdout(fs->get_context(), rgw, 17) << __func__ << " BANG"<< *rgw_fh << dendl; fs->ref(rgw_fh); } else { enum rgw_fh_type fh_type = fh_type_of(flags); uint32_t sl_flags = (flags & RGW_LOOKUP_FLAG_RCB) ? RGWFileHandle::FLAG_IN_CB : RGWFileHandle::FLAG_EXACT_MATCH; bool fast_attrs= fs->get_context()->_conf->rgw_nfs_s3_fast_attrs; if ((flags & RGW_LOOKUP_FLAG_RCB) && fast_attrs) { /* FAKE STAT--this should mean, interpolate special * owner, group, and perms masks */ fhr = fs->fake_leaf(parent, path, fh_type, st, mask, sl_flags); } else { if ((fh_type == RGW_FS_TYPE_DIRECTORY) && fast_attrs) { /* trust cached dir, if present */ fhr = fs->lookup_fh(parent, path, RGWFileHandle::FLAG_DIRECTORY); if (get<0>(fhr)) { rgw_fh = get<0>(fhr); goto done; } } fhr = fs->stat_leaf(parent, path, fh_type, sl_flags); } if (! get<0>(fhr)) { if (! (flags & RGW_LOOKUP_FLAG_CREATE)) return -ENOENT; else fhr = fs->lookup_fh(parent, path, RGWFileHandle::FLAG_CREATE); } rgw_fh = get<0>(fhr); } } /* !root */ done: struct rgw_file_handle *rfh = rgw_fh->get_fh(); *fh = rfh; return 0; } /* rgw_lookup */ /* lookup object by handle (NFS style) */ int rgw_lookup_handle(struct rgw_fs *rgw_fs, struct rgw_fh_hk *fh_hk, struct rgw_file_handle **fh, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = fs->lookup_handle(*fh_hk); if (! rgw_fh) { /* not found */ return -ENOENT; } struct rgw_file_handle *rfh = rgw_fh->get_fh(); *fh = rfh; return 0; } /* * release file handle */ int rgw_fh_rele(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); lsubdout(fs->get_context(), rgw, 17) << __func__ << " " << *rgw_fh << dendl; fs->unref(rgw_fh); return 0; } /* get unix attributes for object */ int rgw_getattr(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, struct stat *st, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->getattr(rgw_fh, st); } /* set unix attributes for object */ int rgw_setattr(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, struct stat *st, uint32_t mask, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->setattr(rgw_fh, st, mask, flags); } /* truncate file */ int rgw_truncate(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint64_t size, uint32_t flags) { return 0; } /* open file */ int rgw_open(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint32_t posix_flags, uint32_t flags) { RGWFileHandle* rgw_fh = get_rgwfh(fh); /* XXX * need to track specific opens--at least read opens and * a write open; we need to know when a write open is returned, * that closes a write transaction * * for now, we will support single-open only, it's preferable to * anything we can otherwise do without access to the NFS state */ if (! rgw_fh->is_file()) return -EISDIR; return rgw_fh->open(flags); } /* close file */ int rgw_close(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); int rc = rgw_fh->close(/* XXX */); if (flags & RGW_CLOSE_FLAG_RELE) fs->unref(rgw_fh); return rc; } int rgw_readdir(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, uint64_t *offset, rgw_readdir_cb rcb, void *cb_arg, bool *eof, uint32_t flags) { RGWFileHandle* parent = get_rgwfh(parent_fh); if (! parent) { /* bad parent */ return -EINVAL; } lsubdout(parent->get_fs()->get_context(), rgw, 15) << __func__ << " offset=" << *offset << dendl; if ((*offset == 0) && (flags & RGW_READDIR_FLAG_DOTDOT)) { /* send '.' and '..' with their NFS-defined offsets */ rcb(".", cb_arg, 1, nullptr, 0, RGW_LOOKUP_FLAG_DIR); rcb("..", cb_arg, 2, nullptr, 0, RGW_LOOKUP_FLAG_DIR); } int rc = parent->readdir(rcb, cb_arg, offset, eof, flags); return rc; } /* rgw_readdir */ /* enumeration continuing from name */ int rgw_readdir2(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char *name, rgw_readdir_cb rcb, void *cb_arg, bool *eof, uint32_t flags) { RGWFileHandle* parent = get_rgwfh(parent_fh); if (! parent) { /* bad parent */ return -EINVAL; } lsubdout(parent->get_fs()->get_context(), rgw, 15) << __func__ << " offset=" << ((name) ? name : "(nil)") << dendl; if ((! name) && (flags & RGW_READDIR_FLAG_DOTDOT)) { /* send '.' and '..' with their NFS-defined offsets */ rcb(".", cb_arg, 1, nullptr, 0, RGW_LOOKUP_FLAG_DIR); rcb("..", cb_arg, 2, nullptr, 0, RGW_LOOKUP_FLAG_DIR); } int rc = parent->readdir(rcb, cb_arg, name, eof, flags); return rc; } /* rgw_readdir2 */ /* project offset of dirent name */ int rgw_dirent_offset(struct rgw_fs *rgw_fs, struct rgw_file_handle *parent_fh, const char *name, int64_t *offset, uint32_t flags) { RGWFileHandle* parent = get_rgwfh(parent_fh); if ((! parent)) { /* bad parent */ return -EINVAL; } std::string sname{name}; int rc = parent->offset_of(sname, offset, flags); return rc; } /* read data from file */ int rgw_read(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint64_t offset, size_t length, size_t *bytes_read, void *buffer, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->read(rgw_fh, offset, length, bytes_read, buffer, flags); } /* read symbolic link */ int rgw_readlink(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint64_t offset, size_t length, size_t *bytes_read, void *buffer, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->readlink(rgw_fh, offset, length, bytes_read, buffer, flags); } /* write data to file */ int rgw_write(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint64_t offset, size_t length, size_t *bytes_written, void *buffer, uint32_t flags) { RGWFileHandle* rgw_fh = get_rgwfh(fh); int rc; *bytes_written = 0; if (! rgw_fh->is_file()) return -EISDIR; if (! rgw_fh->is_open()) { if (flags & RGW_OPEN_FLAG_V3) { rc = rgw_fh->open(flags); if (!! rc) return rc; } else return -EPERM; } rc = rgw_fh->write(offset, length, bytes_written, buffer); return rc; } /* read data from file (vector) */ class RGWReadV { buffer::list bl; struct rgw_vio* vio; public: RGWReadV(buffer::list& _bl, rgw_vio* _vio) : vio(_vio) { bl = std::move(_bl); } struct rgw_vio* get_vio() { return vio; } const auto& buffers() { return bl.buffers(); } unsigned /* XXX */ length() { return bl.length(); } }; void rgw_readv_rele(struct rgw_uio *uio, uint32_t flags) { RGWReadV* rdv = static_cast<RGWReadV*>(uio->uio_p1); rdv->~RGWReadV(); ::operator delete(rdv); } int rgw_readv(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, rgw_uio *uio, uint32_t flags) { #if 0 /* XXX */ CephContext* cct = static_cast<CephContext*>(rgw_fs->rgw); RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); if (! rgw_fh->is_file()) return -EINVAL; int rc = 0; buffer::list bl; RGWGetObjRequest req(cct, fs->get_user(), rgw_fh->bucket_name(), rgw_fh->object_name(), uio->uio_offset, uio->uio_resid, bl); req.do_hexdump = false; rc = g_rgwlib->get_fe()->execute_req(&req); if (! rc) { RGWReadV* rdv = static_cast<RGWReadV*>( ::operator new(sizeof(RGWReadV) + (bl.buffers().size() * sizeof(struct rgw_vio)))); (void) new (rdv) RGWReadV(bl, reinterpret_cast<rgw_vio*>(rdv+sizeof(RGWReadV))); uio->uio_p1 = rdv; uio->uio_cnt = rdv->buffers().size(); uio->uio_resid = rdv->length(); uio->uio_vio = rdv->get_vio(); uio->uio_rele = rgw_readv_rele; int ix = 0; auto& buffers = rdv->buffers(); for (auto& bp : buffers) { rgw_vio *vio = &(uio->uio_vio[ix]); vio->vio_base = const_cast<char*>(bp.c_str()); vio->vio_len = bp.length(); vio->vio_u1 = nullptr; vio->vio_p1 = nullptr; ++ix; } } return rc; #else return 0; #endif } /* write data to file (vector) */ int rgw_writev(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, rgw_uio *uio, uint32_t flags) { // not supported - rest of function is ignored return -ENOTSUP; CephContext* cct = static_cast<CephContext*>(rgw_fs->rgw); RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); if (! rgw_fh->is_file()) return -EINVAL; buffer::list bl; for (unsigned int ix = 0; ix < uio->uio_cnt; ++ix) { rgw_vio *vio = &(uio->uio_vio[ix]); bl.push_back( buffer::create_static(vio->vio_len, static_cast<char*>(vio->vio_base))); } std::string oname = rgw_fh->relative_object_name(); RGWPutObjRequest req(cct, g_rgwlib->get_driver()->get_user(fs->get_user()->user_id), rgw_fh->bucket_name(), oname, bl); int rc = g_rgwlib->get_fe()->execute_req(&req); /* XXX update size (in request) */ return rc; } /* sync written data */ int rgw_fsync(struct rgw_fs *rgw_fs, struct rgw_file_handle *handle, uint32_t flags) { return 0; } int rgw_commit(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, uint64_t offset, uint64_t length, uint32_t flags) { RGWFileHandle* rgw_fh = get_rgwfh(fh); return rgw_fh->commit(offset, length, RGWFileHandle::FLAG_NONE); } /* extended attributes */ int rgw_getxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, rgw_xattrlist *attrs, rgw_getxattr_cb cb, void *cb_arg, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->getxattrs(rgw_fh, attrs, cb, cb_arg, flags); } int rgw_lsxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, rgw_xattrstr *filter_prefix /* ignored */, rgw_getxattr_cb cb, void *cb_arg, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->lsxattrs(rgw_fh, filter_prefix, cb, cb_arg, flags); } int rgw_setxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, rgw_xattrlist *attrs, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->setxattrs(rgw_fh, attrs, flags); } int rgw_rmxattrs(struct rgw_fs *rgw_fs, struct rgw_file_handle *fh, rgw_xattrlist *attrs, uint32_t flags) { RGWLibFS *fs = static_cast<RGWLibFS*>(rgw_fs->fs_private); RGWFileHandle* rgw_fh = get_rgwfh(fh); return fs->rmxattrs(rgw_fh, attrs, flags); } } /* extern "C" */
75,443
26.060258
95
cc
null
ceph-main/src/rgw/rgw_file.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "include/rados/rgw_file.h" /* internal header */ #include <string.h> #include <string_view> #include <sys/stat.h> #include <stdint.h> #include <atomic> #include <chrono> #include <thread> #include <mutex> #include <vector> #include <deque> #include <algorithm> #include <functional> #include <boost/intrusive_ptr.hpp> #include <boost/range/adaptor/reversed.hpp> #include <boost/container/flat_map.hpp> #include <boost/variant.hpp> #include <boost/optional.hpp> #include "xxhash.h" #include "include/buffer.h" #include "common/cohort_lru.h" #include "common/ceph_timer.h" #include "rgw_common.h" #include "rgw_user.h" #include "rgw_lib.h" #include "rgw_ldap.h" #include "rgw_token.h" #include "rgw_putobj_processor.h" #include "rgw_aio_throttle.h" #include "rgw_compression.h" /* XXX * ASSERT_H somehow not defined after all the above (which bring * in common/debug.h [e.g., dout]) */ #include "include/ceph_assert.h" #define RGW_RWXMODE (S_IRWXU | S_IRWXG | S_IRWXO) #define RGW_RWMODE (RGW_RWXMODE & \ ~(S_IXUSR | S_IXGRP | S_IXOTH)) namespace rgw { template <typename T> static inline void ignore(T &&) {} namespace bi = boost::intrusive; class RGWLibFS; class RGWFileHandle; class RGWWriteRequest; inline bool operator <(const struct timespec& lhs, const struct timespec& rhs) { if (lhs.tv_sec == rhs.tv_sec) return lhs.tv_nsec < rhs.tv_nsec; else return lhs.tv_sec < rhs.tv_sec; } inline bool operator ==(const struct timespec& lhs, const struct timespec& rhs) { return ((lhs.tv_sec == rhs.tv_sec) && (lhs.tv_nsec == rhs.tv_nsec)); } /* * XXX * The current 64-bit, non-cryptographic hash used here is intended * for prototyping only. * * However, the invariant being prototyped is that objects be * identifiable by their hash components alone. We believe this can * be legitimately implemented using 128-hash values for bucket and * object components, together with a cluster-resident cryptographic * key. Since an MD5 or SHA-1 key is 128 bits and the (fast), * non-cryptographic CityHash128 hash algorithm takes a 128-bit seed, * speculatively we could use that for the final hash computations. */ struct fh_key { rgw_fh_hk fh_hk {}; uint32_t version; static constexpr uint64_t seed = 8675309; fh_key() : version(0) {} fh_key(const rgw_fh_hk& _hk) : fh_hk(_hk), version(0) { // nothing } fh_key(const uint64_t bk, const uint64_t ok) : version(0) { fh_hk.bucket = bk; fh_hk.object = ok; } fh_key(const uint64_t bk, const char *_o, const std::string& _t) : version(0) { fh_hk.bucket = bk; std::string to = _t + ":" + _o; fh_hk.object = XXH64(to.c_str(), to.length(), seed); } fh_key(const std::string& _b, const std::string& _o, const std::string& _t /* tenant */) : version(0) { std::string tb = _t + ":" + _b; std::string to = _t + ":" + _o; fh_hk.bucket = XXH64(tb.c_str(), tb.length(), seed); fh_hk.object = XXH64(to.c_str(), to.length(), seed); } void encode(buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(fh_hk.bucket, bl); encode(fh_hk.object, bl); encode((uint32_t)2, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(2, bl); decode(fh_hk.bucket, bl); decode(fh_hk.object, bl); if (struct_v >= 2) { decode(version, bl); } DECODE_FINISH(bl); } friend std::ostream& operator<<(std::ostream &os, fh_key const &fhk); }; /* fh_key */ WRITE_CLASS_ENCODER(fh_key); inline bool operator<(const fh_key& lhs, const fh_key& rhs) { return ((lhs.fh_hk.bucket < rhs.fh_hk.bucket) || ((lhs.fh_hk.bucket == rhs.fh_hk.bucket) && (lhs.fh_hk.object < rhs.fh_hk.object))); } inline bool operator>(const fh_key& lhs, const fh_key& rhs) { return (rhs < lhs); } inline bool operator==(const fh_key& lhs, const fh_key& rhs) { return ((lhs.fh_hk.bucket == rhs.fh_hk.bucket) && (lhs.fh_hk.object == rhs.fh_hk.object)); } inline bool operator!=(const fh_key& lhs, const fh_key& rhs) { return !(lhs == rhs); } inline bool operator<=(const fh_key& lhs, const fh_key& rhs) { return (lhs < rhs) || (lhs == rhs); } using boost::variant; using boost::container::flat_map; typedef std::tuple<bool, bool> DecodeAttrsResult; class RGWFileHandle : public cohort::lru::Object { struct rgw_file_handle fh; std::mutex mtx; RGWLibFS* fs; RGWFileHandle* bucket; RGWFileHandle* parent; std::atomic_int64_t file_ondisk_version; // version of unix attrs, file only /* const */ std::string name; /* XXX file or bucket name */ /* const */ fh_key fhk; using lock_guard = std::lock_guard<std::mutex>; using unique_lock = std::unique_lock<std::mutex>; /* TODO: keeping just the last marker is sufficient for * nfs-ganesha 2.4.5; in the near future, nfs-ganesha will * be able to hint the name of the next dirent required, * from which we can directly synthesize a RADOS marker. * using marker_cache_t = flat_map<uint64_t, rgw_obj_key>; */ struct State { uint64_t dev; uint64_t size; uint64_t nlink; uint32_t owner_uid; /* XXX need Unix attr */ uint32_t owner_gid; /* XXX need Unix attr */ mode_t unix_mode; struct timespec ctime; struct timespec mtime; struct timespec atime; uint32_t version; State() : dev(0), size(0), nlink(1), owner_uid(0), owner_gid(0), unix_mode(0), ctime{0,0}, mtime{0,0}, atime{0,0}, version(0) {} } state; struct file { RGWWriteRequest* write_req; file() : write_req(nullptr) {} ~file(); }; struct directory { static constexpr uint32_t FLAG_NONE = 0x0000; uint32_t flags; rgw_obj_key last_marker; struct timespec last_readdir; directory() : flags(FLAG_NONE), last_readdir{0,0} {} }; void clear_state(); void advance_mtime(uint32_t flags = FLAG_NONE); boost::variant<file, directory> variant_type; uint16_t depth; uint32_t flags; ceph::buffer::list etag; ceph::buffer::list acls; public: const static std::string root_name; static constexpr uint16_t MAX_DEPTH = 256; static constexpr uint32_t FLAG_NONE = 0x0000; static constexpr uint32_t FLAG_OPEN = 0x0001; static constexpr uint32_t FLAG_ROOT = 0x0002; static constexpr uint32_t FLAG_CREATE = 0x0004; static constexpr uint32_t FLAG_CREATING = 0x0008; static constexpr uint32_t FLAG_SYMBOLIC_LINK = 0x0009; static constexpr uint32_t FLAG_DIRECTORY = 0x0010; static constexpr uint32_t FLAG_BUCKET = 0x0020; static constexpr uint32_t FLAG_LOCK = 0x0040; static constexpr uint32_t FLAG_DELETED = 0x0080; static constexpr uint32_t FLAG_UNLINK_THIS = 0x0100; static constexpr uint32_t FLAG_LOCKED = 0x0200; static constexpr uint32_t FLAG_STATELESS_OPEN = 0x0400; static constexpr uint32_t FLAG_EXACT_MATCH = 0x0800; static constexpr uint32_t FLAG_MOUNT = 0x1000; static constexpr uint32_t FLAG_IN_CB = 0x2000; #define CREATE_FLAGS(x) \ ((x) & ~(RGWFileHandle::FLAG_CREATE|RGWFileHandle::FLAG_LOCK)) static constexpr uint32_t RCB_MASK = \ RGW_SETATTR_MTIME|RGW_SETATTR_CTIME|RGW_SETATTR_ATIME|RGW_SETATTR_SIZE; friend class RGWLibFS; private: explicit RGWFileHandle(RGWLibFS* _fs) : fs(_fs), bucket(nullptr), parent(nullptr), file_ondisk_version(-1), variant_type{directory()}, depth(0), flags(FLAG_NONE) { fh.fh_hk.bucket = 0; fh.fh_hk.object = 0; /* root */ fh.fh_type = RGW_FS_TYPE_DIRECTORY; variant_type = directory(); /* stat */ state.unix_mode = RGW_RWXMODE|S_IFDIR; /* pointer to self */ fh.fh_private = this; } uint64_t init_fsid(std::string& uid) { return XXH64(uid.c_str(), uid.length(), fh_key::seed); } void init_rootfs(std::string& fsid, const std::string& object_name, bool is_bucket) { /* fh_key */ fh.fh_hk.bucket = XXH64(fsid.c_str(), fsid.length(), fh_key::seed); fh.fh_hk.object = XXH64(object_name.c_str(), object_name.length(), fh_key::seed); fhk = fh.fh_hk; name = object_name; state.dev = init_fsid(fsid); if (is_bucket) { flags |= RGWFileHandle::FLAG_BUCKET | RGWFileHandle::FLAG_MOUNT; bucket = this; depth = 1; } else { flags |= RGWFileHandle::FLAG_ROOT | RGWFileHandle::FLAG_MOUNT; } } void encode(buffer::list& bl) const { ENCODE_START(3, 1, bl); encode(uint32_t(fh.fh_type), bl); encode(state.dev, bl); encode(state.size, bl); encode(state.nlink, bl); encode(state.owner_uid, bl); encode(state.owner_gid, bl); encode(state.unix_mode, bl); for (const auto& t : { state.ctime, state.mtime, state.atime }) { encode(real_clock::from_timespec(t), bl); } encode((uint32_t)2, bl); encode(file_ondisk_version.load(), bl); ENCODE_FINISH(bl); } //XXX: RGWFileHandle::decode method can only be called from // RGWFileHandle::decode_attrs, otherwise the file_ondisk_version // fied would be contaminated void decode(bufferlist::const_iterator& bl) { DECODE_START(3, bl); uint32_t fh_type; decode(fh_type, bl); if ((fh.fh_type != fh_type) && (fh_type == RGW_FS_TYPE_SYMBOLIC_LINK)) fh.fh_type = RGW_FS_TYPE_SYMBOLIC_LINK; decode(state.dev, bl); decode(state.size, bl); decode(state.nlink, bl); decode(state.owner_uid, bl); decode(state.owner_gid, bl); decode(state.unix_mode, bl); ceph::real_time enc_time; for (auto t : { &(state.ctime), &(state.mtime), &(state.atime) }) { decode(enc_time, bl); *t = real_clock::to_timespec(enc_time); } if (struct_v >= 2) { decode(state.version, bl); } if (struct_v >= 3) { int64_t fov; decode(fov, bl); file_ondisk_version = fov; } DECODE_FINISH(bl); } friend void encode(const RGWFileHandle& c, ::ceph::buffer::list &bl, uint64_t features); friend void decode(RGWFileHandle &c, ::ceph::bufferlist::const_iterator &p); public: RGWFileHandle(RGWLibFS* _fs, RGWFileHandle* _parent, const fh_key& _fhk, std::string& _name, uint32_t _flags) : fs(_fs), bucket(nullptr), parent(_parent), file_ondisk_version(-1), name(std::move(_name)), fhk(_fhk), flags(_flags) { if (parent->is_root()) { fh.fh_type = RGW_FS_TYPE_DIRECTORY; variant_type = directory(); flags |= FLAG_BUCKET; } else { bucket = parent->is_bucket() ? parent : parent->bucket; if (flags & FLAG_DIRECTORY) { fh.fh_type = RGW_FS_TYPE_DIRECTORY; variant_type = directory(); } else if(flags & FLAG_SYMBOLIC_LINK) { fh.fh_type = RGW_FS_TYPE_SYMBOLIC_LINK; variant_type = file(); } else { fh.fh_type = RGW_FS_TYPE_FILE; variant_type = file(); } } depth = parent->depth + 1; /* save constant fhk */ fh.fh_hk = fhk.fh_hk; /* XXX redundant in fh_hk */ /* inherits parent's fsid */ state.dev = parent->state.dev; switch (fh.fh_type) { case RGW_FS_TYPE_DIRECTORY: state.unix_mode = RGW_RWXMODE|S_IFDIR; /* virtual directories are always invalid */ advance_mtime(); break; case RGW_FS_TYPE_FILE: state.unix_mode = RGW_RWMODE|S_IFREG; break; case RGW_FS_TYPE_SYMBOLIC_LINK: state.unix_mode = RGW_RWMODE|S_IFLNK; break; default: break; } /* pointer to self */ fh.fh_private = this; } const std::string& get_name() const { return name; } const fh_key& get_key() const { return fhk; } directory* get_directory() { return boost::get<directory>(&variant_type); } size_t get_size() const { return state.size; } const char* stype() { return is_dir() ? "DIR" : "FILE"; } uint16_t get_depth() const { return depth; } struct rgw_file_handle* get_fh() { return &fh; } RGWLibFS* get_fs() { return fs; } RGWFileHandle* get_parent() { return parent; } uint32_t get_owner_uid() const { return state.owner_uid; } uint32_t get_owner_gid() const { return state.owner_gid; } struct timespec get_ctime() const { return state.ctime; } struct timespec get_mtime() const { return state.mtime; } const ceph::buffer::list& get_etag() const { return etag; } const ceph::buffer::list& get_acls() const { return acls; } void create_stat(struct stat* st, uint32_t mask) { if (mask & RGW_SETATTR_UID) state.owner_uid = st->st_uid; if (mask & RGW_SETATTR_GID) state.owner_gid = st->st_gid; if (mask & RGW_SETATTR_MODE) { switch (fh.fh_type) { case RGW_FS_TYPE_DIRECTORY: state.unix_mode = st->st_mode|S_IFDIR; break; case RGW_FS_TYPE_FILE: state.unix_mode = st->st_mode|S_IFREG; break; case RGW_FS_TYPE_SYMBOLIC_LINK: state.unix_mode = st->st_mode|S_IFLNK; break; default: break; } } if (mask & RGW_SETATTR_ATIME) state.atime = st->st_atim; if (mask & RGW_SETATTR_MTIME) { if (fh.fh_type != RGW_FS_TYPE_DIRECTORY) state.mtime = st->st_mtim; } if (mask & RGW_SETATTR_CTIME) state.ctime = st->st_ctim; } int stat(struct stat* st, uint32_t flags = FLAG_NONE) { /* partial Unix attrs */ /* FIPS zeroization audit 20191115: this memset is not security * related. */ memset(st, 0, sizeof(struct stat)); st->st_dev = state.dev; st->st_ino = fh.fh_hk.object; // XXX st->st_uid = state.owner_uid; st->st_gid = state.owner_gid; st->st_mode = state.unix_mode; switch (fh.fh_type) { case RGW_FS_TYPE_DIRECTORY: /* virtual directories are always invalid */ advance_mtime(flags); st->st_nlink = state.nlink; break; case RGW_FS_TYPE_FILE: st->st_nlink = 1; st->st_blksize = 4096; st->st_size = state.size; st->st_blocks = (state.size) / 512; break; case RGW_FS_TYPE_SYMBOLIC_LINK: st->st_nlink = 1; st->st_blksize = 4096; st->st_size = state.size; st->st_blocks = (state.size) / 512; break; default: break; } #ifdef HAVE_STAT_ST_MTIMESPEC_TV_NSEC st->st_atimespec = state.atime; st->st_mtimespec = state.mtime; st->st_ctimespec = state.ctime; #else st->st_atim = state.atime; st->st_mtim = state.mtime; st->st_ctim = state.ctime; #endif return 0; } const std::string& bucket_name() const { if (is_root()) return root_name; if (is_bucket()) return name; return bucket->object_name(); } const std::string& object_name() const { return name; } std::string full_object_name(bool omit_bucket = false) const { std::string path; std::vector<const std::string*> segments; int reserve = 0; const RGWFileHandle* tfh = this; while (tfh && !tfh->is_root() && !(tfh->is_bucket() && omit_bucket)) { segments.push_back(&tfh->object_name()); reserve += (1 + tfh->object_name().length()); tfh = tfh->parent; } int pos = 1; path.reserve(reserve); for (auto& s : boost::adaptors::reverse(segments)) { if (pos > 1) { path += "/"; } else { if (!omit_bucket && ((path.length() == 0) || (path.front() != '/'))) path += "/"; } path += *s; ++pos; } return path; } inline std::string relative_object_name() const { return full_object_name(true /* omit_bucket */); } inline std::string relative_object_name2() { std::string rname = full_object_name(true /* omit_bucket */); if (is_dir()) { rname += "/"; } return rname; } inline std::string format_child_name(const std::string& cbasename, bool is_dir) const { std::string child_name{relative_object_name()}; if ((child_name.size() > 0) && (child_name.back() != '/')) child_name += "/"; child_name += cbasename; if (is_dir) child_name += "/"; return child_name; } inline std::string make_key_name(const char *name) const { std::string key_name{full_object_name()}; if (key_name.length() > 0) key_name += "/"; key_name += name; return key_name; } fh_key make_fhk(const std::string& name); void add_marker(uint64_t off, const rgw_obj_key& marker, uint8_t obj_type) { using std::get; directory* d = get<directory>(&variant_type); if (d) { unique_lock guard(mtx); d->last_marker = marker; } } const rgw_obj_key* find_marker(uint64_t off) const { using std::get; if (off > 0) { const directory* d = get<directory>(&variant_type); if (d ) { return &d->last_marker; } } return nullptr; } int offset_of(const std::string& name, int64_t *offset, uint32_t flags) { if (unlikely(! is_dir())) { return -EINVAL; } *offset = XXH64(name.c_str(), name.length(), fh_key::seed); return 0; } bool is_open() const { return flags & FLAG_OPEN; } bool is_root() const { return flags & FLAG_ROOT; } bool is_mount() const { return flags & FLAG_MOUNT; } bool is_bucket() const { return flags & FLAG_BUCKET; } bool is_object() const { return !is_bucket(); } bool is_file() const { return (fh.fh_type == RGW_FS_TYPE_FILE); } bool is_dir() const { return (fh.fh_type == RGW_FS_TYPE_DIRECTORY); } bool is_link() const { return (fh.fh_type == RGW_FS_TYPE_SYMBOLIC_LINK); } bool creating() const { return flags & FLAG_CREATING; } bool deleted() const { return flags & FLAG_DELETED; } bool stateless_open() const { return flags & FLAG_STATELESS_OPEN; } bool has_children() const; int open(uint32_t gsh_flags) { lock_guard guard(mtx); if (! is_open()) { if (gsh_flags & RGW_OPEN_FLAG_V3) { flags |= FLAG_STATELESS_OPEN; } flags |= FLAG_OPEN; return 0; } return -EPERM; } typedef boost::variant<uint64_t*, const char*> readdir_offset; int readdir(rgw_readdir_cb rcb, void *cb_arg, readdir_offset offset, bool *eof, uint32_t flags); int write(uint64_t off, size_t len, size_t *nbytes, void *buffer); int commit(uint64_t offset, uint64_t length, uint32_t flags) { /* NFS3 and NFSv4 COMMIT implementation * the current atomic update strategy doesn't actually permit * clients to read-stable until either CLOSE (NFSv4+) or the * expiration of the active write timer (NFS3). In the * interim, the client may send an arbitrary number of COMMIT * operations which must return a success result */ return 0; } int write_finish(uint32_t flags = FLAG_NONE); int close(); void open_for_create() { lock_guard guard(mtx); flags |= FLAG_CREATING; } void clear_creating() { lock_guard guard(mtx); flags &= ~FLAG_CREATING; } void inc_nlink(const uint64_t n) { state.nlink += n; } void set_nlink(const uint64_t n) { state.nlink = n; } void set_size(const size_t size) { state.size = size; } void set_times(const struct timespec &ts) { state.ctime = ts; state.mtime = state.ctime; state.atime = state.ctime; } void set_times(real_time t) { set_times(real_clock::to_timespec(t)); } void set_ctime(const struct timespec &ts) { state.ctime = ts; } void set_mtime(const struct timespec &ts) { state.mtime = ts; } void set_atime(const struct timespec &ts) { state.atime = ts; } void set_etag(const ceph::buffer::list& _etag ) { etag = _etag; } void set_acls(const ceph::buffer::list& _acls ) { acls = _acls; } void encode_attrs(ceph::buffer::list& ux_key1, ceph::buffer::list& ux_attrs1, bool inc_ov = true); DecodeAttrsResult decode_attrs(const ceph::buffer::list* ux_key1, const ceph::buffer::list* ux_attrs1); void invalidate(); bool reclaim(const cohort::lru::ObjectFactory* newobj_fac) override; typedef cohort::lru::LRU<std::mutex> FhLRU; struct FhLT { // for internal ordering bool operator()(const RGWFileHandle& lhs, const RGWFileHandle& rhs) const { return (lhs.get_key() < rhs.get_key()); } // for external search by fh_key bool operator()(const fh_key& k, const RGWFileHandle& fh) const { return k < fh.get_key(); } bool operator()(const RGWFileHandle& fh, const fh_key& k) const { return fh.get_key() < k; } }; struct FhEQ { bool operator()(const RGWFileHandle& lhs, const RGWFileHandle& rhs) const { return (lhs.get_key() == rhs.get_key()); } bool operator()(const fh_key& k, const RGWFileHandle& fh) const { return k == fh.get_key(); } bool operator()(const RGWFileHandle& fh, const fh_key& k) const { return fh.get_key() == k; } }; typedef bi::link_mode<bi::safe_link> link_mode; /* XXX normal */ #if defined(FHCACHE_AVL) typedef bi::avl_set_member_hook<link_mode> tree_hook_type; #else /* RBT */ typedef bi::set_member_hook<link_mode> tree_hook_type; #endif tree_hook_type fh_hook; typedef bi::member_hook< RGWFileHandle, tree_hook_type, &RGWFileHandle::fh_hook> FhHook; #if defined(FHCACHE_AVL) typedef bi::avltree<RGWFileHandle, bi::compare<FhLT>, FhHook> FHTree; #else typedef bi::rbtree<RGWFileHandle, bi::compare<FhLT>, FhHook> FhTree; #endif typedef cohort::lru::TreeX<RGWFileHandle, FhTree, FhLT, FhEQ, fh_key, std::mutex> FHCache; ~RGWFileHandle() override; friend std::ostream& operator<<(std::ostream &os, RGWFileHandle const &rgw_fh); class Factory : public cohort::lru::ObjectFactory { public: RGWLibFS* fs; RGWFileHandle* parent; const fh_key& fhk; std::string& name; uint32_t flags; Factory() = delete; Factory(RGWLibFS* _fs, RGWFileHandle* _parent, const fh_key& _fhk, std::string& _name, uint32_t _flags) : fs(_fs), parent(_parent), fhk(_fhk), name(_name), flags(_flags) {} void recycle (cohort::lru::Object* o) override { /* re-use an existing object */ o->~Object(); // call lru::Object virtual dtor // placement new! new (o) RGWFileHandle(fs, parent, fhk, name, flags); } cohort::lru::Object* alloc() override { return new RGWFileHandle(fs, parent, fhk, name, flags); } }; /* Factory */ }; /* RGWFileHandle */ WRITE_CLASS_ENCODER(RGWFileHandle); inline RGWFileHandle* get_rgwfh(struct rgw_file_handle* fh) { return static_cast<RGWFileHandle*>(fh->fh_private); } inline enum rgw_fh_type fh_type_of(uint32_t flags) { enum rgw_fh_type fh_type; switch(flags & RGW_LOOKUP_TYPE_FLAGS) { case RGW_LOOKUP_FLAG_DIR: fh_type = RGW_FS_TYPE_DIRECTORY; break; case RGW_LOOKUP_FLAG_FILE: fh_type = RGW_FS_TYPE_FILE; break; default: fh_type = RGW_FS_TYPE_NIL; }; return fh_type; } typedef std::tuple<RGWFileHandle*, uint32_t> LookupFHResult; typedef std::tuple<RGWFileHandle*, int> MkObjResult; class RGWLibFS { CephContext* cct; struct rgw_fs fs{}; RGWFileHandle root_fh; rgw_fh_callback_t invalidate_cb; void *invalidate_arg; bool shutdown; mutable std::atomic<uint64_t> refcnt; RGWFileHandle::FHCache fh_cache; RGWFileHandle::FhLRU fh_lru; std::string uid; // should match user.user_id, iiuc std::unique_ptr<rgw::sal::User> user; RGWAccessKey key; // XXXX acc_key static std::atomic<uint32_t> fs_inst_counter; static uint32_t write_completion_interval_s; using lock_guard = std::lock_guard<std::mutex>; using unique_lock = std::unique_lock<std::mutex>; struct event { enum class type : uint8_t { READDIR } ; type t; const fh_key fhk; struct timespec ts; event(type t, const fh_key& k, const struct timespec& ts) : t(t), fhk(k), ts(ts) {} }; friend std::ostream& operator<<(std::ostream &os, RGWLibFS::event const &ev); using event_vector = /* boost::small_vector<event, 16> */ std::vector<event>; struct WriteCompletion { RGWFileHandle& rgw_fh; explicit WriteCompletion(RGWFileHandle& _fh) : rgw_fh(_fh) { rgw_fh.get_fs()->ref(&rgw_fh); } void operator()() { rgw_fh.close(); /* will finish in-progress write */ rgw_fh.get_fs()->unref(&rgw_fh); } }; static ceph::timer<ceph::mono_clock> write_timer; struct State { std::mutex mtx; std::atomic<uint32_t> flags; std::deque<event> events; State() : flags(0) {} void push_event(const event& ev) { events.push_back(ev); } } state; uint32_t new_inst() { return ++fs_inst_counter; } friend class RGWFileHandle; friend class RGWLibProcess; public: static constexpr uint32_t FLAG_NONE = 0x0000; static constexpr uint32_t FLAG_CLOSED = 0x0001; struct BucketStats { size_t size; size_t size_rounded; real_time creation_time; uint64_t num_entries; }; RGWLibFS(CephContext* _cct, const char *_uid, const char *_user_id, const char* _key, const char *root) : cct(_cct), root_fh(this), invalidate_cb(nullptr), invalidate_arg(nullptr), shutdown(false), refcnt(1), fh_cache(cct->_conf->rgw_nfs_fhcache_partitions, cct->_conf->rgw_nfs_fhcache_size), fh_lru(cct->_conf->rgw_nfs_lru_lanes, cct->_conf->rgw_nfs_lru_lane_hiwat), uid(_uid), key(_user_id, _key) { if (!root || !strcmp(root, "/")) { root_fh.init_rootfs(uid, RGWFileHandle::root_name, false); } else { root_fh.init_rootfs(uid, root, true); } /* pointer to self */ fs.fs_private = this; /* expose public root fh */ fs.root_fh = root_fh.get_fh(); new_inst(); } friend void intrusive_ptr_add_ref(const RGWLibFS* fs) { fs->refcnt.fetch_add(1, std::memory_order_relaxed); } friend void intrusive_ptr_release(const RGWLibFS* fs) { if (fs->refcnt.fetch_sub(1, std::memory_order_release) == 0) { std::atomic_thread_fence(std::memory_order_acquire); delete fs; } } RGWLibFS* ref() { intrusive_ptr_add_ref(this); return this; } inline void rele() { intrusive_ptr_release(this); } void stop() { shutdown = true; } void release_evict(RGWFileHandle* fh) { /* remove from cache, releases sentinel ref */ fh_cache.remove(fh->fh.fh_hk.object, fh, RGWFileHandle::FHCache::FLAG_LOCK); /* release call-path ref */ (void) fh_lru.unref(fh, cohort::lru::FLAG_NONE); } int authorize(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver) { int ret = driver->get_user_by_access_key(dpp, key.id, null_yield, &user); if (ret == 0) { RGWAccessKey* k = user->get_info().get_key(key.id); if (!k || (k->key != key.key)) return -EINVAL; if (user->get_info().suspended) return -ERR_USER_SUSPENDED; } else { /* try external authenticators (ldap for now) */ rgw::LDAPHelper* ldh = g_rgwlib->get_ldh(); /* !nullptr */ RGWToken token; /* boost filters and/or string_ref may throw on invalid input */ try { token = rgw::from_base64(key.id); } catch(...) { token = std::string(""); } if (token.valid() && (ldh->auth(token.id, token.key) == 0)) { /* try to driver user if it doesn't already exist */ if (user->load_user(dpp, null_yield) < 0) { int ret = user->store_user(dpp, null_yield, true); if (ret < 0) { lsubdout(get_context(), rgw, 10) << "NOTICE: failed to driver new user's info: ret=" << ret << dendl; } } } /* auth success */ } return ret; } /* authorize */ int register_invalidate(rgw_fh_callback_t cb, void *arg, uint32_t flags) { invalidate_cb = cb; invalidate_arg = arg; return 0; } /* find RGWFileHandle by id */ LookupFHResult lookup_fh(const fh_key& fhk, const uint32_t flags = RGWFileHandle::FLAG_NONE) { using std::get; // cast int32_t(RGWFileHandle::FLAG_NONE) due to strictness of Clang // the cast transfers a lvalue into a rvalue in the ctor // check the commit message for the full details LookupFHResult fhr { nullptr, uint32_t(RGWFileHandle::FLAG_NONE) }; RGWFileHandle::FHCache::Latch lat; bool fh_locked = flags & RGWFileHandle::FLAG_LOCKED; retry: RGWFileHandle* fh = fh_cache.find_latch(fhk.fh_hk.object /* partition selector*/, fhk /* key */, lat /* serializer */, RGWFileHandle::FHCache::FLAG_LOCK); /* LATCHED */ if (fh) { if (likely(! fh_locked)) fh->mtx.lock(); // XXX !RAII because may-return-LOCKED /* need initial ref from LRU (fast path) */ if (! fh_lru.ref(fh, cohort::lru::FLAG_INITIAL)) { lat.lock->unlock(); if (likely(! fh_locked)) fh->mtx.unlock(); goto retry; /* !LATCHED */ } /* LATCHED, LOCKED */ if (! (flags & RGWFileHandle::FLAG_LOCK)) fh->mtx.unlock(); /* ! LOCKED */ } lat.lock->unlock(); /* !LATCHED */ get<0>(fhr) = fh; if (fh) { lsubdout(get_context(), rgw, 17) << __func__ << " 1 " << *fh << dendl; } return fhr; } /* lookup_fh(const fh_key&) */ /* find or create an RGWFileHandle */ LookupFHResult lookup_fh(RGWFileHandle* parent, const char *name, const uint32_t flags = RGWFileHandle::FLAG_NONE) { using std::get; // cast int32_t(RGWFileHandle::FLAG_NONE) due to strictness of Clang // the cast transfers a lvalue into a rvalue in the ctor // check the commit message for the full details LookupFHResult fhr { nullptr, uint32_t(RGWFileHandle::FLAG_NONE) }; /* mount is stale? */ if (state.flags & FLAG_CLOSED) return fhr; RGWFileHandle::FHCache::Latch lat; bool fh_locked = flags & RGWFileHandle::FLAG_LOCKED; std::string obj_name{name}; std::string key_name{parent->make_key_name(name)}; fh_key fhk = parent->make_fhk(obj_name); lsubdout(get_context(), rgw, 10) << __func__ << " called on " << parent->object_name() << " for " << key_name << " (" << obj_name << ")" << " -> " << fhk << dendl; retry: RGWFileHandle* fh = fh_cache.find_latch(fhk.fh_hk.object /* partition selector*/, fhk /* key */, lat /* serializer */, RGWFileHandle::FHCache::FLAG_LOCK); /* LATCHED */ if (fh) { if (likely(! fh_locked)) fh->mtx.lock(); // XXX !RAII because may-return-LOCKED if (fh->flags & RGWFileHandle::FLAG_DELETED) { /* for now, delay briefly and retry */ lat.lock->unlock(); if (likely(! fh_locked)) fh->mtx.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(20)); goto retry; /* !LATCHED */ } /* need initial ref from LRU (fast path) */ if (! fh_lru.ref(fh, cohort::lru::FLAG_INITIAL)) { lat.lock->unlock(); if (likely(! fh_locked)) fh->mtx.unlock(); goto retry; /* !LATCHED */ } /* LATCHED, LOCKED */ if (! (flags & RGWFileHandle::FLAG_LOCK)) if (likely(! fh_locked)) fh->mtx.unlock(); /* ! LOCKED */ } else { /* make or re-use handle */ RGWFileHandle::Factory prototype(this, parent, fhk, obj_name, CREATE_FLAGS(flags)); uint32_t iflags{cohort::lru::FLAG_INITIAL}; fh = static_cast<RGWFileHandle*>( fh_lru.insert(&prototype, cohort::lru::Edge::MRU, iflags)); if (fh) { /* lock fh (LATCHED) */ if (flags & RGWFileHandle::FLAG_LOCK) fh->mtx.lock(); if (likely(! (iflags & cohort::lru::FLAG_RECYCLE))) { /* inserts at cached insert iterator, releasing latch */ fh_cache.insert_latched( fh, lat, RGWFileHandle::FHCache::FLAG_UNLOCK); } else { /* recycle step invalidates Latch */ fh_cache.insert( fhk.fh_hk.object, fh, RGWFileHandle::FHCache::FLAG_NONE); lat.lock->unlock(); /* !LATCHED */ } get<1>(fhr) |= RGWFileHandle::FLAG_CREATE; /* ref parent (non-initial ref cannot fail on valid object) */ if (! parent->is_mount()) { (void) fh_lru.ref(parent, cohort::lru::FLAG_NONE); } goto out; /* !LATCHED */ } else { lat.lock->unlock(); goto retry; /* !LATCHED */ } } lat.lock->unlock(); /* !LATCHED */ out: get<0>(fhr) = fh; if (fh) { lsubdout(get_context(), rgw, 17) << __func__ << " 2 " << *fh << dendl; } return fhr; } /* lookup_fh(RGWFileHandle*, const char *, const uint32_t) */ inline void unref(RGWFileHandle* fh) { if (likely(! fh->is_mount())) { (void) fh_lru.unref(fh, cohort::lru::FLAG_NONE); } } inline RGWFileHandle* ref(RGWFileHandle* fh) { if (likely(! fh->is_mount())) { fh_lru.ref(fh, cohort::lru::FLAG_NONE); } return fh; } int getattr(RGWFileHandle* rgw_fh, struct stat* st); int setattr(RGWFileHandle* rgw_fh, struct stat* st, uint32_t mask, uint32_t flags); int getxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs, rgw_getxattr_cb cb, void *cb_arg, uint32_t flags); int lsxattrs(RGWFileHandle* rgw_fh, rgw_xattrstr *filter_prefix, rgw_getxattr_cb cb, void *cb_arg, uint32_t flags); int setxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs, uint32_t flags); int rmxattrs(RGWFileHandle* rgw_fh, rgw_xattrlist* attrs, uint32_t flags); void update_fh(RGWFileHandle *rgw_fh); LookupFHResult stat_bucket(RGWFileHandle* parent, const char *path, RGWLibFS::BucketStats& bs, uint32_t flags); LookupFHResult fake_leaf(RGWFileHandle* parent, const char *path, enum rgw_fh_type type = RGW_FS_TYPE_NIL, struct stat *st = nullptr, uint32_t mask = 0, uint32_t flags = RGWFileHandle::FLAG_NONE); LookupFHResult stat_leaf(RGWFileHandle* parent, const char *path, enum rgw_fh_type type = RGW_FS_TYPE_NIL, uint32_t flags = RGWFileHandle::FLAG_NONE); int read(RGWFileHandle* rgw_fh, uint64_t offset, size_t length, size_t* bytes_read, void* buffer, uint32_t flags); int readlink(RGWFileHandle* rgw_fh, uint64_t offset, size_t length, size_t* bytes_read, void* buffer, uint32_t flags); int rename(RGWFileHandle* old_fh, RGWFileHandle* new_fh, const char *old_name, const char *new_name); MkObjResult create(RGWFileHandle* parent, const char *name, struct stat *st, uint32_t mask, uint32_t flags); MkObjResult symlink(RGWFileHandle* parent, const char *name, const char *link_path, struct stat *st, uint32_t mask, uint32_t flags); MkObjResult mkdir(RGWFileHandle* parent, const char *name, struct stat *st, uint32_t mask, uint32_t flags); int unlink(RGWFileHandle* rgw_fh, const char *name, uint32_t flags = FLAG_NONE); /* find existing RGWFileHandle */ RGWFileHandle* lookup_handle(struct rgw_fh_hk fh_hk) { if (state.flags & FLAG_CLOSED) return nullptr; RGWFileHandle::FHCache::Latch lat; fh_key fhk(fh_hk); retry: RGWFileHandle* fh = fh_cache.find_latch(fhk.fh_hk.object /* partition selector*/, fhk /* key */, lat /* serializer */, RGWFileHandle::FHCache::FLAG_LOCK); /* LATCHED */ if (! fh) { if (unlikely(fhk == root_fh.fh.fh_hk)) { /* lookup for root of this fs */ fh = &root_fh; goto out; } lsubdout(get_context(), rgw, 0) << __func__ << " handle lookup failed " << fhk << dendl; goto out; } fh->mtx.lock(); if (fh->flags & RGWFileHandle::FLAG_DELETED) { /* for now, delay briefly and retry */ lat.lock->unlock(); fh->mtx.unlock(); /* !LOCKED */ std::this_thread::sleep_for(std::chrono::milliseconds(20)); goto retry; /* !LATCHED */ } if (! fh_lru.ref(fh, cohort::lru::FLAG_INITIAL)) { lat.lock->unlock(); fh->mtx.unlock(); goto retry; /* !LATCHED */ } /* LATCHED */ fh->mtx.unlock(); /* !LOCKED */ out: lat.lock->unlock(); /* !LATCHED */ /* special case: lookup root_fh */ if (! fh) { if (unlikely(fh_hk == root_fh.fh.fh_hk)) { fh = &root_fh; } } return fh; } CephContext* get_context() { return cct; } struct rgw_fs* get_fs() { return &fs; } RGWFileHandle& get_fh() { return root_fh; } uint64_t get_fsid() { return root_fh.state.dev; } RGWUserInfo* get_user() { return &user->get_info(); } void update_user(const DoutPrefixProvider *dpp) { (void) g_rgwlib->get_driver()->get_user_by_access_key(dpp, key.id, null_yield, &user); } void close(); void gc(); }; /* RGWLibFS */ static inline std::string make_uri(const std::string& bucket_name, const std::string& object_name) { std::string uri("/"); uri.reserve(bucket_name.length() + object_name.length() + 2); uri += bucket_name; uri += "/"; uri += object_name; return uri; } /* read directory content (buckets) */ class RGWListBucketsRequest : public RGWLibRequest, public RGWListBuckets /* RGWOp */ { public: RGWFileHandle* rgw_fh; RGWFileHandle::readdir_offset offset; void* cb_arg; rgw_readdir_cb rcb; uint64_t* ioff; size_t ix; uint32_t d_count; bool rcb_eof; // caller forced early stop in readdir cycle RGWListBucketsRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, RGWFileHandle* _rgw_fh, rgw_readdir_cb _rcb, void* _cb_arg, RGWFileHandle::readdir_offset& _offset) : RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), offset(_offset), cb_arg(_cb_arg), rcb(_rcb), ioff(nullptr), ix(0), d_count(0), rcb_eof(false) { using boost::get; if (unlikely(!! get<uint64_t*>(&offset))) { ioff = get<uint64_t*>(offset); const auto& mk = rgw_fh->find_marker(*ioff); if (mk) { marker = mk->name; } } else { const char* mk = get<const char*>(offset); if (mk) { marker = mk; } } op = this; } bool only_bucket() override { return false; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; /* XXX derp derp derp */ state->relative_uri = "/"; state->info.request_uri = "/"; // XXX state->info.effective_uri = "/"; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } int get_params(optional_yield) override { limit = -1; /* no limit */ return 0; } void send_response_begin(bool has_buckets) override { sent_data = true; } void send_response_data(rgw::sal::BucketList& buckets) override { if (!sent_data) return; auto& m = buckets.get_buckets(); for (const auto& iter : m) { std::string_view marker{iter.first}; auto& ent = iter.second; if (! this->operator()(ent->get_name(), marker)) { /* caller cannot accept more */ lsubdout(cct, rgw, 5) << "ListBuckets rcb failed" << " dirent=" << ent->get_name() << " call count=" << ix << dendl; rcb_eof = true; return; } ++ix; } } /* send_response_data */ void send_response_end() override { // do nothing } int operator()(const std::string_view& name, const std::string_view& marker) { uint64_t off = XXH64(name.data(), name.length(), fh_key::seed); if (!! ioff) { *ioff = off; } /* update traversal cache */ rgw_fh->add_marker(off, rgw_obj_key{marker.data(), ""}, RGW_FS_TYPE_DIRECTORY); ++d_count; return rcb(name.data(), cb_arg, off, nullptr, 0, RGW_LOOKUP_FLAG_DIR); } bool eof() { using boost::get; if (unlikely(cct->_conf->subsys.should_gather(ceph_subsys_rgw, 15))) { bool is_offset = unlikely(! get<const char*>(&offset)) || !! get<const char*>(offset); lsubdout(cct, rgw, 15) << "READDIR offset: " << ((is_offset) ? offset : "(nil)") << " is_truncated: " << is_truncated << dendl; } return !is_truncated && !rcb_eof; } }; /* RGWListBucketsRequest */ /* read directory content (bucket objects) */ class RGWReaddirRequest : public RGWLibRequest, public RGWListBucket /* RGWOp */ { public: RGWFileHandle* rgw_fh; RGWFileHandle::readdir_offset offset; void* cb_arg; rgw_readdir_cb rcb; uint64_t* ioff; size_t ix; uint32_t d_count; bool rcb_eof; // caller forced early stop in readdir cycle RGWReaddirRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, RGWFileHandle* _rgw_fh, rgw_readdir_cb _rcb, void* _cb_arg, RGWFileHandle::readdir_offset& _offset) : RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), offset(_offset), cb_arg(_cb_arg), rcb(_rcb), ioff(nullptr), ix(0), d_count(0), rcb_eof(false) { using boost::get; if (unlikely(!! get<uint64_t*>(&offset))) { ioff = get<uint64_t*>(offset); const auto& mk = rgw_fh->find_marker(*ioff); if (mk) { marker = *mk; } } else { const char* mk = get<const char*>(offset); if (mk) { std::string tmark{rgw_fh->relative_object_name()}; if (tmark.length() > 0) tmark += "/"; tmark += mk; marker = rgw_obj_key{std::move(tmark), "", ""}; } } default_max = 1000; // XXX was being omitted op = this; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; /* XXX derp derp derp */ std::string uri = "/" + rgw_fh->bucket_name() + "/"; state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ prefix = rgw_fh->relative_object_name(); if (prefix.length() > 0) prefix += "/"; delimiter = '/'; return 0; } int operator()(const std::string_view name, const rgw_obj_key& marker, const ceph::real_time& t, const uint64_t fsz, uint8_t type) { assert(name.length() > 0); // all cases handled in callers /* hash offset of name in parent (short name) for NFS readdir cookie */ uint64_t off = XXH64(name.data(), name.length(), fh_key::seed); if (unlikely(!! ioff)) { *ioff = off; } /* update traversal cache */ rgw_fh->add_marker(off, marker, type); ++d_count; /* set c/mtime and size from bucket index entry */ struct stat st = {}; #ifdef HAVE_STAT_ST_MTIMESPEC_TV_NSEC st.st_atimespec = ceph::real_clock::to_timespec(t); st.st_mtimespec = st.st_atimespec; st.st_ctimespec = st.st_atimespec; #else st.st_atim = ceph::real_clock::to_timespec(t); st.st_mtim = st.st_atim; st.st_ctim = st.st_atim; #endif st.st_size = fsz; return rcb(name.data(), cb_arg, off, &st, RGWFileHandle::RCB_MASK, (type == RGW_FS_TYPE_DIRECTORY) ? RGW_LOOKUP_FLAG_DIR : RGW_LOOKUP_FLAG_FILE); } int get_params(optional_yield) override { max = default_max; return 0; } void send_response() override { req_state* state = get_state(); auto cnow = real_clock::now(); /* enumerate objs and common_prefixes in parallel, * avoiding increment on and end iterator, which is * undefined */ class DirIterator { std::vector<rgw_bucket_dir_entry>& objs; std::vector<rgw_bucket_dir_entry>::iterator obj_iter; std::map<std::string, bool>& common_prefixes; std::map<string, bool>::iterator cp_iter; boost::optional<std::string_view> obj_sref; boost::optional<std::string_view> cp_sref; bool _skip_cp; public: DirIterator(std::vector<rgw_bucket_dir_entry>& objs, std::map<string, bool>& common_prefixes) : objs(objs), common_prefixes(common_prefixes), _skip_cp(false) { obj_iter = objs.begin(); parse_obj(); cp_iter = common_prefixes.begin(); parse_cp(); } bool is_obj() { return (obj_iter != objs.end()); } bool is_cp(){ return (cp_iter != common_prefixes.end()); } bool eof() { return ((!is_obj()) && (!is_cp())); } void parse_obj() { if (is_obj()) { std::string_view sref{obj_iter->key.name}; size_t last_del = sref.find_last_of('/'); if (last_del != string::npos) sref.remove_prefix(last_del+1); obj_sref = sref; } } /* parse_obj */ void next_obj() { ++obj_iter; parse_obj(); } void parse_cp() { if (is_cp()) { /* leading-/ skip case */ if (cp_iter->first == "/") { _skip_cp = true; return; } else _skip_cp = false; /* it's safest to modify the element in place--a suffix-modifying * string_ref operation is problematic since ULP rgw_file callers * will ultimately need a c-string */ if (cp_iter->first.back() == '/') const_cast<std::string&>(cp_iter->first).pop_back(); std::string_view sref{cp_iter->first}; size_t last_del = sref.find_last_of('/'); if (last_del != string::npos) sref.remove_prefix(last_del+1); cp_sref = sref; } /* is_cp */ } /* parse_cp */ void next_cp() { ++cp_iter; parse_cp(); } bool skip_cp() { return _skip_cp; } bool entry_is_obj() { return (is_obj() && ((! is_cp()) || (obj_sref.get() < cp_sref.get()))); } std::string_view get_obj_sref() { return obj_sref.get(); } std::string_view get_cp_sref() { return cp_sref.get(); } std::vector<rgw_bucket_dir_entry>::iterator& get_obj_iter() { return obj_iter; } std::map<string, bool>::iterator& get_cp_iter() { return cp_iter; } }; /* DirIterator */ DirIterator di{objs, common_prefixes}; for (;;) { if (di.eof()) { break; // done } /* assert: one of is_obj() || is_cp() holds */ if (di.entry_is_obj()) { auto sref = di.get_obj_sref(); if (sref.empty()) { /* recursive list of a leaf dir (iirc), do nothing */ } else { /* send a file entry */ auto obj_entry = *(di.get_obj_iter()); lsubdout(cct, rgw, 15) << "RGWReaddirRequest " << __func__ << " " << "list uri=" << state->relative_uri << " " << " prefix=" << prefix << " " << " obj path=" << obj_entry.key.name << " (" << sref << ")" << "" << " mtime=" << real_clock::to_time_t(obj_entry.meta.mtime) << " size=" << obj_entry.meta.accounted_size << dendl; if (! this->operator()(sref, next_marker, obj_entry.meta.mtime, obj_entry.meta.accounted_size, RGW_FS_TYPE_FILE)) { /* caller cannot accept more */ lsubdout(cct, rgw, 5) << "readdir rcb caller signalled stop" << " dirent=" << sref.data() << " call count=" << ix << dendl; rcb_eof = true; return; } } di.next_obj(); // and advance object } else { /* send a dir entry */ if (! di.skip_cp()) { auto sref = di.get_cp_sref(); lsubdout(cct, rgw, 15) << "RGWReaddirRequest " << __func__ << " " << "list uri=" << state->relative_uri << " " << " prefix=" << prefix << " " << " cpref=" << sref << dendl; if (sref.empty()) { /* null path segment--could be created in S3 but has no NFS * interpretation */ } else { if (! this->operator()(sref, next_marker, cnow, 0, RGW_FS_TYPE_DIRECTORY)) { /* caller cannot accept more */ lsubdout(cct, rgw, 5) << "readdir rcb caller signalled stop" << " dirent=" << sref.data() << " call count=" << ix << dendl; rcb_eof = true; return; } } } di.next_cp(); // and advance common_prefixes } /* ! di.entry_is_obj() */ } /* for (;;) */ } virtual void send_versioned_response() { send_response(); } bool eof() { using boost::get; if (unlikely(cct->_conf->subsys.should_gather(ceph_subsys_rgw, 15))) { bool is_offset = unlikely(! get<const char*>(&offset)) || !! get<const char*>(offset); lsubdout(cct, rgw, 15) << "READDIR offset: " << ((is_offset) ? offset : "(nil)") << " next marker: " << next_marker << " is_truncated: " << is_truncated << dendl; } return !is_truncated && !rcb_eof; } }; /* RGWReaddirRequest */ /* dir has-children predicate (bucket objects) */ class RGWRMdirCheck : public RGWLibRequest, public RGWListBucket /* RGWOp */ { public: const RGWFileHandle* rgw_fh; bool valid; bool has_children; RGWRMdirCheck (CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const RGWFileHandle* _rgw_fh) : RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), valid(false), has_children(false) { default_max = 2; op = this; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; std::string uri = "/" + rgw_fh->bucket_name() + "/"; state->relative_uri = uri; state->info.request_uri = uri; state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ prefix = rgw_fh->relative_object_name(); if (prefix.length() > 0) prefix += "/"; delimiter = '/'; return 0; } int get_params(optional_yield) override { max = default_max; return 0; } void send_response() override { valid = true; if ((objs.size() > 1) || (! objs.empty() && (objs.front().key.name != prefix))) { has_children = true; return; } for (auto& iter : common_prefixes) { /* readdir never produces a name for this case */ if (iter.first == "/") continue; has_children = true; break; } } virtual void send_versioned_response() { send_response(); } }; /* RGWRMdirCheck */ /* create bucket */ class RGWCreateBucketRequest : public RGWLibRequest, public RGWCreateBucket /* RGWOp */ { public: const std::string& bucket_name; RGWCreateBucketRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, std::string& _bname) : RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname) { op = this; } bool only_bucket() override { return false; } int read_permissions(RGWOp* op_obj, optional_yield) override { /* we ARE a 'create bucket' request (cf. rgw_rest.cc, ll. 1305-6) */ return 0; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "PUT"; state->op = OP_PUT; string uri = "/" + bucket_name; /* XXX derp derp derp */ state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } int get_params(optional_yield) override { req_state* state = get_state(); RGWAccessControlPolicy_S3 s3policy(state->cct); /* we don't have (any) headers, so just create canned ACLs */ int ret = s3policy.create_canned(state->owner, state->bucket_owner, state->canned_acl); policy = s3policy; return ret; } void send_response() override { /* TODO: something (maybe) */ } }; /* RGWCreateBucketRequest */ /* delete bucket */ class RGWDeleteBucketRequest : public RGWLibRequest, public RGWDeleteBucket /* RGWOp */ { public: const std::string& bucket_name; RGWDeleteBucketRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, std::string& _bname) : RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname) { op = this; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "DELETE"; state->op = OP_DELETE; string uri = "/" + bucket_name; /* XXX derp derp derp */ state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } void send_response() override {} }; /* RGWDeleteBucketRequest */ /* put object */ class RGWPutObjRequest : public RGWLibRequest, public RGWPutObj /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; buffer::list& bl; /* XXX */ size_t bytes_written; RGWPutObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _bname, const std::string& _oname, buffer::list& _bl) : RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname), bl(_bl), bytes_written(0) { op = this; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED int rc = valid_s3_object_name(obj_name); if (rc != 0) return rc; return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "PUT"; state->op = OP_PUT; /* XXX derp derp derp */ std::string uri = make_uri(bucket_name, obj_name); state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ /* XXX required in RGWOp::execute() */ state->content_length = bl.length(); return 0; } int get_params(optional_yield) override { req_state* state = get_state(); RGWAccessControlPolicy_S3 s3policy(state->cct); /* we don't have (any) headers, so just create canned ACLs */ int ret = s3policy.create_canned(state->owner, state->bucket_owner, state->canned_acl); policy = s3policy; return ret; } int get_data(buffer::list& _bl) override { /* XXX for now, use sharing semantics */ _bl = std::move(bl); uint32_t len = _bl.length(); bytes_written += len; return len; } void send_response() override {} int verify_params() override { if (bl.length() > cct->_conf->rgw_max_put_size) return -ERR_TOO_LARGE; return 0; } buffer::list* get_attr(const std::string& k) { auto iter = attrs.find(k); return (iter != attrs.end()) ? &(iter->second) : nullptr; } }; /* RGWPutObjRequest */ /* get object */ class RGWReadRequest : public RGWLibRequest, public RGWGetObj /* RGWOp */ { public: RGWFileHandle* rgw_fh; void *ulp_buffer; size_t nread; size_t read_resid; /* initialize to len, <= sizeof(ulp_buffer) */ bool do_hexdump = false; RGWReadRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, RGWFileHandle* _rgw_fh, uint64_t off, uint64_t len, void *_ulp_buffer) : RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), ulp_buffer(_ulp_buffer), nread(0), read_resid(len) { op = this; /* fixup RGWGetObj (already know range parameters) */ RGWGetObj::range_parsed = true; RGWGetObj::get_data = true; // XXX RGWGetObj::partial_content = true; RGWGetObj::ofs = off; RGWGetObj::end = off + len; } bool only_bucket() override { return false; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; /* XXX derp derp derp */ state->relative_uri = make_uri(rgw_fh->bucket_name(), rgw_fh->relative_object_name()); state->info.request_uri = state->relative_uri; // XXX state->info.effective_uri = state->relative_uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } int get_params(optional_yield) override { return 0; } int send_response_data(ceph::buffer::list& bl, off_t bl_off, off_t bl_len) override { size_t bytes; for (auto& bp : bl.buffers()) { /* if for some reason bl_off indicates the start-of-data is not at * the current buffer::ptr, skip it and account */ if (bl_off > bp.length()) { bl_off -= bp.length(); continue; } /* read no more than read_resid */ bytes = std::min(read_resid, size_t(bp.length()-bl_off)); memcpy(static_cast<char*>(ulp_buffer)+nread, bp.c_str()+bl_off, bytes); read_resid -= bytes; /* reduce read_resid by bytes read */ nread += bytes; bl_off = 0; /* stop if we have no residual ulp_buffer */ if (! read_resid) break; } return 0; } int send_response_data_error(optional_yield) override { /* S3 implementation just sends nothing--there is no side effect * to simulate here */ return 0; } bool prefetch_data() override { return false; } }; /* RGWReadRequest */ /* delete object */ class RGWDeleteObjRequest : public RGWLibRequest, public RGWDeleteObj /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; RGWDeleteObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _bname, const std::string& _oname) : RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname) { op = this; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "DELETE"; state->op = OP_DELETE; /* XXX derp derp derp */ std::string uri = make_uri(bucket_name, obj_name); state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } void send_response() override {} }; /* RGWDeleteObjRequest */ class RGWStatObjRequest : public RGWLibRequest, public RGWGetObj /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; uint64_t _size; uint32_t flags; static constexpr uint32_t FLAG_NONE = 0x000; RGWStatObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _bname, const std::string& _oname, uint32_t _flags) : RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname), _size(0), flags(_flags) { op = this; /* fixup RGWGetObj (already know range parameters) */ RGWGetObj::range_parsed = true; RGWGetObj::get_data = false; // XXX RGWGetObj::partial_content = true; RGWGetObj::ofs = 0; RGWGetObj::end = UINT64_MAX; } const char* name() const override { return "stat_obj"; } RGWOpType get_type() override { return RGW_OP_STAT_OBJ; } real_time get_mtime() const { return lastmod; } /* attributes */ uint64_t get_size() { return _size; } real_time ctime() { return mod_time; } // XXX real_time mtime() { return mod_time; } std::map<string, bufferlist>& get_attrs() { return attrs; } buffer::list* get_attr(const std::string& k) { auto iter = attrs.find(k); return (iter != attrs.end()) ? &(iter->second) : nullptr; } bool only_bucket() override { return false; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; /* XXX derp derp derp */ state->relative_uri = make_uri(bucket_name, obj_name); state->info.request_uri = state->relative_uri; // XXX state->info.effective_uri = state->relative_uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } int get_params(optional_yield) override { return 0; } int send_response_data(ceph::buffer::list& _bl, off_t s_off, off_t e_off) override { /* NOP */ /* XXX save attrs? */ return 0; } int send_response_data_error(optional_yield) override { /* NOP */ return 0; } void execute(optional_yield y) override { RGWGetObj::execute(y); _size = get_state()->obj_size; } }; /* RGWStatObjRequest */ class RGWStatBucketRequest : public RGWLibRequest, public RGWStatBucket /* RGWOp */ { public: std::string uri; std::map<std::string, buffer::list> attrs; RGWLibFS::BucketStats& bs; RGWStatBucketRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _path, RGWLibFS::BucketStats& _stats) : RGWLibRequest(_cct, std::move(_user)), bs(_stats) { uri = "/" + _path; op = this; } buffer::list* get_attr(const std::string& k) { auto iter = attrs.find(k); return (iter != attrs.end()) ? &(iter->second) : nullptr; } real_time get_ctime() const { return bucket->get_creation_time(); } bool only_bucket() override { return false; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; /* XXX derp derp derp */ state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } virtual int get_params() { return 0; } void send_response() override { bucket->get_creation_time() = get_state()->bucket->get_info().creation_time; bs.size = bucket->get_size(); bs.size_rounded = bucket->get_size_rounded(); bs.creation_time = bucket->get_creation_time(); bs.num_entries = bucket->get_count(); std::swap(attrs, get_state()->bucket_attrs); } bool matched() { return (bucket->get_name().length() > 0); } }; /* RGWStatBucketRequest */ class RGWStatLeafRequest : public RGWLibRequest, public RGWListBucket /* RGWOp */ { public: RGWFileHandle* rgw_fh; std::string path; bool matched; bool is_dir; bool exact_matched; RGWStatLeafRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, RGWFileHandle* _rgw_fh, const std::string& _path) : RGWLibRequest(_cct, std::move(_user)), rgw_fh(_rgw_fh), path(_path), matched(false), is_dir(false), exact_matched(false) { default_max = 1000; // logical max {"foo", "foo/"} op = this; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; /* XXX derp derp derp */ std::string uri = "/" + rgw_fh->bucket_name() + "/"; state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ prefix = rgw_fh->relative_object_name(); if (prefix.length() > 0) prefix += "/"; prefix += path; delimiter = '/'; return 0; } int get_params(optional_yield) override { max = default_max; return 0; } void send_response() override { req_state* state = get_state(); // try objects for (const auto& iter : objs) { auto& name = iter.key.name; lsubdout(cct, rgw, 15) << "RGWStatLeafRequest " << __func__ << " " << "list uri=" << state->relative_uri << " " << " prefix=" << prefix << " " << " obj path=" << name << "" << " target = " << path << "" << dendl; /* XXX is there a missing match-dir case (trailing '/')? */ matched = true; if (name == path) { exact_matched = true; return; } } // try prefixes for (auto& iter : common_prefixes) { auto& name = iter.first; lsubdout(cct, rgw, 15) << "RGWStatLeafRequest " << __func__ << " " << "list uri=" << state->relative_uri << " " << " prefix=" << prefix << " " << " pref path=" << name << " (not chomped)" << " target = " << path << "" << dendl; matched = true; /* match-dir case (trailing '/') */ if (name == prefix + "/") { exact_matched = true; is_dir = true; return; } } } virtual void send_versioned_response() { send_response(); } }; /* RGWStatLeafRequest */ /* put object */ class RGWWriteRequest : public RGWLibContinuedReq, public RGWPutObj /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; RGWFileHandle* rgw_fh; std::optional<rgw::BlockingAioThrottle> aio; std::unique_ptr<rgw::sal::Writer> processor; rgw::sal::DataProcessor* filter; boost::optional<RGWPutObj_Compress> compressor; CompressorRef plugin; buffer::list data; uint64_t timer_id; MD5 hash; off_t real_ofs; size_t bytes_written; bool eio; RGWWriteRequest(rgw::sal::Driver* driver, const RGWProcessEnv& penv, std::unique_ptr<rgw::sal::User> _user, RGWFileHandle* _fh, const std::string& _bname, const std::string& _oname) : RGWLibContinuedReq(driver->ctx(), penv, std::move(_user)), bucket_name(_bname), obj_name(_oname), rgw_fh(_fh), filter(nullptr), timer_id(0), real_ofs(0), bytes_written(0), eio(false) { // in ctr this is not a virtual call // invoking this classes's header_init() (void) RGWWriteRequest::header_init(); op = this; // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "PUT"; state->op = OP_PUT; /* XXX derp derp derp */ std::string uri = make_uri(bucket_name, obj_name); state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } int get_params(optional_yield) override { req_state* state = get_state(); RGWAccessControlPolicy_S3 s3policy(state->cct); /* we don't have (any) headers, so just create canned ACLs */ int ret = s3policy.create_canned(state->owner, state->bucket_owner, state->canned_acl); policy = s3policy; return ret; } int get_data(buffer::list& _bl) override { /* XXX for now, use sharing semantics */ uint32_t len = data.length(); _bl = std::move(data); bytes_written += len; return len; } void put_data(off_t off, buffer::list& _bl) { if (off != real_ofs) { eio = true; } data = std::move(_bl); real_ofs += data.length(); ofs = off; /* consumed in exec_continue() */ } int exec_start() override; int exec_continue() override; int exec_finish() override; void send_response() override {} int verify_params() override { return 0; } }; /* RGWWriteRequest */ /* copy object */ class RGWCopyObjRequest : public RGWLibRequest, public RGWCopyObj /* RGWOp */ { public: RGWFileHandle* src_parent; RGWFileHandle* dst_parent; const std::string& src_name; const std::string& dst_name; RGWCopyObjRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, RGWFileHandle* _src_parent, RGWFileHandle* _dst_parent, const std::string& _src_name, const std::string& _dst_name) : RGWLibRequest(_cct, std::move(_user)), src_parent(_src_parent), dst_parent(_dst_parent), src_name(_src_name), dst_name(_dst_name) { /* all requests have this */ op = this; /* allow this request to replace selected attrs */ attrs_mod = rgw::sal::ATTRSMOD_MERGE; } bool only_bucket() override { return true; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "PUT"; // XXX check state->op = OP_PUT; state->src_bucket_name = src_parent->bucket_name(); state->bucket_name = dst_parent->bucket_name(); std::string dest_obj_name = dst_parent->format_child_name(dst_name, false); int rc = valid_s3_object_name(dest_obj_name); if (rc != 0) return rc; state->object = RGWHandler::driver->get_object(rgw_obj_key(dest_obj_name)); /* XXX and fixup key attr (could optimize w/string ref and * dest_obj_name) */ buffer::list ux_key; fh_key fhk = dst_parent->make_fhk(dst_name); rgw::encode(fhk, ux_key); emplace_attr(RGW_ATTR_UNIX_KEY1, std::move(ux_key)); #if 0 /* XXX needed? */ state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ #endif return 0; } int get_params(optional_yield) override { req_state* s = get_state(); RGWAccessControlPolicy_S3 s3policy(s->cct); /* we don't have (any) headers, so just create canned ACLs */ int ret = s3policy.create_canned(s->owner, s->bucket_owner, s->canned_acl); dest_policy = s3policy; /* src_object required before RGWCopyObj::verify_permissions() */ rgw_obj_key k = rgw_obj_key(src_name); s->src_object = s->bucket->get_object(k); s->object = s->src_object->clone(); // needed to avoid trap at rgw_op.cc:5150 return ret; } void send_response() override {} void send_partial_response(off_t ofs) override {} }; /* RGWCopyObjRequest */ class RGWGetAttrsRequest : public RGWLibRequest, public RGWGetAttrs /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; RGWGetAttrsRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _bname, const std::string& _oname) : RGWLibRequest(_cct, std::move(_user)), RGWGetAttrs(), bucket_name(_bname), obj_name(_oname) { op = this; } const flat_map<std::string, std::optional<buffer::list>>& get_attrs() { return attrs; } virtual bool only_bucket() { return false; } virtual int op_init() { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } virtual int header_init() { req_state* s = get_state(); s->info.method = "GET"; s->op = OP_GET; std::string uri = make_uri(bucket_name, obj_name); s->relative_uri = uri; s->info.request_uri = uri; s->info.effective_uri = uri; s->info.request_params = ""; s->info.domain = ""; /* XXX ? */ return 0; } virtual int get_params() { return 0; } virtual void send_response() {} }; /* RGWGetAttrsRequest */ class RGWSetAttrsRequest : public RGWLibRequest, public RGWSetAttrs /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; RGWSetAttrsRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _bname, const std::string& _oname) : RGWLibRequest(_cct, std::move(_user)), bucket_name(_bname), obj_name(_oname) { op = this; } const std::map<std::string, buffer::list>& get_attrs() { return attrs; } bool only_bucket() override { return false; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "PUT"; state->op = OP_PUT; /* XXX derp derp derp */ std::string uri = make_uri(bucket_name, obj_name); state->relative_uri = uri; state->info.request_uri = uri; // XXX state->info.effective_uri = uri; state->info.request_params = ""; state->info.domain = ""; /* XXX ? */ return 0; } int get_params(optional_yield) override { return 0; } void send_response() override {} }; /* RGWSetAttrsRequest */ class RGWRMAttrsRequest : public RGWLibRequest, public RGWRMAttrs /* RGWOp */ { public: const std::string& bucket_name; const std::string& obj_name; RGWRMAttrsRequest(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, const std::string& _bname, const std::string& _oname) : RGWLibRequest(_cct, std::move(_user)), RGWRMAttrs(), bucket_name(_bname), obj_name(_oname) { op = this; } const rgw::sal::Attrs& get_attrs() { return attrs; } virtual bool only_bucket() { return false; } virtual int op_init() { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } virtual int header_init() { req_state* s = get_state(); s->info.method = "DELETE"; s->op = OP_PUT; std::string uri = make_uri(bucket_name, obj_name); s->relative_uri = uri; s->info.request_uri = uri; s->info.effective_uri = uri; s->info.request_params = ""; s->info.domain = ""; /* XXX ? */ return 0; } virtual int get_params() { return 0; } virtual void send_response() {} }; /* RGWRMAttrsRequest */ /* * Send request to get the rados cluster stats */ class RGWGetClusterStatReq : public RGWLibRequest, public RGWGetClusterStat { public: struct rados_cluster_stat_t& stats_req; RGWGetClusterStatReq(CephContext* _cct, std::unique_ptr<rgw::sal::User> _user, rados_cluster_stat_t& _stats): RGWLibRequest(_cct, std::move(_user)), stats_req(_stats){ op = this; } int op_init() override { // assign driver, s, and dialect_handler // framework promises to call op_init after parent init RGWOp::init(RGWHandler::driver, get_state(), this); op = this; // assign self as op: REQUIRED return 0; } int header_init() override { req_state* state = get_state(); state->info.method = "GET"; state->op = OP_GET; return 0; } int get_params(optional_yield) override { return 0; } bool only_bucket() override { return false; } void send_response() override { stats_req.kb = stats_op.kb; stats_req.kb_avail = stats_op.kb_avail; stats_req.kb_used = stats_op.kb_used; stats_req.num_objects = stats_op.num_objects; } }; /* RGWGetClusterStatReq */ } /* namespace rgw */
77,679
26.179846
92
h
null
ceph-main/src/rgw/rgw_flight.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright 2023 IBM * * See file COPYING for licensing information. */ #include <iostream> #include <fstream> #include <mutex> #include <map> #include <algorithm> #include "arrow/type.h" #include "arrow/buffer.h" #include "arrow/util/string_view.h" #include "arrow/io/interfaces.h" #include "arrow/ipc/reader.h" #include "arrow/table.h" #include "arrow/flight/server.h" #include "parquet/arrow/reader.h" #include "common/dout.h" #include "rgw_op.h" #include "rgw_flight.h" #include "rgw_flight_frontend.h" namespace rgw::flight { // Ticket and FlightKey std::atomic<FlightKey> next_flight_key = null_flight_key; flt::Ticket FlightKeyToTicket(const FlightKey& key) { flt::Ticket result; result.ticket = std::to_string(key); return result; } arw::Result<FlightKey> TicketToFlightKey(const flt::Ticket& t) { try { return (FlightKey) std::stoul(t.ticket); } catch (std::invalid_argument const& ex) { return arw::Status::Invalid( "could not convert Ticket containing \"%s\" into a Flight Key", t.ticket); } catch (const std::out_of_range& ex) { return arw::Status::Invalid( "could not convert Ticket containing \"%s\" into a Flight Key due to range", t.ticket); } } // FlightData FlightData::FlightData(const std::string& _uri, const std::string& _tenant_name, const std::string& _bucket_name, const rgw_obj_key& _object_key, uint64_t _num_records, uint64_t _obj_size, std::shared_ptr<arw::Schema>& _schema, std::shared_ptr<const arw::KeyValueMetadata>& _kv_metadata, rgw_user _user_id) : key(++next_flight_key), /* expires(coarse_real_clock::now() + lifespan), */ uri(_uri), tenant_name(_tenant_name), bucket_name(_bucket_name), object_key(_object_key), num_records(_num_records), obj_size(_obj_size), schema(_schema), kv_metadata(_kv_metadata), user_id(_user_id) { } /**** FlightStore ****/ FlightStore::FlightStore(const DoutPrefix& _dp) : dp(_dp) { } FlightStore::~FlightStore() { } /**** MemoryFlightStore ****/ MemoryFlightStore::MemoryFlightStore(const DoutPrefix& _dp) : FlightStore(_dp) { } MemoryFlightStore::~MemoryFlightStore() { } FlightKey MemoryFlightStore::add_flight(FlightData&& flight) { std::pair<decltype(map)::iterator,bool> result; { const std::lock_guard lock(mtx); result = map.insert( {flight.key, std::move(flight)} ); } ceph_assertf(result.second, "unable to add FlightData to MemoryFlightStore"); // temporary until error handling return result.first->second.key; } arw::Result<FlightData> MemoryFlightStore::get_flight(const FlightKey& key) const { const std::lock_guard lock(mtx); auto i = map.find(key); if (i == map.cend()) { return arw::Status::KeyError("could not find Flight with Key %" PRIu32, key); } else { return i->second; } } // returns either the next FilghtData or, if at end, empty optional std::optional<FlightData> MemoryFlightStore::after_key(const FlightKey& key) const { std::optional<FlightData> result; { const std::lock_guard lock(mtx); auto i = map.upper_bound(key); if (i != map.end()) { result = i->second; } } return result; } int MemoryFlightStore::remove_flight(const FlightKey& key) { return 0; } int MemoryFlightStore::expire_flights() { return 0; } /**** FlightServer ****/ FlightServer::FlightServer(RGWProcessEnv& _env, FlightStore* _flight_store, const DoutPrefix& _dp) : env(_env), driver(env.driver), dp(_dp), flight_store(_flight_store) { } FlightServer::~FlightServer() { } arw::Status FlightServer::ListFlights(const flt::ServerCallContext& context, const flt::Criteria* criteria, std::unique_ptr<flt::FlightListing>* listings) { // function local class to implement FlightListing interface class RGWFlightListing : public flt::FlightListing { FlightStore* flight_store; FlightKey previous_key; public: RGWFlightListing(FlightStore* flight_store) : flight_store(flight_store), previous_key(null_flight_key) { } arw::Status Next(std::unique_ptr<flt::FlightInfo>* info) { std::optional<FlightData> fd = flight_store->after_key(previous_key); if (fd) { previous_key = fd->key; auto descriptor = flt::FlightDescriptor::Path( { fd->tenant_name, fd->bucket_name, fd->object_key.name, fd->object_key.instance, fd->object_key.ns }); flt::FlightEndpoint endpoint; endpoint.ticket = FlightKeyToTicket(fd->key); std::vector<flt::FlightEndpoint> endpoints { endpoint }; ARROW_ASSIGN_OR_RAISE(flt::FlightInfo info_obj, flt::FlightInfo::Make(*fd->schema, descriptor, endpoints, fd->num_records, fd->obj_size)); *info = std::make_unique<flt::FlightInfo>(std::move(info_obj)); return arw::Status::OK(); } else { *info = nullptr; return arw::Status::OK(); } } }; // class RGWFlightListing *listings = std::make_unique<RGWFlightListing>(flight_store); return arw::Status::OK(); } // FlightServer::ListFlights arw::Status FlightServer::GetFlightInfo(const flt::ServerCallContext &context, const flt::FlightDescriptor &request, std::unique_ptr<flt::FlightInfo> *info) { return arw::Status::OK(); } // FlightServer::GetFlightInfo arw::Status FlightServer::GetSchema(const flt::ServerCallContext &context, const flt::FlightDescriptor &request, std::unique_ptr<flt::SchemaResult> *schema) { return arw::Status::OK(); } // FlightServer::GetSchema // A Buffer that owns its memory and frees it when the Buffer is // destructed class OwnedBuffer : public arw::Buffer { uint8_t* buffer; protected: OwnedBuffer(uint8_t* _buffer, int64_t _size) : Buffer(_buffer, _size), buffer(_buffer) { } public: ~OwnedBuffer() override { delete[] buffer; } static arw::Result<std::shared_ptr<OwnedBuffer>> make(int64_t size) { uint8_t* buffer = new (std::nothrow) uint8_t[size]; if (!buffer) { return arw::Status::OutOfMemory("could not allocated buffer of size %" PRId64, size); } OwnedBuffer* ptr = new OwnedBuffer(buffer, size); std::shared_ptr<OwnedBuffer> result; result.reset(ptr); return result; } // if what's read in is less than capacity void set_size(int64_t size) { size_ = size; } // pointer that can be used to write into buffer uint8_t* writeable_data() { return buffer; } }; // class OwnedBuffer #if 0 // remove classes used for testing and incrementally building // make local to DoGet eventually class LocalInputStream : public arw::io::InputStream { std::iostream::pos_type position; std::fstream file; std::shared_ptr<const arw::KeyValueMetadata> kv_metadata; const DoutPrefix dp; public: LocalInputStream(std::shared_ptr<const arw::KeyValueMetadata> _kv_metadata, const DoutPrefix _dp) : kv_metadata(_kv_metadata), dp(_dp) {} arw::Status Open() { file.open("/tmp/green_tripdata_2022-04.parquet", std::ios::in); if (!file.good()) { return arw::Status::IOError("unable to open file"); } INFO << "file opened successfully" << dendl; position = file.tellg(); return arw::Status::OK(); } arw::Status Close() override { file.close(); INFO << "file closed" << dendl; return arw::Status::OK(); } arw::Result<int64_t> Tell() const override { if (position < 0) { return arw::Status::IOError( "could not query file implementaiton with tellg"); } else { return int64_t(position); } } bool closed() const override { return file.is_open(); } arw::Result<int64_t> Read(int64_t nbytes, void* out) override { INFO << "entered: asking for " << nbytes << " bytes" << dendl; if (file.read(reinterpret_cast<char*>(out), reinterpret_cast<std::streamsize>(nbytes))) { const std::streamsize bytes_read = file.gcount(); INFO << "Point A: read bytes " << bytes_read << dendl; position = file.tellg(); return bytes_read; } else { ERROR << "unable to read from file" << dendl; return arw::Status::IOError("unable to read from offset %" PRId64, int64_t(position)); } } arw::Result<std::shared_ptr<arw::Buffer>> Read(int64_t nbytes) override { INFO << "entered: " << ": asking for " << nbytes << " bytes" << dendl; std::shared_ptr<OwnedBuffer> buffer; ARROW_ASSIGN_OR_RAISE(buffer, OwnedBuffer::make(nbytes)); if (file.read(reinterpret_cast<char*>(buffer->writeable_data()), reinterpret_cast<std::streamsize>(nbytes))) { const auto bytes_read = file.gcount(); INFO << "Point B: read bytes " << bytes_read << dendl; // buffer->set_size(bytes_read); position = file.tellg(); return buffer; } else if (file.rdstate() & std::ifstream::failbit && file.rdstate() & std::ifstream::eofbit) { const auto bytes_read = file.gcount(); INFO << "3 read bytes " << bytes_read << " and reached EOF" << dendl; // buffer->set_size(bytes_read); position = file.tellg(); return buffer; } else { ERROR << "unable to read from file" << dendl; return arw::Status::IOError("unable to read from offset %ld", position); } } arw::Result<arw::util::string_view> Peek(int64_t nbytes) override { INFO << "called, not implemented" << dendl; return arw::Status::NotImplemented("peek not currently allowed"); } bool supports_zero_copy() const override { return false; } arw::Result<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadata() override { INFO << "called" << dendl; return kv_metadata; } }; // class LocalInputStream class LocalRandomAccessFile : public arw::io::RandomAccessFile { FlightData flight_data; const DoutPrefix dp; std::iostream::pos_type position; std::fstream file; public: LocalRandomAccessFile(const FlightData& _flight_data, const DoutPrefix _dp) : flight_data(_flight_data), dp(_dp) { } // implement InputStream arw::Status Open() { file.open("/tmp/green_tripdata_2022-04.parquet", std::ios::in); if (!file.good()) { return arw::Status::IOError("unable to open file"); } INFO << "file opened successfully" << dendl; position = file.tellg(); return arw::Status::OK(); } arw::Status Close() override { file.close(); INFO << "file closed" << dendl; return arw::Status::OK(); } arw::Result<int64_t> Tell() const override { if (position < 0) { return arw::Status::IOError( "could not query file implementaiton with tellg"); } else { return int64_t(position); } } bool closed() const override { return file.is_open(); } arw::Result<int64_t> Read(int64_t nbytes, void* out) override { INFO << "entered: asking for " << nbytes << " bytes" << dendl; if (file.read(reinterpret_cast<char*>(out), reinterpret_cast<std::streamsize>(nbytes))) { const std::streamsize bytes_read = file.gcount(); INFO << "Point A: read bytes " << bytes_read << dendl; position = file.tellg(); return bytes_read; } else { ERROR << "unable to read from file" << dendl; return arw::Status::IOError("unable to read from offset %" PRId64, int64_t(position)); } } arw::Result<std::shared_ptr<arw::Buffer>> Read(int64_t nbytes) override { INFO << "entered: asking for " << nbytes << " bytes" << dendl; std::shared_ptr<OwnedBuffer> buffer; ARROW_ASSIGN_OR_RAISE(buffer, OwnedBuffer::make(nbytes)); if (file.read(reinterpret_cast<char*>(buffer->writeable_data()), reinterpret_cast<std::streamsize>(nbytes))) { const auto bytes_read = file.gcount(); INFO << "Point B: read bytes " << bytes_read << dendl; // buffer->set_size(bytes_read); position = file.tellg(); return buffer; } else if (file.rdstate() & std::ifstream::failbit && file.rdstate() & std::ifstream::eofbit) { const auto bytes_read = file.gcount(); INFO << "3 read bytes " << bytes_read << " and reached EOF" << dendl; // buffer->set_size(bytes_read); position = file.tellg(); return buffer; } else { ERROR << "unable to read from file" << dendl; return arw::Status::IOError("unable to read from offset %ld", position); } } bool supports_zero_copy() const override { return false; } // implement Seekable arw::Result<int64_t> GetSize() override { return flight_data.obj_size; } arw::Result<arw::util::string_view> Peek(int64_t nbytes) override { std::iostream::pos_type here = file.tellg(); if (here == -1) { return arw::Status::IOError( "unable to determine current position ahead of peek"); } ARROW_ASSIGN_OR_RAISE(OwningStringView result, OwningStringView::make(nbytes)); // read ARROW_ASSIGN_OR_RAISE(int64_t bytes_read, Read(nbytes, (void*) result.writeable_data())); (void) bytes_read; // silence unused variable warnings // return offset to original ARROW_RETURN_NOT_OK(Seek(here)); return result; } arw::Result<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadata() { return flight_data.kv_metadata; } arw::Future<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadataAsync( const arw::io::IOContext& io_context) override { return arw::Future<std::shared_ptr<const arw::KeyValueMetadata>>::MakeFinished(ReadMetadata()); } // implement Seekable interface arw::Status Seek(int64_t position) { file.seekg(position); if (file.fail()) { return arw::Status::IOError( "error encountered during seek to %" PRId64, position); } else { return arw::Status::OK(); } } }; // class LocalRandomAccessFile #endif class RandomAccessObject : public arw::io::RandomAccessFile { FlightData flight_data; const DoutPrefix dp; int64_t position; bool is_closed; std::unique_ptr<rgw::sal::Object::ReadOp> op; public: RandomAccessObject(const FlightData& _flight_data, std::unique_ptr<rgw::sal::Object>& obj, const DoutPrefix _dp) : flight_data(_flight_data), dp(_dp), position(-1), is_closed(false) { op = obj->get_read_op(); } arw::Status Open() { int ret = op->prepare(null_yield, &dp); if (ret < 0) { return arw::Status::IOError( "unable to prepare object with error %d", ret); } INFO << "file opened successfully" << dendl; position = 0; return arw::Status::OK(); } // implement InputStream arw::Status Close() override { position = -1; is_closed = true; (void) op.reset(); INFO << "object closed" << dendl; return arw::Status::OK(); } arw::Result<int64_t> Tell() const override { if (position < 0) { return arw::Status::IOError("could not determine position"); } else { return position; } } bool closed() const override { return is_closed; } arw::Result<int64_t> Read(int64_t nbytes, void* out) override { INFO << "entered: asking for " << nbytes << " bytes" << dendl; if (position < 0) { ERROR << "error, position indicated error" << dendl; return arw::Status::IOError("object read op is in bad state"); } // note: read function reads through end_position inclusive int64_t end_position = position + nbytes - 1; bufferlist bl; const int64_t bytes_read = op->read(position, end_position, bl, null_yield, &dp); if (bytes_read < 0) { const int64_t former_position = position; position = -1; ERROR << "read operation returned " << bytes_read << dendl; return arw::Status::IOError( "unable to read object at position %" PRId64 ", error code: %" PRId64, former_position, bytes_read); } // TODO: see if there's a way to get rid of this copy, perhaps // updating rgw::sal::read_op bl.cbegin().copy(bytes_read, reinterpret_cast<char*>(out)); position += bytes_read; if (nbytes != bytes_read) { INFO << "partial read: nbytes=" << nbytes << ", bytes_read=" << bytes_read << dendl; } INFO << bytes_read << " bytes read" << dendl; return bytes_read; } arw::Result<std::shared_ptr<arw::Buffer>> Read(int64_t nbytes) override { INFO << "entered: asking for " << nbytes << " bytes" << dendl; std::shared_ptr<OwnedBuffer> buffer; ARROW_ASSIGN_OR_RAISE(buffer, OwnedBuffer::make(nbytes)); ARROW_ASSIGN_OR_RAISE(const int64_t bytes_read, Read(nbytes, buffer->writeable_data())); buffer->set_size(bytes_read); return buffer; } bool supports_zero_copy() const override { return false; } // implement Seekable arw::Result<int64_t> GetSize() override { INFO << "entered: " << flight_data.obj_size << " returned" << dendl; return flight_data.obj_size; } arw::Result<arw::util::string_view> Peek(int64_t nbytes) override { INFO << "entered: " << nbytes << " bytes" << dendl; int64_t saved_position = position; ARROW_ASSIGN_OR_RAISE(OwningStringView buffer, OwningStringView::make(nbytes)); ARROW_ASSIGN_OR_RAISE(const int64_t bytes_read, Read(nbytes, (void*) buffer.writeable_data())); // restore position for a peek position = saved_position; if (bytes_read < nbytes) { // create new OwningStringView with moved buffer return OwningStringView::shrink(std::move(buffer), bytes_read); } else { return buffer; } } arw::Result<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadata() { return flight_data.kv_metadata; } arw::Future<std::shared_ptr<const arw::KeyValueMetadata>> ReadMetadataAsync( const arw::io::IOContext& io_context) override { return arw::Future<std::shared_ptr<const arw::KeyValueMetadata>>::MakeFinished(ReadMetadata()); } // implement Seekable interface arw::Status Seek(int64_t new_position) { INFO << "entered: position: " << new_position << dendl; if (position < 0) { ERROR << "error, position indicated error" << dendl; return arw::Status::IOError("object read op is in bad state"); } else { position = new_position; return arw::Status::OK(); } } }; // class RandomAccessObject arw::Status FlightServer::DoGet(const flt::ServerCallContext &context, const flt::Ticket &request, std::unique_ptr<flt::FlightDataStream> *stream) { int ret; ARROW_ASSIGN_OR_RAISE(FlightKey key, TicketToFlightKey(request)); ARROW_ASSIGN_OR_RAISE(FlightData fd, get_flight_store()->get_flight(key)); std::unique_ptr<rgw::sal::User> user = driver->get_user(fd.user_id); if (user->empty()) { INFO << "user is empty" << dendl; } else { // TODO: test what happens if user is not loaded ret = user->load_user(&dp, null_yield); if (ret < 0) { ERROR << "load_user returned " << ret << dendl; // TODO return something } INFO << "user is " << user->get_display_name() << dendl; } std::unique_ptr<rgw::sal::Bucket> bucket; ret = driver->get_bucket(&dp, &(*user), fd.tenant_name, fd.bucket_name, &bucket, null_yield); if (ret < 0) { ERROR << "get_bucket returned " << ret << dendl; // TODO return something } std::unique_ptr<rgw::sal::Object> object = bucket->get_object(fd.object_key); auto input = std::make_shared<RandomAccessObject>(fd, object, dp); ARROW_RETURN_NOT_OK(input->Open()); std::unique_ptr<parquet::arrow::FileReader> reader; ARROW_RETURN_NOT_OK(parquet::arrow::OpenFile(input, arw::default_memory_pool(), &reader)); std::shared_ptr<arrow::Table> table; ARROW_RETURN_NOT_OK(reader->ReadTable(&table)); std::vector<std::shared_ptr<arw::RecordBatch>> batches; arw::TableBatchReader batch_reader(*table); ARROW_RETURN_NOT_OK(batch_reader.ReadAll(&batches)); ARROW_ASSIGN_OR_RAISE(auto owning_reader, arw::RecordBatchReader::Make( std::move(batches), table->schema())); *stream = std::unique_ptr<flt::FlightDataStream>( new flt::RecordBatchStream(owning_reader)); return arw::Status::OK(); } // flightServer::DoGet } // namespace rgw::flight
20,311
27.016552
108
cc
null
ceph-main/src/rgw/rgw_flight.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright 2023 IBM * * See file COPYING for licensing information. */ #pragma once #include <map> #include <mutex> #include <atomic> #include "include/common_fwd.h" #include "common/ceph_context.h" #include "common/Thread.h" #include "common/ceph_time.h" #include "rgw_frontend.h" #include "arrow/type.h" #include "arrow/flight/server.h" #include "arrow/util/string_view.h" #include "rgw_flight_frontend.h" #define INFO_F(dp) ldpp_dout(&dp, 20) << "INFO: " << __func__ << ": " #define STATUS_F(dp) ldpp_dout(&dp, 10) << "STATUS: " << __func__ << ": " #define WARN_F(dp) ldpp_dout(&dp, 0) << "WARNING: " << __func__ << ": " #define ERROR_F(dp) ldpp_dout(&dp, 0) << "ERROR: " << __func__ << ": " #define INFO INFO_F(dp) #define STATUS STATUS_F(dp) #define WARN WARN_F(dp) #define ERROR ERROR_F(dp) namespace arw = arrow; namespace flt = arrow::flight; struct req_state; namespace rgw::flight { static const coarse_real_clock::duration lifespan = std::chrono::hours(1); struct FlightData { FlightKey key; // coarse_real_clock::time_point expires; std::string uri; std::string tenant_name; std::string bucket_name; rgw_obj_key object_key; // NB: what about object's namespace and instance? uint64_t num_records; uint64_t obj_size; std::shared_ptr<arw::Schema> schema; std::shared_ptr<const arw::KeyValueMetadata> kv_metadata; rgw_user user_id; // TODO: this should be removed when we do // proper flight authentication FlightData(const std::string& _uri, const std::string& _tenant_name, const std::string& _bucket_name, const rgw_obj_key& _object_key, uint64_t _num_records, uint64_t _obj_size, std::shared_ptr<arw::Schema>& _schema, std::shared_ptr<const arw::KeyValueMetadata>& _kv_metadata, rgw_user _user_id); }; // stores flights that have been created and helps expire them class FlightStore { protected: const DoutPrefix& dp; public: FlightStore(const DoutPrefix& dp); virtual ~FlightStore(); virtual FlightKey add_flight(FlightData&& flight) = 0; // TODO consider returning const shared pointers to FlightData in // the following two functions virtual arw::Result<FlightData> get_flight(const FlightKey& key) const = 0; virtual std::optional<FlightData> after_key(const FlightKey& key) const = 0; virtual int remove_flight(const FlightKey& key) = 0; virtual int expire_flights() = 0; }; class MemoryFlightStore : public FlightStore { std::map<FlightKey, FlightData> map; mutable std::mutex mtx; // for map public: MemoryFlightStore(const DoutPrefix& dp); virtual ~MemoryFlightStore(); FlightKey add_flight(FlightData&& flight) override; arw::Result<FlightData> get_flight(const FlightKey& key) const override; std::optional<FlightData> after_key(const FlightKey& key) const override; int remove_flight(const FlightKey& key) override; int expire_flights() override; }; class FlightServer : public flt::FlightServerBase { using Data1 = std::vector<std::shared_ptr<arw::RecordBatch>>; RGWProcessEnv& env; rgw::sal::Driver* driver; const DoutPrefix& dp; FlightStore* flight_store; std::map<std::string, Data1> data; public: static constexpr int default_port = 8077; FlightServer(RGWProcessEnv& env, FlightStore* flight_store, const DoutPrefix& dp); ~FlightServer() override; FlightStore* get_flight_store() { return flight_store; } arw::Status ListFlights(const flt::ServerCallContext& context, const flt::Criteria* criteria, std::unique_ptr<flt::FlightListing>* listings) override; arw::Status GetFlightInfo(const flt::ServerCallContext &context, const flt::FlightDescriptor &request, std::unique_ptr<flt::FlightInfo> *info) override; arw::Status GetSchema(const flt::ServerCallContext &context, const flt::FlightDescriptor &request, std::unique_ptr<flt::SchemaResult> *schema) override; arw::Status DoGet(const flt::ServerCallContext &context, const flt::Ticket &request, std::unique_ptr<flt::FlightDataStream> *stream) override; }; // class FlightServer class OwningStringView : public arw::util::string_view { uint8_t* buffer; int64_t capacity; int64_t consumed; OwningStringView(uint8_t* _buffer, int64_t _size) : arw::util::string_view((const char*) _buffer, _size), buffer(_buffer), capacity(_size), consumed(_size) { } OwningStringView(OwningStringView&& from, int64_t new_size) : buffer(nullptr), capacity(from.capacity), consumed(new_size) { // should be impossible due to static function check ceph_assertf(consumed <= capacity, "new size cannot exceed capacity"); std::swap(buffer, from.buffer); from.capacity = 0; from.consumed = 0; } public: OwningStringView(OwningStringView&&) = default; OwningStringView& operator=(OwningStringView&&) = default; uint8_t* writeable_data() { return buffer; } ~OwningStringView() { if (buffer) { delete[] buffer; } } static arw::Result<OwningStringView> make(int64_t size) { uint8_t* buffer = new uint8_t[size]; if (!buffer) { return arw::Status::OutOfMemory("could not allocated buffer of size %" PRId64, size); } return OwningStringView(buffer, size); } static arw::Result<OwningStringView> shrink(OwningStringView&& from, int64_t new_size) { if (new_size > from.capacity) { return arw::Status::Invalid("new size cannot exceed capacity"); } else { return OwningStringView(std::move(from), new_size); } } }; // GLOBAL flt::Ticket FlightKeyToTicket(const FlightKey& key); arw::Status TicketToFlightKey(const flt::Ticket& t, FlightKey& key); } // namespace rgw::flight
5,924
25.689189
91
h
null
ceph-main/src/rgw/rgw_flight_frontend.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright 2023 IBM * * See file COPYING for licensing information. */ #include <cstdio> #include <filesystem> #include <sstream> #include "arrow/type.h" #include "arrow/flight/server.h" #include "arrow/io/file.h" #include "parquet/arrow/reader.h" #include "parquet/arrow/schema.h" #include "parquet/stream_reader.h" #include "rgw_flight_frontend.h" #include "rgw_flight.h" // logging constexpr unsigned dout_subsys = ceph_subsys_rgw_flight; constexpr const char* dout_prefix_str = "rgw arrow_flight: "; namespace rgw::flight { const FlightKey null_flight_key = 0; FlightFrontend::FlightFrontend(RGWProcessEnv& _env, RGWFrontendConfig* _config, int _port) : env(_env), config(_config), port(_port), dp(env.driver->ctx(), dout_subsys, dout_prefix_str) { env.flight_store = new MemoryFlightStore(dp); env.flight_server = new FlightServer(env, env.flight_store, dp); INFO << "flight server started" << dendl; } FlightFrontend::~FlightFrontend() { delete env.flight_server; env.flight_server = nullptr; delete env.flight_store; env.flight_store = nullptr; INFO << "flight server shut down" << dendl; } int FlightFrontend::init() { if (port <= 0) { port = FlightServer::default_port; } const std::string url = std::string("grpc+tcp://localhost:") + std::to_string(port); flt::Location location; arw::Status s = flt::Location::Parse(url, &location); if (!s.ok()) { ERROR << "couldn't parse url=" << url << ", status=" << s << dendl; return -EINVAL; } flt::FlightServerOptions options(location); options.verify_client = false; s = env.flight_server->Init(options); if (!s.ok()) { ERROR << "couldn't init flight server; status=" << s << dendl; return -EINVAL; } INFO << "FlightServer inited; will use port " << port << dendl; return 0; } int FlightFrontend::run() { try { flight_thread = make_named_thread(server_thread_name, &FlightServer::Serve, env.flight_server); INFO << "FlightServer thread started, id=" << flight_thread.get_id() << ", joinable=" << flight_thread.joinable() << dendl; return 0; } catch (std::system_error& e) { ERROR << "FlightServer thread failed to start" << dendl; return -e.code().value(); } } void FlightFrontend::stop() { env.flight_server->Shutdown(); env.flight_server->Wait(); INFO << "FlightServer shut down" << dendl; } void FlightFrontend::join() { flight_thread.join(); INFO << "FlightServer thread joined" << dendl; } void FlightFrontend::pause_for_new_config() { // ignore since config changes won't alter flight_server } void FlightFrontend::unpause_with_new_config() { // ignore since config changes won't alter flight_server } /* ************************************************************ */ FlightGetObj_Filter::FlightGetObj_Filter(const req_state* request, RGWGetObj_Filter* next) : RGWGetObj_Filter(next), penv(request->penv), dp(request->cct->get(), dout_subsys, dout_prefix_str), current_offset(0), expected_size(request->obj_size), uri(request->decoded_uri), tenant_name(request->bucket->get_tenant()), bucket_name(request->bucket->get_name()), object_key(request->object->get_key()), // note: what about object namespace and instance? schema_status(arrow::StatusCode::Cancelled, "schema determination incomplete"), user_id(request->user->get_id()) { #warning "TODO: fix use of tmpnam" char name[L_tmpnam]; const char* namep = std::tmpnam(name); if (!namep) { // } temp_file_name = namep; temp_file.open(temp_file_name); } FlightGetObj_Filter::~FlightGetObj_Filter() { if (temp_file.is_open()) { temp_file.close(); } std::error_code error; std::filesystem::remove(temp_file_name, error); if (error) { ERROR << "FlightGetObj_Filter got error when removing temp file; " "error=" << error.value() << ", temp_file_name=" << temp_file_name << dendl; } else { INFO << "parquet/arrow schema determination status: " << schema_status << dendl; } } int FlightGetObj_Filter::handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { INFO << "flight handling data from offset " << current_offset << " (" << bl_ofs << ") of size " << bl_len << dendl; current_offset += bl_len; if (temp_file.is_open()) { bl.write_stream(temp_file); if (current_offset >= expected_size) { INFO << "data read is completed, current_offset=" << current_offset << ", expected_size=" << expected_size << dendl; temp_file.close(); std::shared_ptr<const arw::KeyValueMetadata> kv_metadata; std::shared_ptr<arw::Schema> aw_schema; int64_t num_rows = 0; auto process_metadata = [&aw_schema, &num_rows, &kv_metadata, this]() -> arrow::Status { ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::io::ReadableFile> file, arrow::io::ReadableFile::Open(temp_file_name)); const std::shared_ptr<parquet::FileMetaData> metadata = parquet::ReadMetaData(file); file->Close(); num_rows = metadata->num_rows(); kv_metadata = metadata->key_value_metadata(); const parquet::SchemaDescriptor* pq_schema = metadata->schema(); ARROW_RETURN_NOT_OK(parquet::arrow::FromParquetSchema(pq_schema, &aw_schema)); return arrow::Status::OK(); }; schema_status = process_metadata(); if (!schema_status.ok()) { ERROR << "reading metadata to access schema, error=" << schema_status << dendl; } else { // INFO << "arrow_schema=" << *aw_schema << dendl; FlightStore* store = penv.flight_store; auto key = store->add_flight(FlightData(uri, tenant_name, bucket_name, object_key, num_rows, expected_size, aw_schema, kv_metadata, user_id)); (void) key; // suppress unused variable warning } } // if last block } // if file opened // chain to next filter in stream int ret = RGWGetObj_Filter::handle_data(bl, bl_ofs, bl_len); return ret; } #if 0 void code_snippets() { INFO << "num_columns:" << md->num_columns() << " num_schema_elements:" << md->num_schema_elements() << " num_rows:" << md->num_rows() << " num_row_groups:" << md->num_row_groups() << dendl; INFO << "file schema: name=" << schema1->name() << ", ToString:" << schema1->ToString() << ", num_columns=" << schema1->num_columns() << dendl; for (int c = 0; c < schema1->num_columns(); ++c) { const parquet::ColumnDescriptor* cd = schema1->Column(c); // const parquet::ConvertedType::type t = cd->converted_type; const std::shared_ptr<const parquet::LogicalType> lt = cd->logical_type(); INFO << "column " << c << ": name=" << cd->name() << ", ToString=" << cd->ToString() << ", logical_type=" << lt->ToString() << dendl; } INFO << "There are " << md->num_rows() << " rows and " << md->num_row_groups() << " row groups" << dendl; for (int rg = 0; rg < md->num_row_groups(); ++rg) { INFO << "Row Group " << rg << dendl; auto rg_md = md->RowGroup(rg); auto schema2 = rg_md->schema(); } } #endif } // namespace rgw::flight
7,224
28.251012
145
cc
null
ceph-main/src/rgw/rgw_flight_frontend.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright 2023 IBM * * See file COPYING for licensing information. */ #pragma once #include "include/common_fwd.h" #include "common/Thread.h" #include "rgw_frontend.h" #include "rgw_op.h" #include "arrow/status.h" namespace rgw::flight { using FlightKey = uint32_t; extern const FlightKey null_flight_key; class FlightServer; class FlightFrontend : public RGWFrontend { static constexpr std::string_view server_thread_name = "Arrow Flight Server thread"; RGWProcessEnv& env; std::thread flight_thread; RGWFrontendConfig* config; int port; const DoutPrefix dp; public: // port <= 0 means let server decide; typically 8077 FlightFrontend(RGWProcessEnv& env, RGWFrontendConfig* config, int port = -1); ~FlightFrontend() override; int init() override; int run() override; void stop() override; void join() override; void pause_for_new_config() override; void unpause_with_new_config() override; }; // class FlightFrontend class FlightGetObj_Filter : public RGWGetObj_Filter { const RGWProcessEnv& penv; const DoutPrefix dp; FlightKey key; uint64_t current_offset; uint64_t expected_size; std::string uri; std::string tenant_name; std::string bucket_name; rgw_obj_key object_key; std::string temp_file_name; std::ofstream temp_file; arrow::Status schema_status; rgw_user user_id; // TODO: this should be removed when we do // proper flight authentication public: FlightGetObj_Filter(const req_state* request, RGWGetObj_Filter* next); ~FlightGetObj_Filter(); int handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) override; #if 0 // this would allow the range to be modified if necessary; int fixup_range(off_t& ofs, off_t& end) override; #endif }; } // namespace rgw::flight
1,934
21.241379
72
h
null
ceph-main/src/rgw/rgw_formats.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <boost/format.hpp> #include "common/escape.h" #include "common/Formatter.h" #include "rgw/rgw_common.h" #include "rgw/rgw_formats.h" #include "rgw/rgw_rest.h" #define LARGE_SIZE 8192 #define dout_subsys ceph_subsys_rgw using namespace std; RGWFormatter_Plain::RGWFormatter_Plain(const bool ukv) : use_kv(ukv) { } RGWFormatter_Plain::~RGWFormatter_Plain() { free(buf); } void RGWFormatter_Plain::flush(ostream& os) { if (!buf) return; if (len) { os << buf; os.flush(); } reset_buf(); } void RGWFormatter_Plain::reset_buf() { free(buf); buf = NULL; len = 0; max_len = 0; } void RGWFormatter_Plain::reset() { reset_buf(); stack.clear(); min_stack_level = 0; } void RGWFormatter_Plain::open_array_section(std::string_view name) { struct plain_stack_entry new_entry; new_entry.is_array = true; new_entry.size = 0; if (use_kv && min_stack_level > 0 && !stack.empty()) { struct plain_stack_entry& entry = stack.back(); if (!entry.is_array) dump_format(name, ""); } stack.push_back(new_entry); } void RGWFormatter_Plain::open_array_section_in_ns(std::string_view name, const char *ns) { ostringstream oss; oss << name << " " << ns; open_array_section(oss.str().c_str()); } void RGWFormatter_Plain::open_object_section(std::string_view name) { struct plain_stack_entry new_entry; new_entry.is_array = false; new_entry.size = 0; if (use_kv && min_stack_level > 0) dump_format(name, ""); stack.push_back(new_entry); } void RGWFormatter_Plain::open_object_section_in_ns(std::string_view name, const char *ns) { ostringstream oss; oss << name << " " << ns; open_object_section(oss.str().c_str()); } void RGWFormatter_Plain::close_section() { stack.pop_back(); } void RGWFormatter_Plain::dump_unsigned(std::string_view name, uint64_t u) { dump_value_int(name, "%" PRIu64, u); } void RGWFormatter_Plain::dump_int(std::string_view name, int64_t u) { dump_value_int(name, "%" PRId64, u); } void RGWFormatter_Plain::dump_float(std::string_view name, double d) { dump_value_int(name, "%f", d); } void RGWFormatter_Plain::dump_string(std::string_view name, std::string_view s) { dump_format(name, "%.*s", s.size(), s.data()); } std::ostream& RGWFormatter_Plain::dump_stream(std::string_view name) { // TODO: implement this! ceph_abort(); } void RGWFormatter_Plain::dump_format_va(std::string_view name, const char *ns, bool quoted, const char *fmt, va_list ap) { char buf[LARGE_SIZE]; struct plain_stack_entry& entry = stack.back(); if (!min_stack_level) min_stack_level = stack.size(); bool should_print = ((stack.size() == min_stack_level && !entry.size) || use_kv); entry.size++; if (!should_print) return; vsnprintf(buf, LARGE_SIZE, fmt, ap); const char *eol; if (wrote_something) { if (use_kv && entry.is_array && entry.size > 1) eol = ", "; else eol = "\n"; } else eol = ""; wrote_something = true; if (use_kv && !entry.is_array) write_data("%s%.*s: %s", eol, name.size(), name.data(), buf); else write_data("%s%s", eol, buf); } int RGWFormatter_Plain::get_len() const { // don't include null termination in length return (len ? len - 1 : 0); } void RGWFormatter_Plain::write_raw_data(const char *data) { write_data("%s", data); } void RGWFormatter_Plain::write_data(const char *fmt, ...) { #define LARGE_ENOUGH_LEN 128 int n, size = LARGE_ENOUGH_LEN; char s[size + 8]; char *p, *np; bool p_on_stack; va_list ap; int pos; p = s; p_on_stack = true; while (1) { va_start(ap, fmt); n = vsnprintf(p, size, fmt, ap); va_end(ap); if (n > -1 && n < size) goto done; /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ if (p_on_stack) np = (char *)malloc(size + 8); else np = (char *)realloc(p, size + 8); if (!np) goto done_free; p = np; p_on_stack = false; } done: #define LARGE_ENOUGH_BUF 4096 if (!buf) { max_len = std::max(LARGE_ENOUGH_BUF, size); buf = (char *)malloc(max_len); if (!buf) { cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl; goto done_free; } } if (len + size > max_len) { max_len = len + size + LARGE_ENOUGH_BUF; void *_realloc = NULL; if ((_realloc = realloc(buf, max_len)) == NULL) { cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl; goto done_free; } else { buf = (char *)_realloc; } } pos = len; if (len) pos--; // squash null termination strcpy(buf + pos, p); len = pos + strlen(p) + 1; done_free: if (!p_on_stack) free(p); } void RGWFormatter_Plain::dump_value_int(std::string_view name, const char *fmt, ...) { char buf[LARGE_SIZE]; va_list ap; if (!min_stack_level) min_stack_level = stack.size(); struct plain_stack_entry& entry = stack.back(); bool should_print = ((stack.size() == min_stack_level && !entry.size) || use_kv); entry.size++; if (!should_print) return; va_start(ap, fmt); vsnprintf(buf, LARGE_SIZE, fmt, ap); va_end(ap); const char *eol; if (wrote_something) { eol = "\n"; } else eol = ""; wrote_something = true; if (use_kv && !entry.is_array) write_data("%s%.*s: %s", eol, name.size(), name.data(), buf); else write_data("%s%s", eol, buf); } /* An utility class that serves as a mean to access the protected static * methods of XMLFormatter. */ class HTMLHelper : public XMLFormatter { public: static std::string escape(const std::string& unescaped_str) { int len = escape_xml_attr_len(unescaped_str.c_str()); std::string escaped(len, 0); escape_xml_attr(unescaped_str.c_str(), escaped.data()); return escaped; } }; void RGWSwiftWebsiteListingFormatter::generate_header( const std::string& dir_path, const std::string& css_path) { ss << R"(<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 )" << R"(Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">)"; ss << "<html><head><title>Listing of " << xml_stream_escaper(dir_path) << "</title>"; if (! css_path.empty()) { ss << boost::format(R"(<link rel="stylesheet" type="text/css" href="%s" />)") % url_encode(css_path); } else { ss << R"(<style type="text/css">)" << R"(h1 {font-size: 1em; font-weight: bold;})" << R"(th {text-align: left; padding: 0px 1em 0px 1em;})" << R"(td {padding: 0px 1em 0px 1em;})" << R"(a {text-decoration: none;})" << R"(</style>)"; } ss << "</head><body>"; ss << R"(<h1 id="title">Listing of )" << xml_stream_escaper(dir_path) << "</h1>" << R"(<table id="listing">)" << R"(<tr id="heading">)" << R"(<th class="colname">Name</th>)" << R"(<th class="colsize">Size</th>)" << R"(<th class="coldate">Date</th>)" << R"(</tr>)"; if (! prefix.empty()) { ss << R"(<tr id="parent" class="item">)" << R"(<td class="colname"><a href="../">../</a></td>)" << R"(<td class="colsize">&nbsp;</td>)" << R"(<td class="coldate">&nbsp;</td>)" << R"(</tr>)"; } } void RGWSwiftWebsiteListingFormatter::generate_footer() { ss << R"(</table></body></html>)"; } std::string RGWSwiftWebsiteListingFormatter::format_name( const std::string& item_name) const { return item_name.substr(prefix.length()); } void RGWSwiftWebsiteListingFormatter::dump_object(const rgw_bucket_dir_entry& objent) { const auto name = format_name(objent.key.name); ss << boost::format(R"(<tr class="item %s">)") % "default" << boost::format(R"(<td class="colname"><a href="%s">%s</a></td>)") % url_encode(name) % HTMLHelper::escape(name) << boost::format(R"(<td class="colsize">%lld</td>)") % objent.meta.size << boost::format(R"(<td class="coldate">%s</td>)") % dump_time_to_str(objent.meta.mtime) << R"(</tr>)"; } void RGWSwiftWebsiteListingFormatter::dump_subdir(const std::string& name) { const auto fname = format_name(name); ss << R"(<tr class="item subdir">)" << boost::format(R"(<td class="colname"><a href="%s">%s</a></td>)") % url_encode(fname) % HTMLHelper::escape(fname) << R"(<td class="colsize">&nbsp;</td>)" << R"(<td class="coldate">&nbsp;</td>)" << R"(</tr>)"; }
9,132
23.225464
120
cc
null
ceph-main/src/rgw/rgw_formats.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "common/Formatter.h" #include <list> #include <stdint.h> #include <string> #include <ostream> struct plain_stack_entry { int size; bool is_array; }; /* FIXME: this class is mis-named. * FIXME: This was a hack to send certain swift messages. * There is a much better way to do this. */ class RGWFormatter_Plain : public Formatter { void reset_buf(); public: explicit RGWFormatter_Plain(bool use_kv = false); ~RGWFormatter_Plain() override; void set_status(int status, const char* status_name) override {}; void output_header() override {}; void output_footer() override {}; void enable_line_break() override {}; void flush(std::ostream& os) override; void reset() override; void open_array_section(std::string_view name) override; void open_array_section_in_ns(std::string_view name, const char *ns) override; void open_object_section(std::string_view name) override; void open_object_section_in_ns(std::string_view name, const char *ns) override; void close_section() override; void dump_unsigned(std::string_view name, uint64_t u) override; void dump_int(std::string_view name, int64_t u) override; void dump_float(std::string_view name, double d) override; void dump_string(std::string_view name, std::string_view s) override; std::ostream& dump_stream(std::string_view name) override; void dump_format_va(std::string_view name, const char *ns, bool quoted, const char *fmt, va_list ap) override; int get_len() const override; void write_raw_data(const char *data) override; private: void write_data(const char *fmt, ...); void dump_value_int(std::string_view name, const char *fmt, ...); char *buf = nullptr; int len = 0; int max_len = 0; std::list<struct plain_stack_entry> stack; size_t min_stack_level = 0; bool use_kv; bool wrote_something = 0; }; /* This is a presentation layer. No logic inside, please. */ class RGWSwiftWebsiteListingFormatter { std::ostream& ss; const std::string prefix; protected: std::string format_name(const std::string& item_name) const; public: RGWSwiftWebsiteListingFormatter(std::ostream& ss, std::string prefix) : ss(ss), prefix(std::move(prefix)) { } /* The supplied css_path can be empty. In such situation a default, * embedded style sheet will be generated. */ void generate_header(const std::string& dir_path, const std::string& css_path); void generate_footer(); void dump_object(const rgw_bucket_dir_entry& objent); void dump_subdir(const std::string& name); }; class RGWFormatterFlusher { protected: Formatter *formatter; bool flushed; bool started; virtual void do_flush() = 0; virtual void do_start(int ret) {} void set_formatter(Formatter *f) { formatter = f; } public: explicit RGWFormatterFlusher(Formatter *f) : formatter(f), flushed(false), started(false) {} virtual ~RGWFormatterFlusher() {} void flush() { do_flush(); flushed = true; } virtual void start(int client_ret) { if (!started) do_start(client_ret); started = true; } Formatter *get_formatter() { return formatter; } bool did_flush() { return flushed; } bool did_start() { return started; } }; class RGWStreamFlusher : public RGWFormatterFlusher { std::ostream& os; protected: void do_flush() override { formatter->flush(os); } public: RGWStreamFlusher(Formatter *f, std::ostream& _os) : RGWFormatterFlusher(f), os(_os) {} }; class RGWNullFlusher : public RGWFormatterFlusher { protected: void do_flush() override { } public: RGWNullFlusher() : RGWFormatterFlusher(nullptr) {} };
3,776
27.186567
112
h
null
ceph-main/src/rgw/rgw_frontend.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <signal.h> #include "rgw_frontend.h" #include "include/str_list.h" #include "include/ceph_assert.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; int RGWFrontendConfig::parse_config(const string& config, std::multimap<string, string>& config_map) { for (auto& entry : get_str_vec(config, " ")) { string key; string val; if (framework.empty()) { framework = entry; dout(0) << "framework: " << framework << dendl; continue; } ssize_t pos = entry.find('='); if (pos < 0) { dout(0) << "framework conf key: " << entry << dendl; config_map.emplace(std::move(entry), ""); continue; } int ret = parse_key_value(entry, key, val); if (ret < 0) { cerr << "ERROR: can't parse " << entry << std::endl; return ret; } dout(0) << "framework conf key: " << key << ", val: " << val << dendl; config_map.emplace(std::move(key), std::move(val)); } return 0; } void RGWFrontendConfig::set_default_config(RGWFrontendConfig& def_conf) { const auto& def_conf_map = def_conf.get_config_map(); for (auto& entry : def_conf_map) { if (config_map.find(entry.first) == config_map.end()) { config_map.emplace(entry.first, entry.second); } } } std::optional<string> RGWFrontendConfig::get_val(const std::string& key) { auto iter = config_map.find(key); if (iter == config_map.end()) { return std::nullopt; } return iter->second; } bool RGWFrontendConfig::get_val(const string& key, const string& def_val, string *out) { auto iter = config_map.find(key); if (iter == config_map.end()) { *out = def_val; return false; } *out = iter->second; return true; } bool RGWFrontendConfig::get_val(const string& key, int def_val, int *out) { string str; bool found = get_val(key, "", &str); if (!found) { *out = def_val; return false; } string err; *out = strict_strtol(str.c_str(), 10, &err); if (!err.empty()) { cerr << "error parsing int: " << str << ": " << err << std::endl; return -EINVAL; } return 0; } void RGWProcessFrontend::stop() { pprocess->close_fd(); thread->kill(SIGUSR1); }
2,318
20.877358
74
cc
null
ceph-main/src/rgw/rgw_frontend.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <map> #include <string> #include <vector> #include "common/RWLock.h" #include "rgw_request.h" #include "rgw_process.h" #include "rgw_process_env.h" #include "rgw_realm_reloader.h" #include "rgw_auth_registry.h" #include "rgw_sal_rados.h" #define dout_context g_ceph_context namespace rgw::dmclock { class SyncScheduler; class ClientConfig; class SchedulerCtx; } class RGWFrontendConfig { std::string config; std::multimap<std::string, std::string> config_map; std::string framework; int parse_config(const std::string& config, std::multimap<std::string, std::string>& config_map); public: explicit RGWFrontendConfig(const std::string& config) : config(config) { } int init() { const int ret = parse_config(config, config_map); return ret < 0 ? ret : 0; } void set_default_config(RGWFrontendConfig& def_conf); std::optional<std::string> get_val(const std::string& key); bool get_val(const std::string& key, const std::string& def_val, std::string* out); bool get_val(const std::string& key, int def_val, int *out); std::string get_val(const std::string& key, const std::string& def_val) { std::string out; get_val(key, def_val, &out); return out; } const std::string& get_config() { return config; } std::multimap<std::string, std::string>& get_config_map() { return config_map; } std::string get_framework() const { return framework; } }; class RGWFrontend { public: virtual ~RGWFrontend() {} virtual int init() = 0; virtual int run() = 0; virtual void stop() = 0; virtual void join() = 0; virtual void pause_for_new_config() = 0; virtual void unpause_with_new_config() = 0; }; class RGWProcessFrontend : public RGWFrontend { protected: RGWFrontendConfig* conf; RGWProcess* pprocess; RGWProcessEnv& env; RGWProcessControlThread* thread; public: RGWProcessFrontend(RGWProcessEnv& pe, RGWFrontendConfig* _conf) : conf(_conf), pprocess(nullptr), env(pe), thread(nullptr) { } ~RGWProcessFrontend() override { delete thread; delete pprocess; } int run() override { ceph_assert(pprocess); /* should have initialized by init() */ thread = new RGWProcessControlThread(pprocess); thread->create("rgw_frontend"); return 0; } void stop() override; void join() override { thread->join(); } void pause_for_new_config() override { pprocess->pause(); } void unpause_with_new_config() override { pprocess->unpause_with_new_config(); } }; /* RGWProcessFrontend */ class RGWLoadGenFrontend : public RGWProcessFrontend, public DoutPrefixProvider { public: RGWLoadGenFrontend(RGWProcessEnv& pe, RGWFrontendConfig *_conf) : RGWProcessFrontend(pe, _conf) {} CephContext *get_cct() const { return env.driver->ctx(); } unsigned get_subsys() const { return ceph_subsys_rgw; } std::ostream& gen_prefix(std::ostream& out) const { return out << "rgw loadgen frontend: "; } int init() override { int num_threads; conf->get_val("num_threads", g_conf()->rgw_thread_pool_size, &num_threads); std::string uri_prefix; conf->get_val("prefix", "", &uri_prefix); RGWLoadGenProcess *pp = new RGWLoadGenProcess( g_ceph_context, env, num_threads, std::move(uri_prefix), conf); pprocess = pp; std::string uid_str; conf->get_val("uid", "", &uid_str); if (uid_str.empty()) { derr << "ERROR: uid param must be specified for loadgen frontend" << dendl; return -EINVAL; } rgw_user uid(uid_str); std::unique_ptr<rgw::sal::User> user = env.driver->get_user(uid); int ret = user->load_user(this, null_yield); if (ret < 0) { derr << "ERROR: failed reading user info: uid=" << uid << " ret=" << ret << dendl; return ret; } auto aiter = user->get_info().access_keys.begin(); if (aiter == user->get_info().access_keys.end()) { derr << "ERROR: user has no S3 access keys set" << dendl; return -EINVAL; } pp->set_access_key(aiter->second); return 0; } }; /* RGWLoadGenFrontend */ // FrontendPauser implementation for RGWRealmReloader class RGWFrontendPauser : public RGWRealmReloader::Pauser { std::vector<RGWFrontend*> &frontends; RGWRealmReloader::Pauser* pauser; public: RGWFrontendPauser(std::vector<RGWFrontend*> &frontends, RGWRealmReloader::Pauser* pauser = nullptr) : frontends(frontends), pauser(pauser) {} void pause() override { for (auto frontend : frontends) frontend->pause_for_new_config(); if (pauser) pauser->pause(); } void resume(rgw::sal::Driver* driver) override { for (auto frontend : frontends) frontend->unpause_with_new_config(); if (pauser) pauser->resume(driver); } };
5,004
22.608491
81
h
null
ceph-main/src/rgw/rgw_gc_log.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "include/rados/librados.hpp" #include "cls/rgw/cls_rgw_types.h" // initialize the cls_rgw_gc queue void gc_log_init2(librados::ObjectWriteOperation& op, uint64_t max_size, uint64_t max_deferred); // enqueue a gc entry to omap with cls_rgw void gc_log_enqueue1(librados::ObjectWriteOperation& op, uint32_t expiration, cls_rgw_gc_obj_info& info); // enqueue a gc entry to the cls_rgw_gc queue void gc_log_enqueue2(librados::ObjectWriteOperation& op, uint32_t expiration, const cls_rgw_gc_obj_info& info); // defer a gc entry in omap with cls_rgw void gc_log_defer1(librados::ObjectWriteOperation& op, uint32_t expiration, const cls_rgw_gc_obj_info& info); // defer a gc entry in the cls_rgw_gc queue void gc_log_defer2(librados::ObjectWriteOperation& op, uint32_t expiration, const cls_rgw_gc_obj_info& info);
1,041
34.931034
75
h
null
ceph-main/src/rgw/rgw_http_client.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "include/compat.h" #include "common/errno.h" #include <curl/curl.h> #include <curl/easy.h> #include <curl/multi.h> #include "rgw_common.h" #include "rgw_http_client.h" #include "rgw_http_errors.h" #include "common/async/completion.h" #include "common/RefCountedObj.h" #include "rgw_coroutine.h" #include "rgw_tools.h" #include <atomic> #include <string_view> #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw using namespace std; RGWHTTPManager *rgw_http_manager; struct RGWCurlHandle; static void do_curl_easy_cleanup(RGWCurlHandle *curl_handle); struct rgw_http_req_data : public RefCountedObject { RGWCurlHandle *curl_handle{nullptr}; curl_slist *h{nullptr}; uint64_t id; int ret{0}; std::atomic<bool> done = { false }; RGWHTTPClient *client{nullptr}; rgw_io_id control_io_id; void *user_info{nullptr}; bool registered{false}; RGWHTTPManager *mgr{nullptr}; char error_buf[CURL_ERROR_SIZE]; bool write_paused{false}; bool read_paused{false}; optional<int> user_ret; ceph::mutex lock = ceph::make_mutex("rgw_http_req_data::lock"); ceph::condition_variable cond; using Signature = void(boost::system::error_code); using Completion = ceph::async::Completion<Signature>; std::unique_ptr<Completion> completion; rgw_http_req_data() : id(-1) { // FIPS zeroization audit 20191115: this memset is not security related. memset(error_buf, 0, sizeof(error_buf)); } template <typename ExecutionContext, typename CompletionToken> auto async_wait(ExecutionContext& ctx, CompletionToken&& token) { boost::asio::async_completion<CompletionToken, Signature> init(token); auto& handler = init.completion_handler; { std::unique_lock l{lock}; completion = Completion::create(ctx.get_executor(), std::move(handler)); } return init.result.get(); } int wait(optional_yield y) { if (done) { return ret; } if (y) { auto& context = y.get_io_context(); auto& yield = y.get_yield_context(); boost::system::error_code ec; async_wait(context, yield[ec]); return -ec.value(); } // work on asio threads should be asynchronous, so warn when they block if (is_asio_thread) { dout(20) << "WARNING: blocking http request" << dendl; } std::unique_lock l{lock}; cond.wait(l, [this]{return done==true;}); return ret; } void set_state(int bitmask); void finish(int r, long http_status = -1) { std::lock_guard l{lock}; if (http_status != -1) { if (client) { client->set_http_status(http_status); } } ret = r; if (curl_handle) do_curl_easy_cleanup(curl_handle); if (h) curl_slist_free_all(h); curl_handle = NULL; h = NULL; done = true; if (completion) { boost::system::error_code ec(-ret, boost::system::system_category()); Completion::post(std::move(completion), ec); } else { cond.notify_all(); } } bool is_done() { return done; } int get_retcode() { std::lock_guard l{lock}; return ret; } RGWHTTPManager *get_manager() { std::lock_guard l{lock}; return mgr; } CURL *get_easy_handle() const; }; struct RGWCurlHandle { int uses; mono_time lastuse; CURL* h; explicit RGWCurlHandle(CURL* h) : uses(0), h(h) {}; CURL* operator*() { return this->h; } }; void rgw_http_req_data::set_state(int bitmask) { /* no need to lock here, moreover curl_easy_pause() might trigger * the data receive callback :/ */ CURLcode rc = curl_easy_pause(**curl_handle, bitmask); if (rc != CURLE_OK) { dout(0) << "ERROR: curl_easy_pause() returned rc=" << rc << dendl; } } #define MAXIDLE 5 class RGWCurlHandles : public Thread { public: ceph::mutex cleaner_lock = ceph::make_mutex("RGWCurlHandles::cleaner_lock"); std::vector<RGWCurlHandle*> saved_curl; int cleaner_shutdown; ceph::condition_variable cleaner_cond; RGWCurlHandles() : cleaner_shutdown{0} { } RGWCurlHandle* get_curl_handle(); void release_curl_handle_now(RGWCurlHandle* curl); void release_curl_handle(RGWCurlHandle* curl); void flush_curl_handles(); void* entry(); void stop(); }; RGWCurlHandle* RGWCurlHandles::get_curl_handle() { RGWCurlHandle* curl = 0; CURL* h; { std::lock_guard lock{cleaner_lock}; if (!saved_curl.empty()) { curl = *saved_curl.begin(); saved_curl.erase(saved_curl.begin()); } } if (curl) { } else if ((h = curl_easy_init())) { curl = new RGWCurlHandle{h}; } else { // curl = 0; } return curl; } void RGWCurlHandles::release_curl_handle_now(RGWCurlHandle* curl) { curl_easy_cleanup(**curl); delete curl; } void RGWCurlHandles::release_curl_handle(RGWCurlHandle* curl) { if (cleaner_shutdown) { release_curl_handle_now(curl); } else { curl_easy_reset(**curl); std::lock_guard lock{cleaner_lock}; curl->lastuse = mono_clock::now(); saved_curl.insert(saved_curl.begin(), 1, curl); } } void* RGWCurlHandles::entry() { RGWCurlHandle* curl; std::unique_lock lock{cleaner_lock}; for (;;) { if (cleaner_shutdown) { if (saved_curl.empty()) break; } else { cleaner_cond.wait_for(lock, std::chrono::seconds(MAXIDLE)); } mono_time now = mono_clock::now(); while (!saved_curl.empty()) { auto cend = saved_curl.end(); --cend; curl = *cend; if (!cleaner_shutdown && now - curl->lastuse < std::chrono::seconds(MAXIDLE)) break; saved_curl.erase(cend); release_curl_handle_now(curl); } } return nullptr; } void RGWCurlHandles::stop() { std::lock_guard lock{cleaner_lock}; cleaner_shutdown = 1; cleaner_cond.notify_all(); } void RGWCurlHandles::flush_curl_handles() { stop(); join(); if (!saved_curl.empty()) { dout(0) << "ERROR: " << __func__ << " failed final cleanup" << dendl; } saved_curl.shrink_to_fit(); } CURL *rgw_http_req_data::get_easy_handle() const { return **curl_handle; } static RGWCurlHandles *handles; static RGWCurlHandle *do_curl_easy_init() { return handles->get_curl_handle(); } static void do_curl_easy_cleanup(RGWCurlHandle *curl_handle) { handles->release_curl_handle(curl_handle); } // XXX make this part of the token cache? (but that's swift-only; // and this especially needs to integrates with s3...) void rgw_setup_saved_curl_handles() { handles = new RGWCurlHandles(); handles->create("rgw_curl"); } void rgw_release_all_curl_handles() { handles->flush_curl_handles(); delete handles; } void RGWIOProvider::assign_io(RGWIOIDProvider& io_id_provider, int io_type) { if (id == 0) { id = io_id_provider.get_next(); } } RGWHTTPClient::RGWHTTPClient(CephContext *cct, const string& _method, const string& _url) : NoDoutPrefix(cct, dout_subsys), has_send_len(false), http_status(HTTP_STATUS_NOSTATUS), req_data(nullptr), verify_ssl(cct->_conf->rgw_verify_ssl), cct(cct), method(_method), url(_url) { init(); } std::ostream& RGWHTTPClient::gen_prefix(std::ostream& out) const { out << "http_client[" << method << "/" << url << "]"; return out; } void RGWHTTPClient::init() { auto pos = url.find("://"); if (pos == string::npos) { host = url; return; } protocol = url.substr(0, pos); pos += 3; auto host_end_pos = url.find("/", pos); if (host_end_pos == string::npos) { host = url.substr(pos); return; } host = url.substr(pos, host_end_pos - pos); resource_prefix = url.substr(host_end_pos + 1); if (resource_prefix.size() > 0 && resource_prefix[resource_prefix.size() - 1] != '/') { resource_prefix.append("/"); } } /* * the following set of callbacks will be called either on RGWHTTPManager::process(), * or via the RGWHTTPManager async processing. */ size_t RGWHTTPClient::receive_http_header(void * const ptr, const size_t size, const size_t nmemb, void * const _info) { rgw_http_req_data *req_data = static_cast<rgw_http_req_data *>(_info); size_t len = size * nmemb; std::lock_guard l{req_data->lock}; if (!req_data->registered) { return len; } int ret = req_data->client->receive_header(ptr, size * nmemb); if (ret < 0) { dout(5) << "WARNING: client->receive_header() returned ret=" << ret << dendl; req_data->user_ret = ret; return CURLE_WRITE_ERROR; } return len; } size_t RGWHTTPClient::receive_http_data(void * const ptr, const size_t size, const size_t nmemb, void * const _info) { rgw_http_req_data *req_data = static_cast<rgw_http_req_data *>(_info); size_t len = size * nmemb; bool pause = false; RGWHTTPClient *client; { std::lock_guard l{req_data->lock}; if (!req_data->registered) { return len; } client = req_data->client; } size_t& skip_bytes = client->receive_pause_skip; if (skip_bytes >= len) { skip_bytes -= len; return len; } int ret = client->receive_data((char *)ptr + skip_bytes, len - skip_bytes, &pause); if (ret < 0) { dout(5) << "WARNING: client->receive_data() returned ret=" << ret << dendl; req_data->user_ret = ret; return CURLE_WRITE_ERROR; } if (pause) { dout(20) << "RGWHTTPClient::receive_http_data(): pause" << dendl; skip_bytes = len; std::lock_guard l{req_data->lock}; req_data->read_paused = true; return CURL_WRITEFUNC_PAUSE; } skip_bytes = 0; return len; } size_t RGWHTTPClient::send_http_data(void * const ptr, const size_t size, const size_t nmemb, void * const _info) { rgw_http_req_data *req_data = static_cast<rgw_http_req_data *>(_info); RGWHTTPClient *client; { std::lock_guard l{req_data->lock}; if (!req_data->registered) { return 0; } client = req_data->client; } bool pause = false; int ret = client->send_data(ptr, size * nmemb, &pause); if (ret < 0) { dout(5) << "WARNING: client->send_data() returned ret=" << ret << dendl; req_data->user_ret = ret; return CURLE_READ_ERROR; } if (ret == 0 && pause) { std::lock_guard l{req_data->lock}; req_data->write_paused = true; return CURL_READFUNC_PAUSE; } return ret; } ceph::mutex& RGWHTTPClient::get_req_lock() { return req_data->lock; } void RGWHTTPClient::_set_write_paused(bool pause) { ceph_assert(ceph_mutex_is_locked(req_data->lock)); RGWHTTPManager *mgr = req_data->mgr; if (pause == req_data->write_paused) { return; } if (pause) { mgr->set_request_state(this, SET_WRITE_PAUSED); } else { mgr->set_request_state(this, SET_WRITE_RESUME); } } void RGWHTTPClient::_set_read_paused(bool pause) { ceph_assert(ceph_mutex_is_locked(req_data->lock)); RGWHTTPManager *mgr = req_data->mgr; if (pause == req_data->read_paused) { return; } if (pause) { mgr->set_request_state(this, SET_READ_PAUSED); } else { mgr->set_request_state(this, SET_READ_RESUME); } } static curl_slist *headers_to_slist(param_vec_t& headers) { curl_slist *h = NULL; param_vec_t::iterator iter; for (iter = headers.begin(); iter != headers.end(); ++iter) { pair<string, string>& p = *iter; string val = p.first; if (strncmp(val.c_str(), "HTTP_", 5) == 0) { val = val.substr(5); } /* we need to convert all underscores into dashes as some web servers forbid them * in the http header field names */ for (size_t i = 0; i < val.size(); i++) { if (val[i] == '_') { val[i] = '-'; } } val = camelcase_dash_http_attr(val); // curl won't send headers with empty values unless it ends with a ; instead if (p.second.empty()) { val.append(1, ';'); } else { val.append(": "); val.append(p.second); } h = curl_slist_append(h, val.c_str()); } return h; } static bool is_upload_request(const string& method) { return method == "POST" || method == "PUT"; } /* * process a single simple one off request */ int RGWHTTPClient::process(optional_yield y) { return RGWHTTP::process(this, y); } string RGWHTTPClient::to_str() { string method_str = (method.empty() ? "<no-method>" : method); string url_str = (url.empty() ? "<no-url>" : url); return method_str + " " + url_str; } int RGWHTTPClient::get_req_retcode() { if (!req_data) { return -EINVAL; } return req_data->get_retcode(); } /* * init request, will be used later with RGWHTTPManager */ int RGWHTTPClient::init_request(rgw_http_req_data *_req_data) { ceph_assert(!req_data); _req_data->get(); req_data = _req_data; req_data->curl_handle = do_curl_easy_init(); CURL *easy_handle = req_data->get_easy_handle(); dout(20) << "sending request to " << url << dendl; curl_slist *h = headers_to_slist(headers); req_data->h = h; curl_easy_setopt(easy_handle, CURLOPT_CUSTOMREQUEST, method.c_str()); curl_easy_setopt(easy_handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easy_handle, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(easy_handle, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(easy_handle, CURLOPT_HEADERFUNCTION, receive_http_header); curl_easy_setopt(easy_handle, CURLOPT_WRITEHEADER, (void *)req_data); curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, receive_http_data); curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, (void *)req_data); curl_easy_setopt(easy_handle, CURLOPT_ERRORBUFFER, (void *)req_data->error_buf); curl_easy_setopt(easy_handle, CURLOPT_LOW_SPEED_TIME, cct->_conf->rgw_curl_low_speed_time); curl_easy_setopt(easy_handle, CURLOPT_LOW_SPEED_LIMIT, cct->_conf->rgw_curl_low_speed_limit); curl_easy_setopt(easy_handle, CURLOPT_TCP_KEEPALIVE, cct->_conf->rgw_curl_tcp_keepalive); curl_easy_setopt(easy_handle, CURLOPT_READFUNCTION, send_http_data); curl_easy_setopt(easy_handle, CURLOPT_READDATA, (void *)req_data); curl_easy_setopt(easy_handle, CURLOPT_BUFFERSIZE, cct->_conf->rgw_curl_buffersize); if (send_data_hint || is_upload_request(method)) { curl_easy_setopt(easy_handle, CURLOPT_UPLOAD, 1L); } if (has_send_len) { // TODO: prevent overflow by using curl_off_t // and: CURLOPT_INFILESIZE_LARGE, CURLOPT_POSTFIELDSIZE_LARGE const long size = send_len; curl_easy_setopt(easy_handle, CURLOPT_INFILESIZE, size); if (method == "POST") { curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDSIZE, size); // TODO: set to size smaller than 1MB should prevent the "Expect" field // from being sent. So explicit removal is not needed h = curl_slist_append(h, "Expect:"); } } if (method == "HEAD") { curl_easy_setopt(easy_handle, CURLOPT_NOBODY, 1L); } if (h) { curl_easy_setopt(easy_handle, CURLOPT_HTTPHEADER, (void *)h); } if (!verify_ssl) { curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYHOST, 0L); dout(20) << "ssl verification is set to off" << dendl; } else { if (!ca_path.empty()) { curl_easy_setopt(easy_handle, CURLOPT_CAINFO, ca_path.c_str()); dout(20) << "using custom ca cert "<< ca_path.c_str() << " for ssl" << dendl; } if (!client_cert.empty()) { if (!client_key.empty()) { curl_easy_setopt(easy_handle, CURLOPT_SSLCERT, client_cert.c_str()); curl_easy_setopt(easy_handle, CURLOPT_SSLKEY, client_key.c_str()); dout(20) << "using custom client cert " << client_cert.c_str() << " and private key " << client_key.c_str() << dendl; } else { dout(5) << "private key is missing for client certificate" << dendl; } } } curl_easy_setopt(easy_handle, CURLOPT_PRIVATE, (void *)req_data); curl_easy_setopt(easy_handle, CURLOPT_TIMEOUT, req_timeout); return 0; } bool RGWHTTPClient::is_done() { return req_data->is_done(); } /* * wait for async request to complete */ int RGWHTTPClient::wait(optional_yield y) { return req_data->wait(y); } void RGWHTTPClient::cancel() { if (req_data) { RGWHTTPManager *http_manager = req_data->mgr; if (http_manager) { http_manager->remove_request(this); } } } RGWHTTPClient::~RGWHTTPClient() { cancel(); if (req_data) { req_data->put(); } } int RGWHTTPHeadersCollector::receive_header(void * const ptr, const size_t len) { const std::string_view header_line(static_cast<const char *>(ptr), len); /* We're tokening the line that way due to backward compatibility. */ const size_t sep_loc = header_line.find_first_of(" \t:"); if (std::string_view::npos == sep_loc) { /* Wrongly formatted header? Just skip it. */ return 0; } header_name_t name(header_line.substr(0, sep_loc)); if (0 == relevant_headers.count(name)) { /* Not interested in this particular header. */ return 0; } const auto value_part = header_line.substr(sep_loc + 1); /* Skip spaces and tabs after the separator. */ const size_t val_loc_s = value_part.find_first_not_of(' '); const size_t val_loc_e = value_part.find_first_of("\r\n"); if (std::string_view::npos == val_loc_s || std::string_view::npos == val_loc_e) { /* Empty value case. */ found_headers.emplace(name, header_value_t()); } else { found_headers.emplace(name, header_value_t( value_part.substr(val_loc_s, val_loc_e - val_loc_s))); } return 0; } int RGWHTTPTransceiver::send_data(void* ptr, size_t len, bool* pause) { int length_to_copy = 0; if (post_data_index < post_data.length()) { length_to_copy = min(post_data.length() - post_data_index, len); memcpy(ptr, post_data.data() + post_data_index, length_to_copy); post_data_index += length_to_copy; } return length_to_copy; } static int clear_signal(int fd) { // since we're in non-blocking mode, we can try to read a lot more than // one signal from signal_thread() to avoid later wakeups std::array<char, 256> buf{}; int ret = ::read(fd, (void *)buf.data(), buf.size()); if (ret < 0) { ret = -errno; return ret == -EAGAIN ? 0 : ret; // clear EAGAIN } return 0; } static int do_curl_wait(CephContext *cct, CURLM *handle, int signal_fd) { int num_fds; struct curl_waitfd wait_fd; wait_fd.fd = signal_fd; wait_fd.events = CURL_WAIT_POLLIN; wait_fd.revents = 0; int ret = curl_multi_wait(handle, &wait_fd, 1, cct->_conf->rgw_curl_wait_timeout_ms, &num_fds); if (ret) { ldout(cct, 0) << "ERROR: curl_multi_wait() returned " << ret << dendl; return -EIO; } if (wait_fd.revents > 0) { ret = clear_signal(signal_fd); if (ret < 0) { ldout(cct, 0) << "ERROR: " << __func__ << "(): read() returned " << ret << dendl; return ret; } } return 0; } void *RGWHTTPManager::ReqsThread::entry() { manager->reqs_thread_entry(); return NULL; } /* * RGWHTTPManager has two modes of operation: threaded and non-threaded. */ RGWHTTPManager::RGWHTTPManager(CephContext *_cct, RGWCompletionManager *_cm) : cct(_cct), completion_mgr(_cm) { multi_handle = (void *)curl_multi_init(); thread_pipe[0] = -1; thread_pipe[1] = -1; } RGWHTTPManager::~RGWHTTPManager() { stop(); if (multi_handle) curl_multi_cleanup((CURLM *)multi_handle); } void RGWHTTPManager::register_request(rgw_http_req_data *req_data) { std::unique_lock rl{reqs_lock}; req_data->id = num_reqs; req_data->registered = true; reqs[num_reqs] = req_data; num_reqs++; ldout(cct, 20) << __func__ << " mgr=" << this << " req_data->id=" << req_data->id << ", curl_handle=" << req_data->curl_handle << dendl; } bool RGWHTTPManager::unregister_request(rgw_http_req_data *req_data) { std::unique_lock rl{reqs_lock}; if (!req_data->registered) { return false; } req_data->get(); req_data->registered = false; unregistered_reqs.push_back(req_data); ldout(cct, 20) << __func__ << " mgr=" << this << " req_data->id=" << req_data->id << ", curl_handle=" << req_data->curl_handle << dendl; return true; } void RGWHTTPManager::complete_request(rgw_http_req_data *req_data) { std::unique_lock rl{reqs_lock}; _complete_request(req_data); } void RGWHTTPManager::_complete_request(rgw_http_req_data *req_data) { map<uint64_t, rgw_http_req_data *>::iterator iter = reqs.find(req_data->id); if (iter != reqs.end()) { reqs.erase(iter); } { std::lock_guard l{req_data->lock}; req_data->mgr = nullptr; } if (completion_mgr) { completion_mgr->complete(NULL, req_data->control_io_id, req_data->user_info); } req_data->put(); } void RGWHTTPManager::finish_request(rgw_http_req_data *req_data, int ret, long http_status) { req_data->finish(ret, http_status); complete_request(req_data); } void RGWHTTPManager::_finish_request(rgw_http_req_data *req_data, int ret) { req_data->finish(ret); _complete_request(req_data); } void RGWHTTPManager::_set_req_state(set_state& ss) { ss.req->set_state(ss.bitmask); } /* * hook request to the curl multi handle */ int RGWHTTPManager::link_request(rgw_http_req_data *req_data) { ldout(cct, 20) << __func__ << " req_data=" << req_data << " req_data->id=" << req_data->id << ", curl_handle=" << req_data->curl_handle << dendl; CURLMcode mstatus = curl_multi_add_handle((CURLM *)multi_handle, req_data->get_easy_handle()); if (mstatus) { dout(0) << "ERROR: failed on curl_multi_add_handle, status=" << mstatus << dendl; return -EIO; } return 0; } /* * unhook request from the curl multi handle, and finish request if it wasn't finished yet as * there will be no more processing on this request */ void RGWHTTPManager::_unlink_request(rgw_http_req_data *req_data) { if (req_data->curl_handle) { curl_multi_remove_handle((CURLM *)multi_handle, req_data->get_easy_handle()); } if (!req_data->is_done()) { _finish_request(req_data, -ECANCELED); } } void RGWHTTPManager::unlink_request(rgw_http_req_data *req_data) { std::unique_lock wl{reqs_lock}; _unlink_request(req_data); } void RGWHTTPManager::manage_pending_requests() { reqs_lock.lock_shared(); if (max_threaded_req == num_reqs && unregistered_reqs.empty() && reqs_change_state.empty()) { reqs_lock.unlock_shared(); return; } reqs_lock.unlock_shared(); std::unique_lock wl{reqs_lock}; if (!reqs_change_state.empty()) { for (auto siter : reqs_change_state) { _set_req_state(siter); } reqs_change_state.clear(); } if (!unregistered_reqs.empty()) { for (auto& r : unregistered_reqs) { _unlink_request(r); r->put(); } unregistered_reqs.clear(); } map<uint64_t, rgw_http_req_data *>::iterator iter = reqs.find(max_threaded_req); list<std::pair<rgw_http_req_data *, int> > remove_reqs; for (; iter != reqs.end(); ++iter) { rgw_http_req_data *req_data = iter->second; int r = link_request(req_data); if (r < 0) { ldout(cct, 0) << "ERROR: failed to link http request" << dendl; remove_reqs.push_back(std::make_pair(iter->second, r)); } else { max_threaded_req = iter->first + 1; } } for (auto piter : remove_reqs) { rgw_http_req_data *req_data = piter.first; int r = piter.second; _finish_request(req_data, r); } } int RGWHTTPManager::add_request(RGWHTTPClient *client) { rgw_http_req_data *req_data = new rgw_http_req_data; int ret = client->init_request(req_data); if (ret < 0) { req_data->put(); req_data = NULL; return ret; } req_data->mgr = this; req_data->client = client; req_data->control_io_id = client->get_io_id(RGWHTTPClient::HTTPCLIENT_IO_CONTROL); req_data->user_info = client->get_io_user_info(); register_request(req_data); if (!is_started) { ret = link_request(req_data); if (ret < 0) { req_data->put(); req_data = NULL; } return ret; } ret = signal_thread(); if (ret < 0) { finish_request(req_data, ret); } return ret; } int RGWHTTPManager::remove_request(RGWHTTPClient *client) { rgw_http_req_data *req_data = client->get_req_data(); if (!is_started) { unlink_request(req_data); return 0; } if (!unregister_request(req_data)) { return 0; } int ret = signal_thread(); if (ret < 0) { return ret; } return 0; } int RGWHTTPManager::set_request_state(RGWHTTPClient *client, RGWHTTPRequestSetState state) { rgw_http_req_data *req_data = client->get_req_data(); ceph_assert(ceph_mutex_is_locked(req_data->lock)); /* can only do that if threaded */ if (!is_started) { return -EINVAL; } bool suggested_wr_paused = req_data->write_paused; bool suggested_rd_paused = req_data->read_paused; switch (state) { case SET_WRITE_PAUSED: suggested_wr_paused = true; break; case SET_WRITE_RESUME: suggested_wr_paused = false; break; case SET_READ_PAUSED: suggested_rd_paused = true; break; case SET_READ_RESUME: suggested_rd_paused = false; break; default: /* shouldn't really be here */ return -EIO; } if (suggested_wr_paused == req_data->write_paused && suggested_rd_paused == req_data->read_paused) { return 0; } req_data->write_paused = suggested_wr_paused; req_data->read_paused = suggested_rd_paused; int bitmask = CURLPAUSE_CONT; if (req_data->write_paused) { bitmask |= CURLPAUSE_SEND; } if (req_data->read_paused) { bitmask |= CURLPAUSE_RECV; } reqs_change_state.push_back(set_state(req_data, bitmask)); int ret = signal_thread(); if (ret < 0) { return ret; } return 0; } int RGWHTTPManager::start() { if (pipe_cloexec(thread_pipe, 0) < 0) { int e = errno; ldout(cct, 0) << "ERROR: pipe(): " << cpp_strerror(e) << dendl; return -e; } // enable non-blocking reads if (::fcntl(thread_pipe[0], F_SETFL, O_NONBLOCK) < 0) { int e = errno; ldout(cct, 0) << "ERROR: fcntl(): " << cpp_strerror(e) << dendl; TEMP_FAILURE_RETRY(::close(thread_pipe[0])); TEMP_FAILURE_RETRY(::close(thread_pipe[1])); return -e; } is_started = true; reqs_thread = new ReqsThread(this); reqs_thread->create("http_manager"); return 0; } void RGWHTTPManager::stop() { if (is_stopped) { return; } is_stopped = true; if (is_started) { going_down = true; signal_thread(); reqs_thread->join(); delete reqs_thread; TEMP_FAILURE_RETRY(::close(thread_pipe[1])); TEMP_FAILURE_RETRY(::close(thread_pipe[0])); } } int RGWHTTPManager::signal_thread() { uint32_t buf = 0; int ret = write(thread_pipe[1], (void *)&buf, sizeof(buf)); if (ret < 0) { ret = -errno; ldout(cct, 0) << "ERROR: " << __func__ << ": write() returned ret=" << ret << dendl; return ret; } return 0; } void *RGWHTTPManager::reqs_thread_entry() { int still_running; int mstatus; ldout(cct, 20) << __func__ << ": start" << dendl; while (!going_down) { int ret = do_curl_wait(cct, (CURLM *)multi_handle, thread_pipe[0]); if (ret < 0) { dout(0) << "ERROR: do_curl_wait() returned: " << ret << dendl; return NULL; } manage_pending_requests(); mstatus = curl_multi_perform((CURLM *)multi_handle, &still_running); switch (mstatus) { case CURLM_OK: case CURLM_CALL_MULTI_PERFORM: break; default: dout(10) << "curl_multi_perform returned: " << mstatus << dendl; break; } int msgs_left; CURLMsg *msg; while ((msg = curl_multi_info_read((CURLM *)multi_handle, &msgs_left))) { if (msg->msg == CURLMSG_DONE) { int result = msg->data.result; CURL *e = msg->easy_handle; rgw_http_req_data *req_data; curl_easy_getinfo(e, CURLINFO_PRIVATE, (void **)&req_data); curl_multi_remove_handle((CURLM *)multi_handle, e); long http_status; int status; if (!req_data->user_ret) { curl_easy_getinfo(e, CURLINFO_RESPONSE_CODE, (void **)&http_status); status = rgw_http_error_to_errno(http_status); if (result != CURLE_OK && status == 0) { dout(0) << "ERROR: curl error: " << curl_easy_strerror((CURLcode)result) << ", maybe network unstable" << dendl; status = -EAGAIN; } } else { status = *req_data->user_ret; rgw_err err; set_req_state_err(err, status, 0); http_status = err.http_ret; } int id = req_data->id; finish_request(req_data, status, http_status); switch (result) { case CURLE_OK: break; case CURLE_OPERATION_TIMEDOUT: dout(0) << "WARNING: curl operation timed out, network average transfer speed less than " << cct->_conf->rgw_curl_low_speed_limit << " Bytes per second during " << cct->_conf->rgw_curl_low_speed_time << " seconds." << dendl; default: dout(20) << "ERROR: msg->data.result=" << result << " req_data->id=" << id << " http_status=" << http_status << dendl; dout(20) << "ERROR: curl error: " << curl_easy_strerror((CURLcode)result) << " req_data->error_buf=" << req_data->error_buf << dendl; break; } } } } std::unique_lock rl{reqs_lock}; for (auto r : unregistered_reqs) { _unlink_request(r); } unregistered_reqs.clear(); auto all_reqs = std::move(reqs); for (auto iter : all_reqs) { _unlink_request(iter.second); } reqs.clear(); if (completion_mgr) { completion_mgr->go_down(); } return 0; } void rgw_http_client_init(CephContext *cct) { curl_global_init(CURL_GLOBAL_ALL); rgw_http_manager = new RGWHTTPManager(cct); rgw_http_manager->start(); } void rgw_http_client_cleanup() { rgw_http_manager->stop(); delete rgw_http_manager; curl_global_cleanup(); } int RGWHTTP::send(RGWHTTPClient *req) { if (!req) { return 0; } int r = rgw_http_manager->add_request(req); if (r < 0) { return r; } return 0; } int RGWHTTP::process(RGWHTTPClient *req, optional_yield y) { if (!req) { return 0; } int r = send(req); if (r < 0) { return r; } return req->wait(y); }
30,536
23.948529
148
cc
null
ceph-main/src/rgw/rgw_http_client.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "common/async/yield_context.h" #include "common/Cond.h" #include "rgw_common.h" #include "rgw_string.h" #include "rgw_http_client_types.h" #include <atomic> using param_pair_t = std::pair<std::string, std::string>; using param_vec_t = std::vector<param_pair_t>; void rgw_http_client_init(CephContext *cct); void rgw_http_client_cleanup(); struct rgw_http_req_data; class RGWHTTPManager; class RGWHTTPClient : public RGWIOProvider, public NoDoutPrefix { friend class RGWHTTPManager; bufferlist send_bl; bufferlist::iterator send_iter; bool has_send_len; long http_status; bool send_data_hint{false}; size_t receive_pause_skip{0}; /* how many bytes to skip next time receive_data is called due to being paused */ void *user_info{nullptr}; rgw_http_req_data *req_data; bool verify_ssl; // Do not validate self signed certificates, default to false std::string ca_path; std::string client_cert; std::string client_key; std::atomic<unsigned> stopped { 0 }; protected: CephContext *cct; std::string method; std::string url; std::string protocol; std::string host; std::string resource_prefix; size_t send_len{0}; param_vec_t headers; long req_timeout{0L}; void init(); RGWHTTPManager *get_manager(); int init_request(rgw_http_req_data *req_data); virtual int receive_header(void *ptr, size_t len) { return 0; } virtual int receive_data(void *ptr, size_t len, bool *pause) { return 0; } virtual int send_data(void *ptr, size_t len, bool *pause=nullptr) { return 0; } /* Callbacks for libcurl. */ static size_t receive_http_header(void *ptr, size_t size, size_t nmemb, void *_info); static size_t receive_http_data(void *ptr, size_t size, size_t nmemb, void *_info); static size_t send_http_data(void *ptr, size_t size, size_t nmemb, void *_info); ceph::mutex& get_req_lock(); /* needs to be called under req_lock() */ void _set_write_paused(bool pause); void _set_read_paused(bool pause); public: static const long HTTP_STATUS_NOSTATUS = 0; static const long HTTP_STATUS_UNAUTHORIZED = 401; static const long HTTP_STATUS_NOTFOUND = 404; static constexpr int HTTPCLIENT_IO_READ = 0x1; static constexpr int HTTPCLIENT_IO_WRITE = 0x2; static constexpr int HTTPCLIENT_IO_CONTROL = 0x4; virtual ~RGWHTTPClient(); explicit RGWHTTPClient(CephContext *cct, const std::string& _method, const std::string& _url); std::ostream& gen_prefix(std::ostream& out) const override; void append_header(const std::string& name, const std::string& val) { headers.push_back(std::pair<std::string, std::string>(name, val)); } void set_send_length(size_t len) { send_len = len; has_send_len = true; } void set_send_data_hint(bool hint) { send_data_hint = hint; } long get_http_status() const { return http_status; } void set_http_status(long _http_status) { http_status = _http_status; } void set_verify_ssl(bool flag) { verify_ssl = flag; } // set request timeout in seconds // zero (default) mean that request will never timeout void set_req_timeout(long timeout) { req_timeout = timeout; } int process(optional_yield y); int wait(optional_yield y); void cancel(); bool is_done(); rgw_http_req_data *get_req_data() { return req_data; } std::string to_str(); int get_req_retcode(); void set_url(const std::string& _url) { url = _url; } void set_method(const std::string& _method) { method = _method; } void set_io_user_info(void *_user_info) override { user_info = _user_info; } void *get_io_user_info() override { return user_info; } void set_ca_path(const std::string& _ca_path) { ca_path = _ca_path; } void set_client_cert(const std::string& _client_cert) { client_cert = _client_cert; } void set_client_key(const std::string& _client_key) { client_key = _client_key; } }; class RGWHTTPHeadersCollector : public RGWHTTPClient { public: typedef std::string header_name_t; typedef std::string header_value_t; typedef std::set<header_name_t, ltstr_nocase> header_spec_t; RGWHTTPHeadersCollector(CephContext * const cct, const std::string& method, const std::string& url, const header_spec_t &relevant_headers) : RGWHTTPClient(cct, method, url), relevant_headers(relevant_headers) { } std::map<header_name_t, header_value_t, ltstr_nocase> get_headers() const { return found_headers; } /* Throws std::out_of_range */ const header_value_t& get_header_value(const header_name_t& name) const { return found_headers.at(name); } protected: int receive_header(void *ptr, size_t len) override; private: const std::set<header_name_t, ltstr_nocase> relevant_headers; std::map<header_name_t, header_value_t, ltstr_nocase> found_headers; }; class RGWHTTPTransceiver : public RGWHTTPHeadersCollector { bufferlist * const read_bl; std::string post_data; size_t post_data_index; public: RGWHTTPTransceiver(CephContext * const cct, const std::string& method, const std::string& url, bufferlist * const read_bl, const header_spec_t intercept_headers = {}) : RGWHTTPHeadersCollector(cct, method, url, intercept_headers), read_bl(read_bl), post_data_index(0) { } RGWHTTPTransceiver(CephContext * const cct, const std::string& method, const std::string& url, bufferlist * const read_bl, const bool verify_ssl, const header_spec_t intercept_headers = {}) : RGWHTTPHeadersCollector(cct, method, url, intercept_headers), read_bl(read_bl), post_data_index(0) { set_verify_ssl(verify_ssl); } void set_post_data(const std::string& _post_data) { this->post_data = _post_data; } protected: int send_data(void* ptr, size_t len, bool *pause=nullptr) override; int receive_data(void *ptr, size_t len, bool *pause) override { read_bl->append((char *)ptr, len); return 0; } }; typedef RGWHTTPTransceiver RGWPostHTTPData; class RGWCompletionManager; enum RGWHTTPRequestSetState { SET_NOP = 0, SET_WRITE_PAUSED = 1, SET_WRITE_RESUME = 2, SET_READ_PAUSED = 3, SET_READ_RESUME = 4, }; class RGWHTTPManager { struct set_state { rgw_http_req_data *req; int bitmask; set_state(rgw_http_req_data *_req, int _bitmask) : req(_req), bitmask(_bitmask) {} }; CephContext *cct; RGWCompletionManager *completion_mgr; void *multi_handle; bool is_started = false; std::atomic<unsigned> going_down { 0 }; std::atomic<unsigned> is_stopped { 0 }; ceph::shared_mutex reqs_lock = ceph::make_shared_mutex("RGWHTTPManager::reqs_lock"); std::map<uint64_t, rgw_http_req_data *> reqs; std::list<rgw_http_req_data *> unregistered_reqs; std::list<set_state> reqs_change_state; std::map<uint64_t, rgw_http_req_data *> complete_reqs; int64_t num_reqs = 0; int64_t max_threaded_req = 0; int thread_pipe[2]; void register_request(rgw_http_req_data *req_data); void complete_request(rgw_http_req_data *req_data); void _complete_request(rgw_http_req_data *req_data); bool unregister_request(rgw_http_req_data *req_data); void _unlink_request(rgw_http_req_data *req_data); void unlink_request(rgw_http_req_data *req_data); void finish_request(rgw_http_req_data *req_data, int r, long http_status = -1); void _finish_request(rgw_http_req_data *req_data, int r); void _set_req_state(set_state& ss); int link_request(rgw_http_req_data *req_data); void manage_pending_requests(); class ReqsThread : public Thread { RGWHTTPManager *manager; public: explicit ReqsThread(RGWHTTPManager *_m) : manager(_m) {} void *entry() override; }; ReqsThread *reqs_thread = nullptr; void *reqs_thread_entry(); int signal_thread(); public: RGWHTTPManager(CephContext *_cct, RGWCompletionManager *completion_mgr = NULL); ~RGWHTTPManager(); int start(); void stop(); int add_request(RGWHTTPClient *client); int remove_request(RGWHTTPClient *client); int set_request_state(RGWHTTPClient *client, RGWHTTPRequestSetState state); }; class RGWHTTP { public: static int send(RGWHTTPClient *req); static int process(RGWHTTPClient *req, optional_yield y); };
9,012
24.825215
90
h
null
ceph-main/src/rgw/rgw_http_client_curl.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_http_client_curl.h" #include <mutex> #include <vector> #include <curl/curl.h> #include "rgw_common.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_rgw #ifdef WITH_CURL_OPENSSL #include <openssl/crypto.h> #endif #if defined(WITH_CURL_OPENSSL) && OPENSSL_API_COMPAT < 0x10100000L namespace openssl { class RGWSSLSetup { std::vector <std::mutex> locks; public: explicit RGWSSLSetup(int n) : locks (n){} void set_lock(int id){ try { locks.at(id).lock(); } catch (std::out_of_range& e) { dout(0) << __func__ << " failed to set locks" << dendl; } } void clear_lock(int id){ try { locks.at(id).unlock(); } catch (std::out_of_range& e) { dout(0) << __func__ << " failed to unlock" << dendl; } } }; void rgw_ssl_locking_callback(int mode, int id, const char *file, int line) { static RGWSSLSetup locks(CRYPTO_num_locks()); if (mode & CRYPTO_LOCK) locks.set_lock(id); else locks.clear_lock(id); } unsigned long rgw_ssl_thread_id_callback(){ return (unsigned long)pthread_self(); } void init_ssl(){ CRYPTO_set_id_callback((unsigned long (*) ()) rgw_ssl_thread_id_callback); CRYPTO_set_locking_callback(rgw_ssl_locking_callback); } } /* namespace openssl */ #endif // WITH_CURL_OPENSSL namespace rgw { namespace curl { #if defined(WITH_CURL_OPENSSL) && OPENSSL_API_COMPAT < 0x10100000L void init_ssl() { ::openssl::init_ssl(); } bool fe_inits_ssl(boost::optional <const fe_map_t&> m, long& curl_global_flags){ if (m) { for (const auto& kv: *m){ if (kv.first == "beast"){ std::string cert; kv.second->get_val("ssl_certificate","", &cert); if (!cert.empty()){ /* TODO this flag is no op for curl > 7.57 */ curl_global_flags &= ~CURL_GLOBAL_SSL; return true; } } } } return false; } #endif // WITH_CURL_OPENSSL std::once_flag curl_init_flag; void setup_curl(boost::optional<const fe_map_t&> m) { long curl_global_flags = CURL_GLOBAL_ALL; #if defined(WITH_CURL_OPENSSL) && OPENSSL_API_COMPAT < 0x10100000L if (!fe_inits_ssl(m, curl_global_flags)) init_ssl(); #endif std::call_once(curl_init_flag, curl_global_init, curl_global_flags); rgw_setup_saved_curl_handles(); } void cleanup_curl() { rgw_release_all_curl_handles(); curl_global_cleanup(); } } /* namespace curl */ } /* namespace rgw */
2,530
21.39823
80
cc
null
ceph-main/src/rgw/rgw_http_client_curl.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2018 SUSE Linux GmBH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <map> #include <boost/optional.hpp> #include "rgw_frontend.h" namespace rgw { namespace curl { using fe_map_t = std::multimap <std::string, RGWFrontendConfig *>; void setup_curl(boost::optional<const fe_map_t&> m); void cleanup_curl(); } }
680
21.7
70
h
null
ceph-main/src/rgw/rgw_http_client_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp /* * Ceph - scalable distributed file system * * Copyright (C) 2019 Red Hat, Inc. * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #pragma once #include <atomic> struct rgw_io_id { int64_t id{0}; int channels{0}; rgw_io_id() {} rgw_io_id(int64_t _id, int _channels) : id(_id), channels(_channels) {} bool intersects(const rgw_io_id& rhs) { return (id == rhs.id && ((channels | rhs.channels) != 0)); } bool operator<(const rgw_io_id& rhs) const { if (id < rhs.id) { return true; } return (id == rhs.id && channels < rhs.channels); } }; class RGWIOIDProvider { std::atomic<int64_t> max = {0}; public: RGWIOIDProvider() {} int64_t get_next() { return ++max; } }; class RGWIOProvider { int64_t id{-1}; public: RGWIOProvider() {} virtual ~RGWIOProvider() = default; void assign_io(RGWIOIDProvider& io_id_provider, int io_type = -1); rgw_io_id get_io_id(int io_type) { return rgw_io_id{id, io_type}; } virtual void set_io_user_info(void *_user_info) = 0; virtual void *get_io_user_info() = 0; };
1,367
18.542857
73
h
null
ceph-main/src/rgw/rgw_http_errors.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "rgw_common.h" typedef const std::map<int,const std::pair<int, const char*>> rgw_http_errors; extern rgw_http_errors rgw_http_s3_errors; extern rgw_http_errors rgw_http_swift_errors; extern rgw_http_errors rgw_http_sts_errors; extern rgw_http_errors rgw_http_iam_errors; static inline int rgw_http_error_to_errno(int http_err) { if (http_err >= 200 && http_err <= 299) return 0; switch (http_err) { case 304: return -ERR_NOT_MODIFIED; case 400: return -EINVAL; case 401: return -EPERM; case 403: return -EACCES; case 404: return -ENOENT; case 405: return -ERR_METHOD_NOT_ALLOWED; case 409: return -ENOTEMPTY; case 503: return -EBUSY; default: return -EIO; } return 0; /* unreachable */ }
938
19.866667
78
h
null
ceph-main/src/rgw/rgw_iam_policy.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <cstring> #include <iostream> #include <regex> #include <sstream> #include <stack> #include <utility> #include <arpa/inet.h> #include <experimental/iterator> #include "rapidjson/reader.h" #include "include/expected.hpp" #include "rgw_auth.h" #include "rgw_iam_policy.h" namespace { constexpr int dout_subsys = ceph_subsys_rgw; } using std::dec; using std::hex; using std::int64_t; using std::size_t; using std::string; using std::stringstream; using std::ostream; using std::uint16_t; using std::uint64_t; using boost::container::flat_set; using std::regex; using std::regex_match; using std::smatch; using rapidjson::BaseReaderHandler; using rapidjson::UTF8; using rapidjson::SizeType; using rapidjson::Reader; using rapidjson::kParseCommentsFlag; using rapidjson::kParseNumbersAsStringsFlag; using rapidjson::StringStream; using rgw::auth::Principal; namespace rgw { namespace IAM { #include "rgw_iam_policy_keywords.frag.cc" struct actpair { const char* name; const uint64_t bit; }; static const actpair actpairs[] = {{ "s3:AbortMultipartUpload", s3AbortMultipartUpload }, { "s3:CreateBucket", s3CreateBucket }, { "s3:DeleteBucketPolicy", s3DeleteBucketPolicy }, { "s3:DeleteBucket", s3DeleteBucket }, { "s3:DeleteBucketWebsite", s3DeleteBucketWebsite }, { "s3:DeleteObject", s3DeleteObject }, { "s3:DeleteObjectVersion", s3DeleteObjectVersion }, { "s3:DeleteObjectTagging", s3DeleteObjectTagging }, { "s3:DeleteObjectVersionTagging", s3DeleteObjectVersionTagging }, { "s3:DeleteBucketPublicAccessBlock", s3DeleteBucketPublicAccessBlock}, { "s3:DeletePublicAccessBlock", s3DeletePublicAccessBlock}, { "s3:DeleteReplicationConfiguration", s3DeleteReplicationConfiguration }, { "s3:GetAccelerateConfiguration", s3GetAccelerateConfiguration }, { "s3:GetBucketAcl", s3GetBucketAcl }, { "s3:GetBucketCORS", s3GetBucketCORS }, { "s3:GetBucketEncryption", s3GetBucketEncryption }, { "s3:GetBucketLocation", s3GetBucketLocation }, { "s3:GetBucketLogging", s3GetBucketLogging }, { "s3:GetBucketNotification", s3GetBucketNotification }, { "s3:GetBucketPolicy", s3GetBucketPolicy }, { "s3:GetBucketPolicyStatus", s3GetBucketPolicyStatus }, { "s3:GetBucketPublicAccessBlock", s3GetBucketPublicAccessBlock }, { "s3:GetBucketRequestPayment", s3GetBucketRequestPayment }, { "s3:GetBucketTagging", s3GetBucketTagging }, { "s3:GetBucketVersioning", s3GetBucketVersioning }, { "s3:GetBucketWebsite", s3GetBucketWebsite }, { "s3:GetLifecycleConfiguration", s3GetLifecycleConfiguration }, { "s3:GetBucketObjectLockConfiguration", s3GetBucketObjectLockConfiguration }, { "s3:GetPublicAccessBlock", s3GetPublicAccessBlock }, { "s3:GetObjectAcl", s3GetObjectAcl }, { "s3:GetObject", s3GetObject }, { "s3:GetObjectTorrent", s3GetObjectTorrent }, { "s3:GetObjectVersionAcl", s3GetObjectVersionAcl }, { "s3:GetObjectVersion", s3GetObjectVersion }, { "s3:GetObjectVersionTorrent", s3GetObjectVersionTorrent }, { "s3:GetObjectTagging", s3GetObjectTagging }, { "s3:GetObjectVersionTagging", s3GetObjectVersionTagging}, { "s3:GetObjectRetention", s3GetObjectRetention}, { "s3:GetObjectLegalHold", s3GetObjectLegalHold}, { "s3:GetReplicationConfiguration", s3GetReplicationConfiguration }, { "s3:ListAllMyBuckets", s3ListAllMyBuckets }, { "s3:ListBucketMultipartUploads", s3ListBucketMultipartUploads }, { "s3:ListBucket", s3ListBucket }, { "s3:ListBucketVersions", s3ListBucketVersions }, { "s3:ListMultipartUploadParts", s3ListMultipartUploadParts }, { "s3:PutAccelerateConfiguration", s3PutAccelerateConfiguration }, { "s3:PutBucketAcl", s3PutBucketAcl }, { "s3:PutBucketCORS", s3PutBucketCORS }, { "s3:PutBucketEncryption", s3PutBucketEncryption }, { "s3:PutBucketLogging", s3PutBucketLogging }, { "s3:PutBucketNotification", s3PutBucketNotification }, { "s3:PutBucketPolicy", s3PutBucketPolicy }, { "s3:PutBucketRequestPayment", s3PutBucketRequestPayment }, { "s3:PutBucketTagging", s3PutBucketTagging }, { "s3:PutBucketVersioning", s3PutBucketVersioning }, { "s3:PutBucketWebsite", s3PutBucketWebsite }, { "s3:PutLifecycleConfiguration", s3PutLifecycleConfiguration }, { "s3:PutBucketObjectLockConfiguration", s3PutBucketObjectLockConfiguration }, { "s3:PutObjectAcl", s3PutObjectAcl }, { "s3:PutObject", s3PutObject }, { "s3:PutObjectVersionAcl", s3PutObjectVersionAcl }, { "s3:PutObjectTagging", s3PutObjectTagging }, { "s3:PutObjectVersionTagging", s3PutObjectVersionTagging }, { "s3:PutObjectRetention", s3PutObjectRetention }, { "s3:PutObjectLegalHold", s3PutObjectLegalHold }, { "s3:BypassGovernanceRetention", s3BypassGovernanceRetention }, { "s3:PutBucketPublicAccessBlock", s3PutBucketPublicAccessBlock }, { "s3:PutPublicAccessBlock", s3PutPublicAccessBlock }, { "s3:PutReplicationConfiguration", s3PutReplicationConfiguration }, { "s3:RestoreObject", s3RestoreObject }, { "iam:PutUserPolicy", iamPutUserPolicy }, { "iam:GetUserPolicy", iamGetUserPolicy }, { "iam:DeleteUserPolicy", iamDeleteUserPolicy }, { "iam:ListUserPolicies", iamListUserPolicies }, { "iam:CreateRole", iamCreateRole}, { "iam:DeleteRole", iamDeleteRole}, { "iam:GetRole", iamGetRole}, { "iam:ModifyRoleTrustPolicy", iamModifyRoleTrustPolicy}, { "iam:ListRoles", iamListRoles}, { "iam:PutRolePolicy", iamPutRolePolicy}, { "iam:GetRolePolicy", iamGetRolePolicy}, { "iam:ListRolePolicies", iamListRolePolicies}, { "iam:DeleteRolePolicy", iamDeleteRolePolicy}, { "iam:CreateOIDCProvider", iamCreateOIDCProvider}, { "iam:DeleteOIDCProvider", iamDeleteOIDCProvider}, { "iam:GetOIDCProvider", iamGetOIDCProvider}, { "iam:ListOIDCProviders", iamListOIDCProviders}, { "iam:TagRole", iamTagRole}, { "iam:ListRoleTags", iamListRoleTags}, { "iam:UntagRole", iamUntagRole}, { "iam:UpdateRole", iamUpdateRole}, { "sts:AssumeRole", stsAssumeRole}, { "sts:AssumeRoleWithWebIdentity", stsAssumeRoleWithWebIdentity}, { "sts:GetSessionToken", stsGetSessionToken}, { "sts:TagSession", stsTagSession}, }; struct PolicyParser; const Keyword top[1]{{"<Top>", TokenKind::pseudo, TokenID::Top, 0, false, false}}; const Keyword cond_key[1]{{"<Condition Key>", TokenKind::cond_key, TokenID::CondKey, 0, true, false}}; struct ParseState { PolicyParser* pp; const Keyword* w; bool arraying = false; bool objecting = false; bool cond_ifexists = false; void reset(); void annotate(std::string&& a); boost::optional<Principal> parse_principal(string&& s, string* errmsg); ParseState(PolicyParser* pp, const Keyword* w) : pp(pp), w(w) {} bool obj_start(); bool obj_end(); bool array_start() { if (w->arrayable && !arraying) { arraying = true; return true; } annotate(fmt::format("`{}` does not take array.", w->name)); return false; } bool array_end(); bool key(const char* s, size_t l); bool do_string(CephContext* cct, const char* s, size_t l); bool number(const char* str, size_t l); }; // If this confuses you, look up the Curiously Recurring Template Pattern struct PolicyParser : public BaseReaderHandler<UTF8<>, PolicyParser> { keyword_hash tokens; std::vector<ParseState> s; CephContext* cct; const string& tenant; Policy& policy; uint32_t v = 0; const bool reject_invalid_principals; uint32_t seen = 0; std::string annotation{"No error?"}; uint32_t dex(TokenID in) const { switch (in) { case TokenID::Version: return 0x1; case TokenID::Id: return 0x2; case TokenID::Statement: return 0x4; case TokenID::Sid: return 0x8; case TokenID::Effect: return 0x10; case TokenID::Principal: return 0x20; case TokenID::NotPrincipal: return 0x40; case TokenID::Action: return 0x80; case TokenID::NotAction: return 0x100; case TokenID::Resource: return 0x200; case TokenID::NotResource: return 0x400; case TokenID::Condition: return 0x800; case TokenID::AWS: return 0x1000; case TokenID::Federated: return 0x2000; case TokenID::Service: return 0x4000; case TokenID::CanonicalUser: return 0x8000; default: ceph_abort(); } } bool test(TokenID in) { return seen & dex(in); } void set(TokenID in) { seen |= dex(in); if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) | dex(TokenID::Principal) | dex(TokenID::NotPrincipal) | dex(TokenID::Action) | dex(TokenID::NotAction) | dex(TokenID::Resource) | dex(TokenID::NotResource) | dex(TokenID::Condition) | dex(TokenID::AWS) | dex(TokenID::Federated) | dex(TokenID::Service) | dex(TokenID::CanonicalUser))) { v |= dex(in); } } void set(std::initializer_list<TokenID> l) { for (auto in : l) { seen |= dex(in); if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) | dex(TokenID::Principal) | dex(TokenID::NotPrincipal) | dex(TokenID::Action) | dex(TokenID::NotAction) | dex(TokenID::Resource) | dex(TokenID::NotResource) | dex(TokenID::Condition) | dex(TokenID::AWS) | dex(TokenID::Federated) | dex(TokenID::Service) | dex(TokenID::CanonicalUser))) { v |= dex(in); } } } void reset(TokenID in) { seen &= ~dex(in); if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) | dex(TokenID::Principal) | dex(TokenID::NotPrincipal) | dex(TokenID::Action) | dex(TokenID::NotAction) | dex(TokenID::Resource) | dex(TokenID::NotResource) | dex(TokenID::Condition) | dex(TokenID::AWS) | dex(TokenID::Federated) | dex(TokenID::Service) | dex(TokenID::CanonicalUser))) { v &= ~dex(in); } } void reset(std::initializer_list<TokenID> l) { for (auto in : l) { seen &= ~dex(in); if (dex(in) & (dex(TokenID::Sid) | dex(TokenID::Effect) | dex(TokenID::Principal) | dex(TokenID::NotPrincipal) | dex(TokenID::Action) | dex(TokenID::NotAction) | dex(TokenID::Resource) | dex(TokenID::NotResource) | dex(TokenID::Condition) | dex(TokenID::AWS) | dex(TokenID::Federated) | dex(TokenID::Service) | dex(TokenID::CanonicalUser))) { v &= ~dex(in); } } } void reset(uint32_t& v) { seen &= ~v; v = 0; } PolicyParser(CephContext* cct, const string& tenant, Policy& policy, bool reject_invalid_principals) : cct(cct), tenant(tenant), policy(policy), reject_invalid_principals(reject_invalid_principals) {} PolicyParser(const PolicyParser& policy) = delete; bool StartObject() { if (s.empty()) { s.push_back({this, top}); s.back().objecting = true; return true; } return s.back().obj_start(); } bool EndObject(SizeType memberCount) { if (s.empty()) { annotation = "Attempt to end unopened object at top level."; return false; } return s.back().obj_end(); } bool Key(const char* str, SizeType length, bool copy) { if (s.empty()) { annotation = "Key not allowed at top level."; return false; } return s.back().key(str, length); } bool String(const char* str, SizeType length, bool copy) { if (s.empty()) { annotation = "String not allowed at top level."; return false; } return s.back().do_string(cct, str, length); } bool RawNumber(const char* str, SizeType length, bool copy) { if (s.empty()) { annotation = "Number not allowed at top level."; return false; } return s.back().number(str, length); } bool StartArray() { if (s.empty()) { annotation = "Array not allowed at top level."; return false; } return s.back().array_start(); } bool EndArray(SizeType) { if (s.empty()) { return false; } return s.back().array_end(); } bool Default() { return false; } }; // I really despise this misfeature of C++. // void ParseState::annotate(std::string&& a) { pp->annotation = std::move(a); } bool ParseState::obj_end() { if (objecting) { objecting = false; if (!arraying) { pp->s.pop_back(); } else { reset(); } return true; } annotate( fmt::format("Attempt to end unopened object on keyword `{}`.", w->name)); return false; } bool ParseState::key(const char* s, size_t l) { auto token_len = l; bool ifexists = false; if (w->id == TokenID::Condition && w->kind == TokenKind::statement) { static constexpr char IfExists[] = "IfExists"; if (boost::algorithm::ends_with(std::string_view{s, l}, IfExists)) { ifexists = true; token_len -= sizeof(IfExists)-1; } } auto k = pp->tokens.lookup(s, token_len); if (!k) { if (w->kind == TokenKind::cond_op) { auto id = w->id; auto& t = pp->policy.statements.back(); auto c_ife = cond_ifexists; pp->s.emplace_back(pp, cond_key); t.conditions.emplace_back(id, s, l, c_ife); return true; } else { annotate(fmt::format("Unknown key `{}`.", std::string_view{s, token_len})); return false; } } // If the token we're going with belongs within the condition at the // top of the stack and we haven't already encountered it, push it // on the stack // Top if ((((w->id == TokenID::Top) && (k->kind == TokenKind::top)) || // Statement ((w->id == TokenID::Statement) && (k->kind == TokenKind::statement)) || /// Principal ((w->id == TokenID::Principal || w->id == TokenID::NotPrincipal) && (k->kind == TokenKind::princ_type))) && // Check that it hasn't been encountered. Note that this // conjoins with the run of disjunctions above. !pp->test(k->id)) { pp->set(k->id); pp->s.emplace_back(pp, k); return true; } else if ((w->id == TokenID::Condition) && (k->kind == TokenKind::cond_op)) { pp->s.emplace_back(pp, k); pp->s.back().cond_ifexists = ifexists; return true; } annotate(fmt::format("Token `{}` is not allowed in the context of `{}`.", k->name, w->name)); return false; } // I should just rewrite a few helper functions to use iterators, // which will make all of this ever so much nicer. boost::optional<Principal> ParseState::parse_principal(string&& s, string* errmsg) { if ((w->id == TokenID::AWS) && (s == "*")) { // Wildcard! return Principal::wildcard(); } else if (w->id == TokenID::CanonicalUser) { // Do nothing for now. if (errmsg) *errmsg = "RGW does not support canonical users."; return boost::none; } else if (w->id == TokenID::AWS || w->id == TokenID::Federated) { // AWS and Federated ARNs if (auto a = ARN::parse(s)) { if (a->resource == "root") { return Principal::tenant(std::move(a->account)); } static const char rx_str[] = "([^/]*)/(.*)"; static const regex rx(rx_str, sizeof(rx_str) - 1, std::regex_constants::ECMAScript | std::regex_constants::optimize); smatch match; if (regex_match(a->resource, match, rx) && match.size() == 3) { if (match[1] == "user") { return Principal::user(std::move(a->account), match[2]); } if (match[1] == "role") { return Principal::role(std::move(a->account), match[2]); } if (match[1] == "oidc-provider") { return Principal::oidc_provider(std::move(match[2])); } if (match[1] == "assumed-role") { return Principal::assumed_role(std::move(a->account), match[2]); } } } else if (std::none_of(s.begin(), s.end(), [](const char& c) { return (c == ':') || (c == '/'); })) { // Since tenants are simply prefixes, there's no really good // way to see if one exists or not. So we return the thing and // let them try to match against it. return Principal::tenant(std::move(s)); } if (errmsg) *errmsg = fmt::format( "`{}` is not a supported AWS or Federated ARN. Supported ARNs are " "forms like: " "`arn:aws:iam::tenant:root` or a bare tenant name for a tenant, " "`arn:aws:iam::tenant:role/role-name` for a role, " "`arn:aws:sts::tenant:assumed-role/role-name/role-session-name` " "for an assumed role, " "`arn:aws:iam::tenant:user/user-name` for a user, " "`arn:aws:iam::tenant:oidc-provider/idp-url` for OIDC.", s); } if (errmsg) *errmsg = fmt::format("RGW does not support principals of type `{}`.", w->name); return boost::none; } bool ParseState::do_string(CephContext* cct, const char* s, size_t l) { auto k = pp->tokens.lookup(s, l); Policy& p = pp->policy; bool is_action = false; bool is_validaction = false; Statement* t = p.statements.empty() ? nullptr : &(p.statements.back()); // Top level! if (w->id == TokenID::Version) { if (k && k->kind == TokenKind::version_key) { p.version = static_cast<Version>(k->specific); } else { annotate( fmt::format("`{}` is not a valid version. Valid versions are " "`2008-10-17` and `2012-10-17`.", std::string_view{s, l})); return false; } } else if (w->id == TokenID::Id) { p.id = string(s, l); // Statement } else if (w->id == TokenID::Sid) { t->sid.emplace(s, l); } else if (w->id == TokenID::Effect) { if (k && k->kind == TokenKind::effect_key) { t->effect = static_cast<Effect>(k->specific); } else { annotate(fmt::format("`{}` is not a valid effect.", std::string_view{s, l})); return false; } } else if (w->id == TokenID::Principal && s && *s == '*') { t->princ.emplace(Principal::wildcard()); } else if (w->id == TokenID::NotPrincipal && s && *s == '*') { t->noprinc.emplace(Principal::wildcard()); } else if ((w->id == TokenID::Action) || (w->id == TokenID::NotAction)) { is_action = true; if (*s == '*') { is_validaction = true; (w->id == TokenID::Action ? t->action = allValue : t->notaction = allValue); } else { for (auto& p : actpairs) { if (match_policy({s, l}, p.name, MATCH_POLICY_ACTION)) { is_validaction = true; (w->id == TokenID::Action ? t->action[p.bit] = 1 : t->notaction[p.bit] = 1); } if ((t->action & s3AllValue) == s3AllValue) { t->action[s3All] = 1; } if ((t->notaction & s3AllValue) == s3AllValue) { t->notaction[s3All] = 1; } if ((t->action & iamAllValue) == iamAllValue) { t->action[iamAll] = 1; } if ((t->notaction & iamAllValue) == iamAllValue) { t->notaction[iamAll] = 1; } if ((t->action & stsAllValue) == stsAllValue) { t->action[stsAll] = 1; } if ((t->notaction & stsAllValue) == stsAllValue) { t->notaction[stsAll] = 1; } } } } else if (w->id == TokenID::Resource || w->id == TokenID::NotResource) { auto a = ARN::parse({s, l}, true); if (!a) { annotate( fmt::format("`{}` is not a valid ARN. Resource ARNs should have a " "format like `arn:aws:s3::tenant:resource' or " "`arn:aws:s3:::resource`.", std::string_view{s, l})); return false; } // You can't specify resources for someone ELSE'S account. if (a->account.empty() || a->account == pp->tenant || a->account == "*") { if (a->account.empty() || a->account == "*") a->account = pp->tenant; (w->id == TokenID::Resource ? t->resource : t->notresource) .emplace(std::move(*a)); } else { annotate(fmt::format("Policy owned by tenant `{}` cannot grant access to " "resource owned by tenant `{}`.", pp->tenant, a->account)); return false; } } else if (w->kind == TokenKind::cond_key) { auto& t = pp->policy.statements.back(); if (l > 0 && *s == '$') { if (l >= 2 && *(s+1) == '{') { if (l > 0 && *(s+l-1) == '}') { t.conditions.back().isruntime = true; } else { annotate(fmt::format("Invalid interpolation `{}`.", std::string_view{s, l})); return false; } } else { annotate(fmt::format("Invalid interpolation `{}`.", std::string_view{s, l})); return false; } } t.conditions.back().vals.emplace_back(s, l); // Principals } else if (w->kind == TokenKind::princ_type) { if (pp->s.size() <= 1) { annotate(fmt::format("Principle isn't allowed at top level.")); return false; } auto& pri = pp->s[pp->s.size() - 2].w->id == TokenID::Principal ? t->princ : t->noprinc; string errmsg; if (auto o = parse_principal({s, l}, &errmsg)) { pri.emplace(std::move(*o)); } else if (pp->reject_invalid_principals) { annotate(std::move(errmsg)); return false; } else { ldout(cct, 0) << "Ignored principle `" << std::string_view{s, l} << "`: " << errmsg << dendl; } } else { // Failure annotate(fmt::format("`{}` is not valid in the context of `{}`.", std::string_view{s, l}, w->name)); return false; } if (!arraying) { pp->s.pop_back(); } if (is_action && !is_validaction) { annotate(fmt::format("`{}` is not a valid action.", std::string_view{s, l})); return false; } return true; } bool ParseState::number(const char* s, size_t l) { // Top level! if (w->kind == TokenKind::cond_key) { auto& t = pp->policy.statements.back(); t.conditions.back().vals.emplace_back(s, l); } else { // Failure annotate("Numbers are not allowed outside condition arguments."); return false; } if (!arraying) { pp->s.pop_back(); } return true; } void ParseState::reset() { pp->reset(pp->v); } bool ParseState::obj_start() { if (w->objectable && !objecting) { objecting = true; if (w->id == TokenID::Statement) { pp->policy.statements.emplace_back(); } return true; } annotate(fmt::format("The {} keyword cannot introduce an object.", w->name)); return false; } bool ParseState::array_end() { if (arraying && !objecting) { pp->s.pop_back(); return true; } annotate("Attempt to close unopened array."); return false; } ostream& operator <<(ostream& m, const MaskedIP& ip) { // I have a theory about why std::bitset is the way it is. if (ip.v6) { for (int i = 7; i >= 0; --i) { uint16_t hextet = 0; for (int j = 15; j >= 0; --j) { hextet |= (ip.addr[(i * 16) + j] << j); } m << hex << (unsigned int) hextet; if (i != 0) { m << ":"; } } } else { // It involves Satan. for (int i = 3; i >= 0; --i) { uint8_t b = 0; for (int j = 7; j >= 0; --j) { b |= (ip.addr[(i * 8) + j] << j); } m << (unsigned int) b; if (i != 0) { m << "."; } } } m << "/" << dec << ip.prefix; // It would explain a lot return m; } bool Condition::eval(const Environment& env) const { std::vector<std::string> runtime_vals; auto i = env.find(key); if (op == TokenID::Null) { return i == env.end() ? true : false; } if (i == env.end()) { if (op == TokenID::ForAllValuesStringEquals || op == TokenID::ForAllValuesStringEqualsIgnoreCase || op == TokenID::ForAllValuesStringLike) { return true; } else { return ifexists; } } if (isruntime) { string k = vals.back(); k.erase(0,2); //erase $, { k.erase(k.length() - 1, 1); //erase } const auto& it = env.equal_range(k); for (auto itr = it.first; itr != it.second; itr++) { runtime_vals.emplace_back(itr->second); } } const auto& s = i->second; const auto& itr = env.equal_range(key); switch (op) { // String! case TokenID::ForAnyValueStringEquals: case TokenID::StringEquals: return orrible(std::equal_to<std::string>(), itr, isruntime? runtime_vals : vals); case TokenID::StringNotEquals: return orrible(std::not_fn(std::equal_to<std::string>()), itr, isruntime? runtime_vals : vals); case TokenID::ForAnyValueStringEqualsIgnoreCase: case TokenID::StringEqualsIgnoreCase: return orrible(ci_equal_to(), itr, isruntime? runtime_vals : vals); case TokenID::StringNotEqualsIgnoreCase: return orrible(std::not_fn(ci_equal_to()), itr, isruntime? runtime_vals : vals); case TokenID::ForAnyValueStringLike: case TokenID::StringLike: return orrible(string_like(), itr, isruntime? runtime_vals : vals); case TokenID::StringNotLike: return orrible(std::not_fn(string_like()), itr, isruntime? runtime_vals : vals); case TokenID::ForAllValuesStringEquals: return andible(std::equal_to<std::string>(), itr, isruntime? runtime_vals : vals); case TokenID::ForAllValuesStringLike: return andible(string_like(), itr, isruntime? runtime_vals : vals); case TokenID::ForAllValuesStringEqualsIgnoreCase: return andible(ci_equal_to(), itr, isruntime? runtime_vals : vals); // Numeric case TokenID::NumericEquals: return shortible(std::equal_to<double>(), as_number, s, vals); case TokenID::NumericNotEquals: return shortible(std::not_fn(std::equal_to<double>()), as_number, s, vals); case TokenID::NumericLessThan: return shortible(std::less<double>(), as_number, s, vals); case TokenID::NumericLessThanEquals: return shortible(std::less_equal<double>(), as_number, s, vals); case TokenID::NumericGreaterThan: return shortible(std::greater<double>(), as_number, s, vals); case TokenID::NumericGreaterThanEquals: return shortible(std::greater_equal<double>(), as_number, s, vals); // Date! case TokenID::DateEquals: return shortible(std::equal_to<ceph::real_time>(), as_date, s, vals); case TokenID::DateNotEquals: return shortible(std::not_fn(std::equal_to<ceph::real_time>()), as_date, s, vals); case TokenID::DateLessThan: return shortible(std::less<ceph::real_time>(), as_date, s, vals); case TokenID::DateLessThanEquals: return shortible(std::less_equal<ceph::real_time>(), as_date, s, vals); case TokenID::DateGreaterThan: return shortible(std::greater<ceph::real_time>(), as_date, s, vals); case TokenID::DateGreaterThanEquals: return shortible(std::greater_equal<ceph::real_time>(), as_date, s, vals); // Bool! case TokenID::Bool: return shortible(std::equal_to<bool>(), as_bool, s, vals); // Binary! case TokenID::BinaryEquals: return shortible(std::equal_to<ceph::bufferlist>(), as_binary, s, vals); // IP Address! case TokenID::IpAddress: return shortible(std::equal_to<MaskedIP>(), as_network, s, vals); case TokenID::NotIpAddress: { auto xc = as_network(s); if (!xc) { return false; } for (const string& d : vals) { auto xd = as_network(d); if (!xd) { continue; } if (xc == xd) { return false; } } return true; } #if 0 // Amazon Resource Names! (Does S3 need this?) TokenID::ArnEquals, TokenID::ArnNotEquals, TokenID::ArnLike, TokenID::ArnNotLike, #endif default: return false; } } boost::optional<MaskedIP> Condition::as_network(const string& s) { MaskedIP m; if (s.empty()) { return boost::none; } m.v6 = (s.find(':') == string::npos) ? false : true; auto slash = s.find('/'); if (slash == string::npos) { m.prefix = m.v6 ? 128 : 32; } else { char* end = 0; m.prefix = strtoul(s.data() + slash + 1, &end, 10); if (*end != 0 || (m.v6 && m.prefix > 128) || (!m.v6 && m.prefix > 32)) { return boost::none; } } string t; auto p = &s; if (slash != string::npos) { t.assign(s, 0, slash); p = &t; } if (m.v6) { struct in6_addr a; if (inet_pton(AF_INET6, p->c_str(), static_cast<void*>(&a)) != 1) { return boost::none; } m.addr |= Address(a.s6_addr[15]) << 0; m.addr |= Address(a.s6_addr[14]) << 8; m.addr |= Address(a.s6_addr[13]) << 16; m.addr |= Address(a.s6_addr[12]) << 24; m.addr |= Address(a.s6_addr[11]) << 32; m.addr |= Address(a.s6_addr[10]) << 40; m.addr |= Address(a.s6_addr[9]) << 48; m.addr |= Address(a.s6_addr[8]) << 56; m.addr |= Address(a.s6_addr[7]) << 64; m.addr |= Address(a.s6_addr[6]) << 72; m.addr |= Address(a.s6_addr[5]) << 80; m.addr |= Address(a.s6_addr[4]) << 88; m.addr |= Address(a.s6_addr[3]) << 96; m.addr |= Address(a.s6_addr[2]) << 104; m.addr |= Address(a.s6_addr[1]) << 112; m.addr |= Address(a.s6_addr[0]) << 120; } else { struct in_addr a; if (inet_pton(AF_INET, p->c_str(), static_cast<void*>(&a)) != 1) { return boost::none; } m.addr = ntohl(a.s_addr); } return m; } namespace { const char* condop_string(const TokenID t) { switch (t) { case TokenID::StringEquals: return "StringEquals"; case TokenID::StringNotEquals: return "StringNotEquals"; case TokenID::StringEqualsIgnoreCase: return "StringEqualsIgnoreCase"; case TokenID::StringNotEqualsIgnoreCase: return "StringNotEqualsIgnoreCase"; case TokenID::StringLike: return "StringLike"; case TokenID::StringNotLike: return "StringNotLike"; // Numeric! case TokenID::NumericEquals: return "NumericEquals"; case TokenID::NumericNotEquals: return "NumericNotEquals"; case TokenID::NumericLessThan: return "NumericLessThan"; case TokenID::NumericLessThanEquals: return "NumericLessThanEquals"; case TokenID::NumericGreaterThan: return "NumericGreaterThan"; case TokenID::NumericGreaterThanEquals: return "NumericGreaterThanEquals"; case TokenID::DateEquals: return "DateEquals"; case TokenID::DateNotEquals: return "DateNotEquals"; case TokenID::DateLessThan: return "DateLessThan"; case TokenID::DateLessThanEquals: return "DateLessThanEquals"; case TokenID::DateGreaterThan: return "DateGreaterThan"; case TokenID::DateGreaterThanEquals: return "DateGreaterThanEquals"; case TokenID::Bool: return "Bool"; case TokenID::BinaryEquals: return "BinaryEquals"; case TokenID::IpAddress: return "case TokenID::IpAddress"; case TokenID::NotIpAddress: return "NotIpAddress"; case TokenID::ArnEquals: return "ArnEquals"; case TokenID::ArnNotEquals: return "ArnNotEquals"; case TokenID::ArnLike: return "ArnLike"; case TokenID::ArnNotLike: return "ArnNotLike"; case TokenID::Null: return "Null"; default: return "InvalidConditionOperator"; } } template<typename Iterator> ostream& print_array(ostream& m, Iterator begin, Iterator end) { if (begin == end) { m << "[]"; } else { m << "[ "; std::copy(begin, end, std::experimental::make_ostream_joiner(m, ", ")); m << " ]"; } return m; } template<typename Iterator> ostream& print_dict(ostream& m, Iterator begin, Iterator end) { m << "{ "; std::copy(begin, end, std::experimental::make_ostream_joiner(m, ", ")); m << " }"; return m; } } ostream& operator <<(ostream& m, const Condition& c) { m << condop_string(c.op); if (c.ifexists) { m << "IfExists"; } m << ": { " << c.key; print_array(m, c.vals.cbegin(), c.vals.cend()); return m << " }"; } Effect Statement::eval(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, uint64_t act, boost::optional<const ARN&> res, boost::optional<PolicyPrincipal&> princ_type) const { if (eval_principal(e, ida, princ_type) == Effect::Deny) { return Effect::Pass; } if (res && resource.empty() && notresource.empty()) { return Effect::Pass; } if (!res && (!resource.empty() || !notresource.empty())) { return Effect::Pass; } if (!resource.empty() && res) { if (!std::any_of(resource.begin(), resource.end(), [&res](const ARN& pattern) { return pattern.match(*res); })) { return Effect::Pass; } } else if (!notresource.empty() && res) { if (std::any_of(notresource.begin(), notresource.end(), [&res](const ARN& pattern) { return pattern.match(*res); })) { return Effect::Pass; } } if (!(action[act] == 1) || (notaction[act] == 1)) { return Effect::Pass; } if (std::all_of(conditions.begin(), conditions.end(), [&e](const Condition& c) { return c.eval(e);})) { return effect; } return Effect::Pass; } Effect Statement::eval_principal(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type) const { if (princ_type) { *princ_type = PolicyPrincipal::Other; } if (ida) { if (princ.empty() && noprinc.empty()) { return Effect::Deny; } if (ida->get_identity_type() != TYPE_ROLE && !princ.empty() && !ida->is_identity(princ)) { return Effect::Deny; } if (ida->get_identity_type() == TYPE_ROLE && !princ.empty()) { bool princ_matched = false; for (auto p : princ) { // Check each principal to determine the type of the one that has matched boost::container::flat_set<Principal> id; id.insert(p); if (ida->is_identity(id)) { if (p.is_assumed_role() || p.is_user()) { if (princ_type) *princ_type = PolicyPrincipal::Session; } else { if (princ_type) *princ_type = PolicyPrincipal::Role; } princ_matched = true; } } if (!princ_matched) { return Effect::Deny; } } else if (!noprinc.empty() && ida->is_identity(noprinc)) { return Effect::Deny; } } return Effect::Allow; } Effect Statement::eval_conditions(const Environment& e) const { if (std::all_of(conditions.begin(), conditions.end(), [&e](const Condition& c) { return c.eval(e);})) { return Effect::Allow; } return Effect::Deny; } namespace { const char* action_bit_string(uint64_t action) { switch (action) { case s3GetObject: return "s3:GetObject"; case s3GetObjectVersion: return "s3:GetObjectVersion"; case s3PutObject: return "s3:PutObject"; case s3GetObjectAcl: return "s3:GetObjectAcl"; case s3GetObjectVersionAcl: return "s3:GetObjectVersionAcl"; case s3PutObjectAcl: return "s3:PutObjectAcl"; case s3PutObjectVersionAcl: return "s3:PutObjectVersionAcl"; case s3DeleteObject: return "s3:DeleteObject"; case s3DeleteObjectVersion: return "s3:DeleteObjectVersion"; case s3ListMultipartUploadParts: return "s3:ListMultipartUploadParts"; case s3AbortMultipartUpload: return "s3:AbortMultipartUpload"; case s3GetObjectTorrent: return "s3:GetObjectTorrent"; case s3GetObjectVersionTorrent: return "s3:GetObjectVersionTorrent"; case s3RestoreObject: return "s3:RestoreObject"; case s3CreateBucket: return "s3:CreateBucket"; case s3DeleteBucket: return "s3:DeleteBucket"; case s3ListBucket: return "s3:ListBucket"; case s3ListBucketVersions: return "s3:ListBucketVersions"; case s3ListAllMyBuckets: return "s3:ListAllMyBuckets"; case s3ListBucketMultipartUploads: return "s3:ListBucketMultipartUploads"; case s3GetAccelerateConfiguration: return "s3:GetAccelerateConfiguration"; case s3PutAccelerateConfiguration: return "s3:PutAccelerateConfiguration"; case s3GetBucketAcl: return "s3:GetBucketAcl"; case s3PutBucketAcl: return "s3:PutBucketAcl"; case s3GetBucketCORS: return "s3:GetBucketCORS"; case s3PutBucketCORS: return "s3:PutBucketCORS"; case s3GetBucketEncryption: return "s3:GetBucketEncryption"; case s3PutBucketEncryption: return "s3:PutBucketEncryption"; case s3GetBucketVersioning: return "s3:GetBucketVersioning"; case s3PutBucketVersioning: return "s3:PutBucketVersioning"; case s3GetBucketRequestPayment: return "s3:GetBucketRequestPayment"; case s3PutBucketRequestPayment: return "s3:PutBucketRequestPayment"; case s3GetBucketLocation: return "s3:GetBucketLocation"; case s3GetBucketPolicy: return "s3:GetBucketPolicy"; case s3DeleteBucketPolicy: return "s3:DeleteBucketPolicy"; case s3PutBucketPolicy: return "s3:PutBucketPolicy"; case s3GetBucketNotification: return "s3:GetBucketNotification"; case s3PutBucketNotification: return "s3:PutBucketNotification"; case s3GetBucketLogging: return "s3:GetBucketLogging"; case s3PutBucketLogging: return "s3:PutBucketLogging"; case s3GetBucketTagging: return "s3:GetBucketTagging"; case s3PutBucketTagging: return "s3:PutBucketTagging"; case s3GetBucketWebsite: return "s3:GetBucketWebsite"; case s3PutBucketWebsite: return "s3:PutBucketWebsite"; case s3DeleteBucketWebsite: return "s3:DeleteBucketWebsite"; case s3GetLifecycleConfiguration: return "s3:GetLifecycleConfiguration"; case s3PutLifecycleConfiguration: return "s3:PutLifecycleConfiguration"; case s3PutReplicationConfiguration: return "s3:PutReplicationConfiguration"; case s3GetReplicationConfiguration: return "s3:GetReplicationConfiguration"; case s3DeleteReplicationConfiguration: return "s3:DeleteReplicationConfiguration"; case s3PutObjectTagging: return "s3:PutObjectTagging"; case s3PutObjectVersionTagging: return "s3:PutObjectVersionTagging"; case s3GetObjectTagging: return "s3:GetObjectTagging"; case s3GetObjectVersionTagging: return "s3:GetObjectVersionTagging"; case s3DeleteObjectTagging: return "s3:DeleteObjectTagging"; case s3DeleteObjectVersionTagging: return "s3:DeleteObjectVersionTagging"; case s3PutBucketObjectLockConfiguration: return "s3:PutBucketObjectLockConfiguration"; case s3GetBucketObjectLockConfiguration: return "s3:GetBucketObjectLockConfiguration"; case s3PutObjectRetention: return "s3:PutObjectRetention"; case s3GetObjectRetention: return "s3:GetObjectRetention"; case s3PutObjectLegalHold: return "s3:PutObjectLegalHold"; case s3GetObjectLegalHold: return "s3:GetObjectLegalHold"; case s3BypassGovernanceRetention: return "s3:BypassGovernanceRetention"; case iamPutUserPolicy: return "iam:PutUserPolicy"; case iamGetUserPolicy: return "iam:GetUserPolicy"; case iamListUserPolicies: return "iam:ListUserPolicies"; case iamDeleteUserPolicy: return "iam:DeleteUserPolicy"; case iamCreateRole: return "iam:CreateRole"; case iamDeleteRole: return "iam:DeleteRole"; case iamGetRole: return "iam:GetRole"; case iamModifyRoleTrustPolicy: return "iam:ModifyRoleTrustPolicy"; case iamListRoles: return "iam:ListRoles"; case iamPutRolePolicy: return "iam:PutRolePolicy"; case iamGetRolePolicy: return "iam:GetRolePolicy"; case iamListRolePolicies: return "iam:ListRolePolicies"; case iamDeleteRolePolicy: return "iam:DeleteRolePolicy"; case iamCreateOIDCProvider: return "iam:CreateOIDCProvider"; case iamDeleteOIDCProvider: return "iam:DeleteOIDCProvider"; case iamGetOIDCProvider: return "iam:GetOIDCProvider"; case iamListOIDCProviders: return "iam:ListOIDCProviders"; case iamTagRole: return "iam:TagRole"; case iamListRoleTags: return "iam:ListRoleTags"; case iamUntagRole: return "iam:UntagRole"; case iamUpdateRole: return "iam:UpdateRole"; case stsAssumeRole: return "sts:AssumeRole"; case stsAssumeRoleWithWebIdentity: return "sts:AssumeRoleWithWebIdentity"; case stsGetSessionToken: return "sts:GetSessionToken"; case stsTagSession: return "sts:TagSession"; } return "s3Invalid"; } ostream& print_actions(ostream& m, const Action_t a) { bool begun = false; m << "[ "; for (auto i = 0U; i < allCount; ++i) { if (a[i] == 1) { if (begun) { m << ", "; } else { begun = true; } m << action_bit_string(i); } } if (begun) { m << " ]"; } else { m << "]"; } return m; } } ostream& operator <<(ostream& m, const Statement& s) { m << "{ "; if (s.sid) { m << "Sid: " << *s.sid << ", "; } if (!s.princ.empty()) { m << "Principal: "; print_dict(m, s.princ.cbegin(), s.princ.cend()); m << ", "; } if (!s.noprinc.empty()) { m << "NotPrincipal: "; print_dict(m, s.noprinc.cbegin(), s.noprinc.cend()); m << ", "; } m << "Effect: " << (s.effect == Effect::Allow ? (const char*) "Allow" : (const char*) "Deny"); if (s.action.any() || s.notaction.any() || !s.resource.empty() || !s.notresource.empty() || !s.conditions.empty()) { m << ", "; } if (s.action.any()) { m << "Action: "; print_actions(m, s.action); if (s.notaction.any() || !s.resource.empty() || !s.notresource.empty() || !s.conditions.empty()) { m << ", "; } } if (s.notaction.any()) { m << "NotAction: "; print_actions(m, s.notaction); if (!s.resource.empty() || !s.notresource.empty() || !s.conditions.empty()) { m << ", "; } } if (!s.resource.empty()) { m << "Resource: "; print_array(m, s.resource.cbegin(), s.resource.cend()); if (!s.notresource.empty() || !s.conditions.empty()) { m << ", "; } } if (!s.notresource.empty()) { m << "NotResource: "; print_array(m, s.notresource.cbegin(), s.notresource.cend()); if (!s.conditions.empty()) { m << ", "; } } if (!s.conditions.empty()) { m << "Condition: "; print_dict(m, s.conditions.cbegin(), s.conditions.cend()); } return m << " }"; } Policy::Policy(CephContext* cct, const string& tenant, const bufferlist& _text, bool reject_invalid_principals) : text(_text.to_str()) { StringStream ss(text.data()); PolicyParser pp(cct, tenant, *this, reject_invalid_principals); auto pr = Reader{}.Parse<kParseNumbersAsStringsFlag | kParseCommentsFlag>(ss, pp); if (!pr) { throw PolicyParseException(pr, pp.annotation); } } Effect Policy::eval(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, std::uint64_t action, boost::optional<const ARN&> resource, boost::optional<PolicyPrincipal&> princ_type) const { auto allowed = false; for (auto& s : statements) { auto g = s.eval(e, ida, action, resource, princ_type); if (g == Effect::Deny) { return g; } else if (g == Effect::Allow) { allowed = true; } } return allowed ? Effect::Allow : Effect::Pass; } Effect Policy::eval_principal(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type) const { auto allowed = false; for (auto& s : statements) { auto g = s.eval_principal(e, ida, princ_type); if (g == Effect::Deny) { return g; } else if (g == Effect::Allow) { allowed = true; } } return allowed ? Effect::Allow : Effect::Deny; } Effect Policy::eval_conditions(const Environment& e) const { auto allowed = false; for (auto& s : statements) { auto g = s.eval_conditions(e); if (g == Effect::Deny) { return g; } else if (g == Effect::Allow) { allowed = true; } } return allowed ? Effect::Allow : Effect::Deny; } ostream& operator <<(ostream& m, const Policy& p) { m << "{ Version: " << (p.version == Version::v2008_10_17 ? "2008-10-17" : "2012-10-17"); if (p.id || !p.statements.empty()) { m << ", "; } if (p.id) { m << "Id: " << *p.id; if (!p.statements.empty()) { m << ", "; } } if (!p.statements.empty()) { m << "Statements: "; print_array(m, p.statements.cbegin(), p.statements.cend()); m << ", "; } return m << " }"; } static const Environment iam_all_env = { {"aws:SourceIp","1.1.1.1"}, {"aws:UserId","anonymous"}, {"s3:x-amz-server-side-encryption-aws-kms-key-id","secret"} }; struct IsPublicStatement { bool operator() (const Statement &s) const { if (s.effect == Effect::Allow) { for (const auto& p : s.princ) { if (p.is_wildcard()) { return s.eval_conditions(iam_all_env) == Effect::Allow; } } // no princ should not contain fixed values return std::none_of(s.noprinc.begin(), s.noprinc.end(), [](const rgw::auth::Principal& p) { return p.is_wildcard(); }); } return false; } }; bool is_public(const Policy& p) { return std::any_of(p.statements.begin(), p.statements.end(), IsPublicStatement()); } } // namespace IAM } // namespace rgw
44,595
25.800481
111
cc
null
ceph-main/src/rgw/rgw_iam_policy.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <bitset> #include <chrono> #include <cstdint> #include <iostream> #include <string> #include <string_view> #include <boost/algorithm/string/predicate.hpp> #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include <boost/optional.hpp> #include <boost/thread/shared_mutex.hpp> #include <boost/variant.hpp> #include <fmt/format.h> #include "common/ceph_time.h" #include "common/iso_8601.h" #include "rapidjson/error/error.h" #include "rapidjson/error/en.h" #include "rgw_acl.h" #include "rgw_basic_types.h" #include "rgw_iam_policy_keywords.h" #include "rgw_string.h" #include "rgw_arn.h" namespace rgw { namespace auth { class Identity; } } namespace rgw { namespace IAM { static constexpr std::uint64_t s3GetObject = 0; static constexpr std::uint64_t s3GetObjectVersion = 1; static constexpr std::uint64_t s3PutObject = 2; static constexpr std::uint64_t s3GetObjectAcl = 3; static constexpr std::uint64_t s3GetObjectVersionAcl = 4; static constexpr std::uint64_t s3PutObjectAcl = 5; static constexpr std::uint64_t s3PutObjectVersionAcl = 6; static constexpr std::uint64_t s3DeleteObject = 7; static constexpr std::uint64_t s3DeleteObjectVersion = 8; static constexpr std::uint64_t s3ListMultipartUploadParts = 9; static constexpr std::uint64_t s3AbortMultipartUpload = 10; static constexpr std::uint64_t s3GetObjectTorrent = 11; static constexpr std::uint64_t s3GetObjectVersionTorrent = 12; static constexpr std::uint64_t s3RestoreObject = 13; static constexpr std::uint64_t s3CreateBucket = 14; static constexpr std::uint64_t s3DeleteBucket = 15; static constexpr std::uint64_t s3ListBucket = 16; static constexpr std::uint64_t s3ListBucketVersions = 17; static constexpr std::uint64_t s3ListAllMyBuckets = 18; static constexpr std::uint64_t s3ListBucketMultipartUploads = 19; static constexpr std::uint64_t s3GetAccelerateConfiguration = 20; static constexpr std::uint64_t s3PutAccelerateConfiguration = 21; static constexpr std::uint64_t s3GetBucketAcl = 22; static constexpr std::uint64_t s3PutBucketAcl = 23; static constexpr std::uint64_t s3GetBucketCORS = 24; static constexpr std::uint64_t s3PutBucketCORS = 25; static constexpr std::uint64_t s3GetBucketVersioning = 26; static constexpr std::uint64_t s3PutBucketVersioning = 27; static constexpr std::uint64_t s3GetBucketRequestPayment = 28; static constexpr std::uint64_t s3PutBucketRequestPayment = 29; static constexpr std::uint64_t s3GetBucketLocation = 30; static constexpr std::uint64_t s3GetBucketPolicy = 31; static constexpr std::uint64_t s3DeleteBucketPolicy = 32; static constexpr std::uint64_t s3PutBucketPolicy = 33; static constexpr std::uint64_t s3GetBucketNotification = 34; static constexpr std::uint64_t s3PutBucketNotification = 35; static constexpr std::uint64_t s3GetBucketLogging = 36; static constexpr std::uint64_t s3PutBucketLogging = 37; static constexpr std::uint64_t s3GetBucketTagging = 38; static constexpr std::uint64_t s3PutBucketTagging = 39; static constexpr std::uint64_t s3GetBucketWebsite = 40; static constexpr std::uint64_t s3PutBucketWebsite = 41; static constexpr std::uint64_t s3DeleteBucketWebsite = 42; static constexpr std::uint64_t s3GetLifecycleConfiguration = 43; static constexpr std::uint64_t s3PutLifecycleConfiguration = 44; static constexpr std::uint64_t s3PutReplicationConfiguration = 45; static constexpr std::uint64_t s3GetReplicationConfiguration = 46; static constexpr std::uint64_t s3DeleteReplicationConfiguration = 47; static constexpr std::uint64_t s3GetObjectTagging = 48; static constexpr std::uint64_t s3PutObjectTagging = 49; static constexpr std::uint64_t s3DeleteObjectTagging = 50; static constexpr std::uint64_t s3GetObjectVersionTagging = 51; static constexpr std::uint64_t s3PutObjectVersionTagging = 52; static constexpr std::uint64_t s3DeleteObjectVersionTagging = 53; static constexpr std::uint64_t s3PutBucketObjectLockConfiguration = 54; static constexpr std::uint64_t s3GetBucketObjectLockConfiguration = 55; static constexpr std::uint64_t s3PutObjectRetention = 56; static constexpr std::uint64_t s3GetObjectRetention = 57; static constexpr std::uint64_t s3PutObjectLegalHold = 58; static constexpr std::uint64_t s3GetObjectLegalHold = 59; static constexpr std::uint64_t s3BypassGovernanceRetention = 60; static constexpr std::uint64_t s3GetBucketPolicyStatus = 61; static constexpr std::uint64_t s3PutPublicAccessBlock = 62; static constexpr std::uint64_t s3GetPublicAccessBlock = 63; static constexpr std::uint64_t s3DeletePublicAccessBlock = 64; static constexpr std::uint64_t s3GetBucketPublicAccessBlock = 65; static constexpr std::uint64_t s3PutBucketPublicAccessBlock = 66; static constexpr std::uint64_t s3DeleteBucketPublicAccessBlock = 67; static constexpr std::uint64_t s3GetBucketEncryption = 68; static constexpr std::uint64_t s3PutBucketEncryption = 69; static constexpr std::uint64_t s3All = 70; static constexpr std::uint64_t iamPutUserPolicy = s3All + 1; static constexpr std::uint64_t iamGetUserPolicy = s3All + 2; static constexpr std::uint64_t iamDeleteUserPolicy = s3All + 3; static constexpr std::uint64_t iamListUserPolicies = s3All + 4; static constexpr std::uint64_t iamCreateRole = s3All + 5; static constexpr std::uint64_t iamDeleteRole = s3All + 6; static constexpr std::uint64_t iamModifyRoleTrustPolicy = s3All + 7; static constexpr std::uint64_t iamGetRole = s3All + 8; static constexpr std::uint64_t iamListRoles = s3All + 9; static constexpr std::uint64_t iamPutRolePolicy = s3All + 10; static constexpr std::uint64_t iamGetRolePolicy = s3All + 11; static constexpr std::uint64_t iamListRolePolicies = s3All + 12; static constexpr std::uint64_t iamDeleteRolePolicy = s3All + 13; static constexpr std::uint64_t iamCreateOIDCProvider = s3All + 14; static constexpr std::uint64_t iamDeleteOIDCProvider = s3All + 15; static constexpr std::uint64_t iamGetOIDCProvider = s3All + 16; static constexpr std::uint64_t iamListOIDCProviders = s3All + 17; static constexpr std::uint64_t iamTagRole = s3All + 18; static constexpr std::uint64_t iamListRoleTags = s3All + 19; static constexpr std::uint64_t iamUntagRole = s3All + 20; static constexpr std::uint64_t iamUpdateRole = s3All + 21; static constexpr std::uint64_t iamAll = s3All + 22; static constexpr std::uint64_t stsAssumeRole = iamAll + 1; static constexpr std::uint64_t stsAssumeRoleWithWebIdentity = iamAll + 2; static constexpr std::uint64_t stsGetSessionToken = iamAll + 3; static constexpr std::uint64_t stsTagSession = iamAll + 4; static constexpr std::uint64_t stsAll = iamAll + 5; static constexpr std::uint64_t s3Count = s3All; static constexpr std::uint64_t allCount = stsAll + 1; using Action_t = std::bitset<allCount>; using NotAction_t = Action_t; template <size_t N> constexpr std::bitset<N> make_bitmask(size_t s) { // unfortunately none of the shift/logic operators of std::bitset have a constexpr variation return s < 64 ? std::bitset<N> ((1ULL << s) - 1) : std::bitset<N>((1ULL << 63) - 1) | make_bitmask<N> (s - 63) << 63; } template <size_t N> constexpr std::bitset<N> set_cont_bits(size_t start, size_t end) { return (make_bitmask<N>(end - start)) << start; } static const Action_t None(0); static const Action_t s3AllValue = set_cont_bits<allCount>(0,s3All); static const Action_t iamAllValue = set_cont_bits<allCount>(s3All+1,iamAll); static const Action_t stsAllValue = set_cont_bits<allCount>(iamAll+1,stsAll); static const Action_t allValue = set_cont_bits<allCount>(0,allCount); namespace { // Please update the table in doc/radosgw/s3/authentication.rst if you // modify this function. inline int op_to_perm(std::uint64_t op) { switch (op) { case s3GetObject: case s3GetObjectTorrent: case s3GetObjectVersion: case s3GetObjectVersionTorrent: case s3GetObjectTagging: case s3GetObjectVersionTagging: case s3GetObjectRetention: case s3GetObjectLegalHold: case s3ListAllMyBuckets: case s3ListBucket: case s3ListBucketMultipartUploads: case s3ListBucketVersions: case s3ListMultipartUploadParts: return RGW_PERM_READ; case s3AbortMultipartUpload: case s3CreateBucket: case s3DeleteBucket: case s3DeleteObject: case s3DeleteObjectVersion: case s3PutObject: case s3PutObjectTagging: case s3PutObjectVersionTagging: case s3DeleteObjectTagging: case s3DeleteObjectVersionTagging: case s3RestoreObject: case s3PutObjectRetention: case s3PutObjectLegalHold: case s3BypassGovernanceRetention: return RGW_PERM_WRITE; case s3GetAccelerateConfiguration: case s3GetBucketAcl: case s3GetBucketCORS: case s3GetBucketEncryption: case s3GetBucketLocation: case s3GetBucketLogging: case s3GetBucketNotification: case s3GetBucketPolicy: case s3GetBucketPolicyStatus: case s3GetBucketRequestPayment: case s3GetBucketTagging: case s3GetBucketVersioning: case s3GetBucketWebsite: case s3GetLifecycleConfiguration: case s3GetObjectAcl: case s3GetObjectVersionAcl: case s3GetReplicationConfiguration: case s3GetBucketObjectLockConfiguration: case s3GetBucketPublicAccessBlock: return RGW_PERM_READ_ACP; case s3DeleteBucketPolicy: case s3DeleteBucketWebsite: case s3DeleteReplicationConfiguration: case s3PutAccelerateConfiguration: case s3PutBucketAcl: case s3PutBucketCORS: case s3PutBucketEncryption: case s3PutBucketLogging: case s3PutBucketNotification: case s3PutBucketPolicy: case s3PutBucketRequestPayment: case s3PutBucketTagging: case s3PutBucketVersioning: case s3PutBucketWebsite: case s3PutLifecycleConfiguration: case s3PutObjectAcl: case s3PutObjectVersionAcl: case s3PutReplicationConfiguration: case s3PutBucketObjectLockConfiguration: case s3PutBucketPublicAccessBlock: return RGW_PERM_WRITE_ACP; case s3All: return RGW_PERM_FULL_CONTROL; } return RGW_PERM_INVALID; } } enum class PolicyPrincipal { Role, Session, Other }; using Environment = std::unordered_multimap<std::string, std::string>; using Address = std::bitset<128>; struct MaskedIP { bool v6; Address addr; // Since we're mapping IPv6 to IPv4 addresses, we may want to // consider making the prefix always be in terms of a v6 address // and just use the v6 bit to rewrite it as a v4 prefix for // output. unsigned int prefix; }; std::ostream& operator <<(std::ostream& m, const MaskedIP& ip); inline bool operator ==(const MaskedIP& l, const MaskedIP& r) { auto shift = std::max((l.v6 ? 128 : 32) - ((int) l.prefix), (r.v6 ? 128 : 32) - ((int) r.prefix)); ceph_assert(shift >= 0); return (l.addr >> shift) == (r.addr >> shift); } struct Condition { TokenID op; // Originally I was going to use a perfect hash table, but Marcus // says keys are to be added at run-time not compile time. // In future development, use symbol internment. std::string key; bool ifexists = false; bool isruntime = false; //Is evaluated during run-time // Much to my annoyance there is no actual way to do this in a // typed way that is compatible with AWS. I know this because I've // seen examples where the same value is used as a string in one // context and a date in another. std::vector<std::string> vals; Condition() = default; Condition(TokenID op, const char* s, std::size_t len, bool ifexists) : op(op), key(s, len), ifexists(ifexists) {} bool eval(const Environment& e) const; static boost::optional<double> as_number(const std::string& s) { std::size_t p = 0; try { double d = std::stod(s, &p); if (p < s.length()) { return boost::none; } return d; } catch (const std::logic_error& e) { return boost::none; } } static boost::optional<ceph::real_time> as_date(const std::string& s) { std::size_t p = 0; try { double d = std::stod(s, &p); if (p == s.length()) { return ceph::real_time( std::chrono::seconds(static_cast<uint64_t>(d)) + std::chrono::nanoseconds( static_cast<uint64_t>((d - static_cast<uint64_t>(d)) * 1000000000))); } return from_iso_8601(std::string_view(s), false); } catch (const std::logic_error& e) { return boost::none; } } static boost::optional<bool> as_bool(const std::string& s) { std::size_t p = 0; if (s.empty() || boost::iequals(s, "false")) { return false; } try { double d = std::stod(s, &p); if (p == s.length()) { return !((d == +0.0) || (d == -0.0) || std::isnan(d)); } } catch (const std::logic_error& e) { // Fallthrough } return true; } static boost::optional<ceph::bufferlist> as_binary(const std::string& s) { // In a just world ceph::bufferlist base64; // I could populate a bufferlist base64.push_back(buffer::create_static( s.length(), const_cast<char*>(s.data()))); // Yuck // From a base64 encoded std::string. ceph::bufferlist bin; try { bin.decode_base64(base64); } catch (const ceph::buffer::malformed_input& e) { return boost::none; } return bin; } static boost::optional<MaskedIP> as_network(const std::string& s); struct ci_equal_to { bool operator ()(const std::string& s1, const std::string& s2) const { return boost::iequals(s1, s2); } }; struct string_like { bool operator ()(const std::string& input, const std::string& pattern) const { return match_wildcards(pattern, input, 0); } }; struct ci_starts_with { bool operator()(const std::string& s1, const std::string& s2) const { return boost::istarts_with(s1, s2); } }; using unordered_multimap_it_pair = std::pair <std::unordered_multimap<std::string,std::string>::const_iterator, std::unordered_multimap<std::string,std::string>::const_iterator>; template<typename F> static bool andible(F&& f, const unordered_multimap_it_pair& it, const std::vector<std::string>& v) { for (auto itr = it.first; itr != it.second; itr++) { bool matched = false; for (const auto& d : v) { if (f(itr->second, d)) { matched = true; } } if (!matched) return false; } return true; } template<typename F> static bool orrible(F&& f, const unordered_multimap_it_pair& it, const std::vector<std::string>& v) { for (auto itr = it.first; itr != it.second; itr++) { for (const auto& d : v) { if (f(itr->second, d)) { return true; } } } return false; } template<typename F, typename X> static bool shortible(F&& f, X& x, const std::string& c, const std::vector<std::string>& v) { auto xc = std::forward<X>(x)(c); if (!xc) { return false; } for (const auto& d : v) { auto xd = x(d); if (!xd) { continue; } if (f(*xc, *xd)) { return true; } } return false; } template <typename F> bool has_key_p(const std::string& _key, F p) const { return p(key, _key); } template <typename F> bool has_val_p(const std::string& _val, F p) const { for (auto val : vals) { if (p(val, _val)) return true; } return false; } }; std::ostream& operator <<(std::ostream& m, const Condition& c); struct Statement { boost::optional<std::string> sid = boost::none; boost::container::flat_set<rgw::auth::Principal> princ; boost::container::flat_set<rgw::auth::Principal> noprinc; // Every statement MUST provide an effect. I just initialize it to // deny as defensive programming. Effect effect = Effect::Deny; Action_t action = 0; NotAction_t notaction = 0; boost::container::flat_set<ARN> resource; boost::container::flat_set<ARN> notresource; std::vector<Condition> conditions; Effect eval(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, std::uint64_t action, boost::optional<const ARN&> resource, boost::optional<PolicyPrincipal&> princ_type=boost::none) const; Effect eval_principal(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type=boost::none) const; Effect eval_conditions(const Environment& e) const; }; std::ostream& operator <<(std::ostream& m, const Statement& s); struct PolicyParseException : public std::exception { rapidjson::ParseResult pr; std::string msg; explicit PolicyParseException(const rapidjson::ParseResult pr, const std::string& annotation) : pr(pr), msg(fmt::format("At character offset {}, {}", pr.Offset(), (pr.Code() == rapidjson::kParseErrorTermination ? annotation : rapidjson::GetParseError_En(pr.Code())))) {} const char* what() const noexcept override { return msg.c_str(); } }; struct Policy { std::string text; Version version = Version::v2008_10_17; boost::optional<std::string> id = boost::none; std::vector<Statement> statements; // reject_invalid_principals should be set to // `cct->_conf.get_val<bool>("rgw_policy_reject_invalid_principals")` // when executing operations that *set* a bucket policy, but should // be false when reading a stored bucket policy so as not to break // backwards configuration. Policy(CephContext* cct, const std::string& tenant, const bufferlist& text, bool reject_invalid_principals); Effect eval(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, std::uint64_t action, boost::optional<const ARN&> resource, boost::optional<PolicyPrincipal&> princ_type=boost::none) const; Effect eval_principal(const Environment& e, boost::optional<const rgw::auth::Identity&> ida, boost::optional<PolicyPrincipal&> princ_type=boost::none) const; Effect eval_conditions(const Environment& e) const; template <typename F> bool has_conditional(const std::string& conditional, F p) const { for (const auto&s: statements){ if (std::any_of(s.conditions.begin(), s.conditions.end(), [&](const Condition& c) { return c.has_key_p(conditional, p);})) return true; } return false; } template <typename F> bool has_conditional_value(const std::string& conditional, F p) const { for (const auto&s: statements){ if (std::any_of(s.conditions.begin(), s.conditions.end(), [&](const Condition& c) { return c.has_val_p(conditional, p);})) return true; } return false; } bool has_conditional(const std::string& c) const { return has_conditional(c, Condition::ci_equal_to()); } bool has_partial_conditional(const std::string& c) const { return has_conditional(c, Condition::ci_starts_with()); } // Example: ${s3:ResourceTag} bool has_partial_conditional_value(const std::string& c) const { return has_conditional_value(c, Condition::ci_starts_with()); } }; std::ostream& operator <<(std::ostream& m, const Policy& p); bool is_public(const Policy& p); } }
19,086
31.908621
180
h
null
ceph-main/src/rgw/rgw_iam_policy_keywords.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once namespace rgw { namespace IAM { enum class TokenKind { pseudo, top, statement, cond_op, cond_key, version_key, effect_key, princ_type }; enum class TokenID { /// Pseudo-token Top, /// Top-level tokens Version, Id, Statement, /// Statement level tokens Sid, Effect, Principal, NotPrincipal, Action, NotAction, Resource, NotResource, Condition, /// Condition Operators! /// Any of these, except Null, can have an IfExists variant. // String! StringEquals, StringNotEquals, StringEqualsIgnoreCase, StringNotEqualsIgnoreCase, StringLike, StringNotLike, ForAllValuesStringEquals, ForAnyValueStringEquals, ForAllValuesStringLike, ForAnyValueStringLike, ForAllValuesStringEqualsIgnoreCase, ForAnyValueStringEqualsIgnoreCase, // Numeric! NumericEquals, NumericNotEquals, NumericLessThan, NumericLessThanEquals, NumericGreaterThan, NumericGreaterThanEquals, // Date! DateEquals, DateNotEquals, DateLessThan, DateLessThanEquals, DateGreaterThan, DateGreaterThanEquals, // Bool! Bool, // Binary! BinaryEquals, // IP Address! IpAddress, NotIpAddress, // Amazon Resource Names! (Does S3 need this?) ArnEquals, ArnNotEquals, ArnLike, ArnNotLike, // Null! Null, #if 0 // Keys are done at runtime now /// Condition Keys! awsCurrentTime, awsEpochTime, awsTokenIssueTime, awsMultiFactorAuthPresent, awsMultiFactorAuthAge, awsPrincipalType, awsReferer, awsSecureTransport, awsSourceArn, awsSourceIp, awsSourceVpc, awsSourceVpce, awsUserAgent, awsuserid, awsusername, s3x_amz_acl, s3x_amz_grant_permission, s3x_amz_copy_source, s3x_amz_server_side_encryption, s3x_amz_server_side_encryption_aws_kms_key_id, s3x_amz_metadata_directive, s3x_amz_storage_class, s3VersionId, s3LocationConstraint, s3prefix, s3delimiter, s3max_keys, s3signatureversion, s3authType, s3signatureAge, s3x_amz_content_sha256, #else CondKey, #endif /// /// Versions! /// v2008_10_17, v2012_10_17, /// /// Effects! /// Allow, Deny, /// Principal Types! AWS, Federated, Service, CanonicalUser }; enum class Version { v2008_10_17, v2012_10_17 }; enum class Effect { Allow, Deny, Pass }; enum class Type { string, number, date, boolean, binary, ipaddr, arn, null }; } }
2,454
16.535714
74
h
null
ceph-main/src/rgw/rgw_jsonparser.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include <errno.h> #include <string.h> #include <iostream> #include <map> #include "include/types.h" #include "common/Formatter.h" #include "common/ceph_json.h" #include "rgw_common.h" #define dout_subsys ceph_subsys_rgw using namespace std; void dump_array(JSONObj *obj) { JSONObjIter iter = obj->find_first(); for (; !iter.end(); ++iter) { JSONObj *o = *iter; cout << "data=" << o->get_data() << std::endl; } } struct Key { string user; string access_key; string secret_key; void decode_json(JSONObj *obj) { JSONDecoder::decode_json("user", user, obj); JSONDecoder::decode_json("access_key", access_key, obj); JSONDecoder::decode_json("secret_key", secret_key, obj); } }; struct UserInfo { string uid; string display_name; int max_buckets; list<Key> keys; void decode_json(JSONObj *obj) { JSONDecoder::decode_json("user_id", uid, obj); JSONDecoder::decode_json("display_name", display_name, obj); JSONDecoder::decode_json("max_buckets", max_buckets, obj); JSONDecoder::decode_json("keys", keys, obj); } }; int main(int argc, char **argv) { JSONParser parser; char buf[1024]; bufferlist bl; for (;;) { int done; int len; len = fread(buf, 1, sizeof(buf), stdin); if (ferror(stdin)) { cerr << "read error" << std::endl; exit(-1); } done = feof(stdin); bool ret = parser.parse(buf, len); if (!ret) cerr << "parse error" << std::endl; if (done) { bl.append(buf, len); break; } } JSONObjIter iter = parser.find_first(); for (; !iter.end(); ++iter) { JSONObj *obj = *iter; cout << "is_object=" << obj->is_object() << std::endl; cout << "is_array=" << obj->is_array() << std::endl; cout << "name=" << obj->get_name() << std::endl; cout << "data=" << obj->get_data() << std::endl; } iter = parser.find_first("conditions"); if (!iter.end()) { JSONObj *obj = *iter; JSONObjIter iter2 = obj->find_first(); for (; !iter2.end(); ++iter2) { JSONObj *child = *iter2; cout << "is_object=" << child->is_object() << std::endl; cout << "is_array=" << child->is_array() << std::endl; if (child->is_array()) { dump_array(child); } cout << "name=" << child->get_name() <<std::endl; cout << "data=" << child->get_data() <<std::endl; } } RGWUserInfo ui; try { ui.decode_json(&parser); } catch (const JSONDecoder::err& e) { cout << "failed to decode JSON input: " << e.what() << std::endl; exit(1); } JSONFormatter formatter(true); formatter.open_object_section("user_info"); ui.dump(&formatter); formatter.close_section(); formatter.flush(std::cout); std::cout << std::endl; }
2,902
20.664179
70
cc
null
ceph-main/src/rgw/rgw_kafka.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "rgw_kafka.h" #include "rgw_url.h" #include <librdkafka/rdkafka.h> #include "include/ceph_assert.h" #include <sstream> #include <cstring> #include <unordered_map> #include <string> #include <vector> #include <thread> #include <atomic> #include <mutex> #include <boost/lockfree/queue.hpp> #include "common/dout.h" #define dout_subsys ceph_subsys_rgw // TODO investigation, not necessarily issues: // (1) in case of single threaded writer context use spsc_queue // (2) check performance of emptying queue to local list, and go over the list and publish // (3) use std::shared_mutex (c++17) or equivalent for the connections lock // cmparisson operator between topic pointer and name bool operator==(const rd_kafka_topic_t* rkt, const std::string& name) { return name == std::string_view(rd_kafka_topic_name(rkt)); } namespace rgw::kafka { // status codes for publishing static const int STATUS_CONNECTION_CLOSED = -0x1002; static const int STATUS_QUEUE_FULL = -0x1003; static const int STATUS_MAX_INFLIGHT = -0x1004; static const int STATUS_MANAGER_STOPPED = -0x1005; static const int STATUS_CONNECTION_IDLE = -0x1006; // status code for connection opening static const int STATUS_CONF_ALLOC_FAILED = -0x2001; static const int STATUS_CONF_REPLCACE = -0x2002; static const int STATUS_OK = 0x0; // struct for holding the callback and its tag in the callback list struct reply_callback_with_tag_t { uint64_t tag; reply_callback_t cb; reply_callback_with_tag_t(uint64_t _tag, reply_callback_t _cb) : tag(_tag), cb(_cb) {} bool operator==(uint64_t rhs) { return tag == rhs; } }; typedef std::vector<reply_callback_with_tag_t> CallbackList; // struct for holding the connection state object as well as list of topics // it is used inside an intrusive ref counted pointer (boost::intrusive_ptr) // since references to deleted objects may still exist in the calling code struct connection_t { rd_kafka_t* producer = nullptr; rd_kafka_conf_t* temp_conf = nullptr; std::vector<rd_kafka_topic_t*> topics; uint64_t delivery_tag = 1; int status = STATUS_OK; CephContext* const cct; CallbackList callbacks; const std::string broker; const bool use_ssl; const bool verify_ssl; // TODO currently iognored, not supported in librdkafka v0.11.6 const boost::optional<std::string> ca_location; const std::string user; const std::string password; const boost::optional<std::string> mechanism; utime_t timestamp = ceph_clock_now(); // cleanup of all internal connection resource // the object can still remain, and internal connection // resources created again on successful reconnection void destroy(int s) { status = s; // destroy temporary conf (if connection was never established) if (temp_conf) { rd_kafka_conf_destroy(temp_conf); return; } if (!is_ok()) { // no producer, nothing to destroy return; } // wait for all remaining acks/nacks rd_kafka_flush(producer, 5*1000 /* wait for max 5 seconds */); // destroy all topics std::for_each(topics.begin(), topics.end(), [](auto topic) {rd_kafka_topic_destroy(topic);}); // destroy producer rd_kafka_destroy(producer); producer = nullptr; // fire all remaining callbacks (if not fired by rd_kafka_flush) std::for_each(callbacks.begin(), callbacks.end(), [this](auto& cb_tag) { cb_tag.cb(status); ldout(cct, 20) << "Kafka destroy: invoking callback with tag=" << cb_tag.tag << " for: " << broker << dendl; }); callbacks.clear(); delivery_tag = 1; ldout(cct, 20) << "Kafka destroy: complete for: " << broker << dendl; } bool is_ok() const { return (producer != nullptr); } // ctor for setting immutable values connection_t(CephContext* _cct, const std::string& _broker, bool _use_ssl, bool _verify_ssl, const boost::optional<const std::string&>& _ca_location, const std::string& _user, const std::string& _password, const boost::optional<const std::string&>& _mechanism) : cct(_cct), broker(_broker), use_ssl(_use_ssl), verify_ssl(_verify_ssl), ca_location(_ca_location), user(_user), password(_password), mechanism(_mechanism) {} // dtor also destroys the internals ~connection_t() { destroy(status); } }; // convert int status to string - including RGW specific values std::string status_to_string(int s) { switch (s) { case STATUS_OK: return "STATUS_OK"; case STATUS_CONNECTION_CLOSED: return "RGW_KAFKA_STATUS_CONNECTION_CLOSED"; case STATUS_QUEUE_FULL: return "RGW_KAFKA_STATUS_QUEUE_FULL"; case STATUS_MAX_INFLIGHT: return "RGW_KAFKA_STATUS_MAX_INFLIGHT"; case STATUS_MANAGER_STOPPED: return "RGW_KAFKA_STATUS_MANAGER_STOPPED"; case STATUS_CONF_ALLOC_FAILED: return "RGW_KAFKA_STATUS_CONF_ALLOC_FAILED"; case STATUS_CONF_REPLCACE: return "RGW_KAFKA_STATUS_CONF_REPLCACE"; case STATUS_CONNECTION_IDLE: return "RGW_KAFKA_STATUS_CONNECTION_IDLE"; } return std::string(rd_kafka_err2str((rd_kafka_resp_err_t)s)); } void message_callback(rd_kafka_t* rk, const rd_kafka_message_t* rkmessage, void* opaque) { ceph_assert(opaque); const auto conn = reinterpret_cast<connection_t*>(opaque); const auto result = rkmessage->err; if (!rkmessage->_private) { ldout(conn->cct, 20) << "Kafka run: n/ack received, (no callback) with result=" << result << dendl; return; } const auto tag = reinterpret_cast<uint64_t*>(rkmessage->_private); const auto& callbacks_end = conn->callbacks.end(); const auto& callbacks_begin = conn->callbacks.begin(); const auto tag_it = std::find(callbacks_begin, callbacks_end, *tag); if (tag_it != callbacks_end) { ldout(conn->cct, 20) << "Kafka run: n/ack received, invoking callback with tag=" << *tag << " and result=" << rd_kafka_err2str(result) << dendl; tag_it->cb(result); conn->callbacks.erase(tag_it); } else { // TODO add counter for acks with no callback ldout(conn->cct, 10) << "Kafka run: unsolicited n/ack received with tag=" << *tag << dendl; } delete tag; // rkmessage is destroyed automatically by librdkafka } void log_callback(const rd_kafka_t* rk, int level, const char *fac, const char *buf) { ceph_assert(rd_kafka_opaque(rk)); const auto conn = reinterpret_cast<connection_t*>(rd_kafka_opaque(rk)); if (level <= 3) ldout(conn->cct, 1) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl; else if (level <= 5) ldout(conn->cct, 2) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl; else if (level <= 6) ldout(conn->cct, 10) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl; else ldout(conn->cct, 20) << "RDKAFKA-" << level << "-" << fac << ": " << rd_kafka_name(rk) << ": " << buf << dendl; } void poll_err_callback(rd_kafka_t *rk, int err, const char *reason, void *opaque) { const auto conn = reinterpret_cast<connection_t*>(rd_kafka_opaque(rk)); ldout(conn->cct, 10) << "Kafka run: poll error(" << err << "): " << reason << dendl; } using connection_t_ptr = std::unique_ptr<connection_t>; // utility function to create a producer, when the connection object already exists bool new_producer(connection_t* conn) { // reset all status codes conn->status = STATUS_OK; char errstr[512] = {0}; conn->temp_conf = rd_kafka_conf_new(); if (!conn->temp_conf) { conn->status = STATUS_CONF_ALLOC_FAILED; return false; } // get list of brokers based on the bootsrap broker if (rd_kafka_conf_set(conn->temp_conf, "bootstrap.servers", conn->broker.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; if (conn->use_ssl) { if (!conn->user.empty()) { // use SSL+SASL if (rd_kafka_conf_set(conn->temp_conf, "security.protocol", "SASL_SSL", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK || rd_kafka_conf_set(conn->temp_conf, "sasl.username", conn->user.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK || rd_kafka_conf_set(conn->temp_conf, "sasl.password", conn->password.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured SSL+SASL security" << dendl; if (conn->mechanism) { if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", conn->mechanism->c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured SASL mechanism" << dendl; } else { if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", "PLAIN", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: using default SASL mechanism" << dendl; } } else { // use only SSL if (rd_kafka_conf_set(conn->temp_conf, "security.protocol", "SSL", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured SSL security" << dendl; } if (conn->ca_location) { if (rd_kafka_conf_set(conn->temp_conf, "ssl.ca.location", conn->ca_location->c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured CA location" << dendl; } else { ldout(conn->cct, 20) << "Kafka connect: using default CA location" << dendl; } // Note: when librdkafka.1.0 is available the following line could be uncommented instead of the callback setting call // if (rd_kafka_conf_set(conn->temp_conf, "enable.ssl.certificate.verification", "0", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured security" << dendl; } else if (!conn->user.empty()) { // use SASL+PLAINTEXT if (rd_kafka_conf_set(conn->temp_conf, "security.protocol", "SASL_PLAINTEXT", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK || rd_kafka_conf_set(conn->temp_conf, "sasl.username", conn->user.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK || rd_kafka_conf_set(conn->temp_conf, "sasl.password", conn->password.c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured SASL_PLAINTEXT" << dendl; if (conn->mechanism) { if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", conn->mechanism->c_str(), errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: successfully configured SASL mechanism" << dendl; } else { if (rd_kafka_conf_set(conn->temp_conf, "sasl.mechanism", "PLAIN", errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) goto conf_error; ldout(conn->cct, 20) << "Kafka connect: using default SASL mechanism" << dendl; } } // set the global callback for delivery success/fail rd_kafka_conf_set_dr_msg_cb(conn->temp_conf, message_callback); // set the global opaque pointer to be the connection itself rd_kafka_conf_set_opaque(conn->temp_conf, conn); // redirect kafka logs to RGW rd_kafka_conf_set_log_cb(conn->temp_conf, log_callback); // define poll callback to allow reconnect rd_kafka_conf_set_error_cb(conn->temp_conf, poll_err_callback); // create the producer if (conn->producer) { ldout(conn->cct, 5) << "Kafka connect: producer already exists. detroying the existing before creating a new one" << dendl; conn->destroy(STATUS_CONF_REPLCACE); } conn->producer = rd_kafka_new(RD_KAFKA_PRODUCER, conn->temp_conf, errstr, sizeof(errstr)); if (!conn->producer) { conn->status = rd_kafka_last_error(); ldout(conn->cct, 1) << "Kafka connect: failed to create producer: " << errstr << dendl; return false; } ldout(conn->cct, 20) << "Kafka connect: successfully created new producer" << dendl; { // set log level of producer const auto log_level = conn->cct->_conf->subsys.get_log_level(ceph_subsys_rgw); if (log_level <= 1) rd_kafka_set_log_level(conn->producer, 3); else if (log_level <= 2) rd_kafka_set_log_level(conn->producer, 5); else if (log_level <= 10) rd_kafka_set_log_level(conn->producer, 6); else rd_kafka_set_log_level(conn->producer, 7); } // conf ownership passed to producer conn->temp_conf = nullptr; return true; conf_error: conn->status = rd_kafka_last_error(); ldout(conn->cct, 1) << "Kafka connect: configuration failed: " << errstr << dendl; return false; } // struct used for holding messages in the message queue struct message_wrapper_t { std::string conn_name; std::string topic; std::string message; const reply_callback_t cb; message_wrapper_t(const std::string& _conn_name, const std::string& _topic, const std::string& _message, reply_callback_t _cb) : conn_name(_conn_name), topic(_topic), message(_message), cb(_cb) {} }; typedef std::unordered_map<std::string, connection_t_ptr> ConnectionList; typedef boost::lockfree::queue<message_wrapper_t*, boost::lockfree::fixed_sized<true>> MessageQueue; class Manager { public: const size_t max_connections; const size_t max_inflight; const size_t max_queue; const size_t max_idle_time; private: std::atomic<size_t> connection_count; bool stopped; int read_timeout_ms; ConnectionList connections; MessageQueue messages; std::atomic<size_t> queued; std::atomic<size_t> dequeued; CephContext* const cct; mutable std::mutex connections_lock; std::thread runner; // TODO use rd_kafka_produce_batch for better performance void publish_internal(message_wrapper_t* message) { const std::unique_ptr<message_wrapper_t> msg_deleter(message); const auto conn_it = connections.find(message->conn_name); if (conn_it == connections.end()) { ldout(cct, 1) << "Kafka publish: connection was deleted while message was in the queue. error: " << STATUS_CONNECTION_CLOSED << dendl; if (message->cb) { message->cb(STATUS_CONNECTION_CLOSED); } return; } auto& conn = conn_it->second; conn->timestamp = ceph_clock_now(); if (!conn->is_ok()) { // connection had an issue while message was in the queue // TODO add error stats ldout(conn->cct, 1) << "Kafka publish: producer was closed while message was in the queue. error: " << status_to_string(conn->status) << dendl; if (message->cb) { message->cb(conn->status); } return; } // create a new topic unless it was already created auto topic_it = std::find(conn->topics.begin(), conn->topics.end(), message->topic); rd_kafka_topic_t* topic = nullptr; if (topic_it == conn->topics.end()) { topic = rd_kafka_topic_new(conn->producer, message->topic.c_str(), nullptr); if (!topic) { const auto err = rd_kafka_last_error(); ldout(conn->cct, 1) << "Kafka publish: failed to create topic: " << message->topic << " error: " << status_to_string(err) << dendl; if (message->cb) { message->cb(err); } conn->destroy(err); return; } // TODO use the topics list as an LRU cache conn->topics.push_back(topic); ldout(conn->cct, 20) << "Kafka publish: successfully created topic: " << message->topic << dendl; } else { topic = *topic_it; ldout(conn->cct, 20) << "Kafka publish: reused existing topic: " << message->topic << dendl; } const auto tag = (message->cb == nullptr ? nullptr : new uint64_t(conn->delivery_tag++)); const auto rc = rd_kafka_produce( topic, // TODO: non builtin partitioning RD_KAFKA_PARTITION_UA, // make a copy of the payload // so it is safe to pass the pointer from the string RD_KAFKA_MSG_F_COPY, message->message.data(), message->message.length(), // optional key and its length nullptr, 0, // opaque data: tag, used in the global callback // in order to invoke the real callback // null if no callback exists tag); if (rc == -1) { const auto err = rd_kafka_last_error(); ldout(conn->cct, 10) << "Kafka publish: failed to produce: " << rd_kafka_err2str(err) << dendl; // TODO: dont error on full queue, and don't destroy connection, retry instead // immediatly invoke callback on error if needed if (message->cb) { message->cb(err); } conn->destroy(err); delete tag; return; } if (tag) { auto const q_len = conn->callbacks.size(); if (q_len < max_inflight) { ldout(conn->cct, 20) << "Kafka publish (with callback, tag=" << *tag << "): OK. Queue has: " << q_len << " callbacks" << dendl; conn->callbacks.emplace_back(*tag, message->cb); } else { // immediately invoke callback with error - this is not a connection error ldout(conn->cct, 1) << "Kafka publish (with callback): failed with error: callback queue full" << dendl; message->cb(STATUS_MAX_INFLIGHT); // tag will be deleted when the global callback is invoked } } else { ldout(conn->cct, 20) << "Kafka publish (no callback): OK" << dendl; } // coverity[leaked_storage:SUPPRESS] } // the managers thread: // (1) empty the queue of messages to be published // (2) loop over all connections and read acks // (3) manages deleted connections // (4) TODO reconnect on connection errors // (5) TODO cleanup timedout callbacks void run() noexcept { while (!stopped) { // publish all messages in the queue auto reply_count = 0U; const auto send_count = messages.consume_all(std::bind(&Manager::publish_internal, this, std::placeholders::_1)); dequeued += send_count; ConnectionList::iterator conn_it; ConnectionList::const_iterator end_it; { // thread safe access to the connection list // once the iterators are fetched they are guaranteed to remain valid std::lock_guard lock(connections_lock); conn_it = connections.begin(); end_it = connections.end(); } // loop over all connections to read acks for (;conn_it != end_it;) { auto& conn = conn_it->second; // Checking the connection idlesness if(conn->timestamp.sec() + max_idle_time < ceph_clock_now()) { ldout(conn->cct, 20) << "kafka run: deleting a connection due to idle behaviour: " << ceph_clock_now() << dendl; std::lock_guard lock(connections_lock); conn_it = connections.erase(conn_it); --connection_count; \ continue; } // try to reconnect the connection if it has an error if (!conn->is_ok()) { ldout(conn->cct, 10) << "Kafka run: connection status is: " << status_to_string(conn->status) << dendl; const auto& broker = conn_it->first; ldout(conn->cct, 20) << "Kafka run: retry connection" << dendl; if (new_producer(conn.get()) == false) { ldout(conn->cct, 10) << "Kafka run: connection (" << broker << ") retry failed" << dendl; // TODO: add error counter for failed retries // TODO: add exponential backoff for retries } else { ldout(conn->cct, 10) << "Kafka run: connection (" << broker << ") retry successfull" << dendl; } ++conn_it; continue; } reply_count += rd_kafka_poll(conn->producer, read_timeout_ms); // just increment the iterator ++conn_it; } // if no messages were received or published // across all connection, sleep for 100ms if (send_count == 0 && reply_count == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } } // used in the dtor for message cleanup static void delete_message(const message_wrapper_t* message) { delete message; } public: Manager(size_t _max_connections, size_t _max_inflight, size_t _max_queue, int _read_timeout_ms, CephContext* _cct) : max_connections(_max_connections), max_inflight(_max_inflight), max_queue(_max_queue), max_idle_time(30), connection_count(0), stopped(false), read_timeout_ms(_read_timeout_ms), connections(_max_connections), messages(max_queue), queued(0), dequeued(0), cct(_cct), runner(&Manager::run, this) { // The hashmap has "max connections" as the initial number of buckets, // and allows for 10 collisions per bucket before rehash. // This is to prevent rehashing so that iterators are not invalidated // when a new connection is added. connections.max_load_factor(10.0); // give the runner thread a name for easier debugging const auto rc = ceph_pthread_setname(runner.native_handle(), "kafka_manager"); ceph_assert(rc==0); } // non copyable Manager(const Manager&) = delete; const Manager& operator=(const Manager&) = delete; // stop the main thread void stop() { stopped = true; } // connect to a broker, or reuse an existing connection if already connected bool connect(std::string& broker, const std::string& url, bool use_ssl, bool verify_ssl, boost::optional<const std::string&> ca_location, boost::optional<const std::string&> mechanism) { if (stopped) { ldout(cct, 1) << "Kafka connect: manager is stopped" << dendl; return false; } std::string user; std::string password; if (!parse_url_authority(url, broker, user, password)) { // TODO: increment counter ldout(cct, 1) << "Kafka connect: URL parsing failed" << dendl; return false; } // this should be validated by the regex in parse_url() ceph_assert(user.empty() == password.empty()); if (!user.empty() && !use_ssl && !g_conf().get_val<bool>("rgw_allow_notification_secrets_in_cleartext")) { ldout(cct, 1) << "Kafka connect: user/password are only allowed over secure connection" << dendl; return false; } std::lock_guard lock(connections_lock); const auto it = connections.find(broker); // note that ssl vs. non-ssl connection to the same host are two separate conenctions if (it != connections.end()) { // connection found - return even if non-ok ldout(cct, 20) << "Kafka connect: connection found" << dendl; return it->second.get(); } // connection not found, creating a new one if (connection_count >= max_connections) { // TODO: increment counter ldout(cct, 1) << "Kafka connect: max connections exceeded" << dendl; return false; } // create_connection must always return a connection object // even if error occurred during creation. // in such a case the creation will be retried in the main thread ++connection_count; ldout(cct, 10) << "Kafka connect: new connection is created. Total connections: " << connection_count << dendl; auto conn = connections.emplace(broker, std::make_unique<connection_t>(cct, broker, use_ssl, verify_ssl, ca_location, user, password, mechanism)).first->second.get(); if (!new_producer(conn)) { ldout(cct, 10) << "Kafka connect: new connection is created. But producer creation failed. will retry" << dendl; } return true; } // TODO publish with confirm is needed in "none" case as well, cb should be invoked publish is ok (no ack) int publish(const std::string& conn_name, const std::string& topic, const std::string& message) { if (stopped) { return STATUS_MANAGER_STOPPED; } auto message_wrapper = std::make_unique<message_wrapper_t>(conn_name, topic, message, nullptr); if (messages.push(message_wrapper.get())) { std::ignore = message_wrapper.release(); ++queued; return STATUS_OK; } return STATUS_QUEUE_FULL; } int publish_with_confirm(const std::string& conn_name, const std::string& topic, const std::string& message, reply_callback_t cb) { if (stopped) { return STATUS_MANAGER_STOPPED; } auto message_wrapper = std::make_unique<message_wrapper_t>(conn_name, topic, message, cb); if (messages.push(message_wrapper.get())) { std::ignore = message_wrapper.release(); ++queued; return STATUS_OK; } return STATUS_QUEUE_FULL; } // dtor wait for thread to stop // then connection are cleaned-up ~Manager() { stopped = true; runner.join(); messages.consume_all(delete_message); } // get the number of connections size_t get_connection_count() const { return connection_count; } // get the number of in-flight messages size_t get_inflight() const { size_t sum = 0; std::lock_guard lock(connections_lock); std::for_each(connections.begin(), connections.end(), [&sum](auto& conn_pair) { sum += conn_pair.second->callbacks.size(); }); return sum; } // running counter of the queued messages size_t get_queued() const { return queued; } // running counter of the dequeued messages size_t get_dequeued() const { return dequeued; } }; // singleton manager // note that the manager itself is not a singleton, and multiple instances may co-exist // TODO make the pointer atomic in allocation and deallocation to avoid race conditions static Manager* s_manager = nullptr; static const size_t MAX_CONNECTIONS_DEFAULT = 256; static const size_t MAX_INFLIGHT_DEFAULT = 8192; static const size_t MAX_QUEUE_DEFAULT = 8192; static const int READ_TIMEOUT_MS_DEFAULT = 500; bool init(CephContext* cct) { if (s_manager) { return false; } // TODO: take conf from CephContext s_manager = new Manager(MAX_CONNECTIONS_DEFAULT, MAX_INFLIGHT_DEFAULT, MAX_QUEUE_DEFAULT, READ_TIMEOUT_MS_DEFAULT, cct); return true; } void shutdown() { delete s_manager; s_manager = nullptr; } bool connect(std::string& broker, const std::string& url, bool use_ssl, bool verify_ssl, boost::optional<const std::string&> ca_location, boost::optional<const std::string&> mechanism) { if (!s_manager) return false; return s_manager->connect(broker, url, use_ssl, verify_ssl, ca_location, mechanism); } int publish(const std::string& conn_name, const std::string& topic, const std::string& message) { if (!s_manager) return STATUS_MANAGER_STOPPED; return s_manager->publish(conn_name, topic, message); } int publish_with_confirm(const std::string& conn_name, const std::string& topic, const std::string& message, reply_callback_t cb) { if (!s_manager) return STATUS_MANAGER_STOPPED; return s_manager->publish_with_confirm(conn_name, topic, message, cb); } size_t get_connection_count() { if (!s_manager) return 0; return s_manager->get_connection_count(); } size_t get_inflight() { if (!s_manager) return 0; return s_manager->get_inflight(); } size_t get_queued() { if (!s_manager) return 0; return s_manager->get_queued(); } size_t get_dequeued() { if (!s_manager) return 0; return s_manager->get_dequeued(); } size_t get_max_connections() { if (!s_manager) return MAX_CONNECTIONS_DEFAULT; return s_manager->max_connections; } size_t get_max_inflight() { if (!s_manager) return MAX_INFLIGHT_DEFAULT; return s_manager->max_inflight; } size_t get_max_queue() { if (!s_manager) return MAX_QUEUE_DEFAULT; return s_manager->max_queue; } } // namespace kafka
28,163
36.702811
315
cc
null
ceph-main/src/rgw/rgw_kafka.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include <string> #include <functional> #include <boost/optional.hpp> #include "include/common_fwd.h" namespace rgw::kafka { // the reply callback is expected to get an integer parameter // indicating the result, and not to return anything typedef std::function<void(int)> reply_callback_t; // initialize the kafka manager bool init(CephContext* cct); // shutdown the kafka manager void shutdown(); // connect to a kafka endpoint bool connect(std::string& broker, const std::string& url, bool use_ssl, bool verify_ssl, boost::optional<const std::string&> ca_location, boost::optional<const std::string&> mechanism); // publish a message over a connection that was already created int publish(const std::string& conn_name, const std::string& topic, const std::string& message); // publish a message over a connection that was already created // and pass a callback that will be invoked (async) when broker confirms // receiving the message int publish_with_confirm(const std::string& conn_name, const std::string& topic, const std::string& message, reply_callback_t cb); // convert the integer status returned from the "publish" function to a string std::string status_to_string(int s); // number of connections size_t get_connection_count(); // return the number of messages that were sent // to broker, but were not yet acked/nacked/timedout size_t get_inflight(); // running counter of successfully queued messages size_t get_queued(); // running counter of dequeued messages size_t get_dequeued(); // number of maximum allowed connections size_t get_max_connections(); // number of maximum allowed inflight messages size_t get_max_inflight(); // maximum number of messages in the queue size_t get_max_queue(); }
1,873
26.970149
185
h